pack.lisp 58 KB
Newer Older
wlott's avatar
wlott committed
1
2
3
;;; -*- Package: C; Log: C.Log -*-
;;;
;;; **********************************************************************
ram's avatar
ram committed
4
5
6
7
;;; This code was written as part of the CMU Common Lisp project at
;;; Carnegie Mellon University, and has been placed in the public domain.
;;;
(ext:file-comment
8
  "$Header: src/compiler/pack.lisp $")
ram's avatar
ram committed
9
;;;
wlott's avatar
wlott committed
10
11
12
;;; **********************************************************************
;;;
;;;    This file contains the implementation independent code for Pack phase in
ram's avatar
ram committed
13
14
;;; the compiler.  Pack is responsible for assigning TNs to storage allocations
;;; or "register allocation".
wlott's avatar
wlott committed
15
16
17
;;;
;;; Written by Rob MacLachlan
;;;
ram's avatar
ram committed
18
(in-package "C")
19
(intl:textdomain "cmucl")
ram's avatar
ram committed
20
21

(declaim (optimize (inhibit-warnings 1)))
wlott's avatar
wlott committed
22

23
24
25
26
27
28
;;; Some parameters controlling which optimizations we attempt (for debugging.)
;;;
(defparameter pack-assign-costs t)
(defparameter pack-optimize-saves t)
(defparameter pack-save-once t)

29
30
(declaim (ftype (function (component) index) ir2-block-count))

wlott's avatar
wlott committed
31
32
33

;;;; Conflict determination:

ram's avatar
ram committed
34
(declaim (start-block offset-conflicts-in-sb conflicts-in-sc))
wlott's avatar
wlott committed
35
36
37
38
39

;;; Offset-Conflicts-In-SB  --  Internal
;;;
;;; Return true if the element at the specified offset in SB has a conflict
;;; with TN:
ram's avatar
ram committed
40
41
;;; -- If an component-live TN (:component kind), then iterate over all the
;;;    blocks.  If the element at Offset is used anywhere in any of the
42
;;;    component's blocks (always-live /= 0), then there is a conflict.
wlott's avatar
wlott committed
43
44
45
46
47
48
49
50
51
52
;;; -- If TN is global (Confs true), then iterate over the blocks TN is live in
;;;    (using TN-Global-Conflicts).  If the TN is live everywhere in the block
;;;    (:Live), then there is a conflict if the element at offset is used
;;;    anywhere in the block (Always-Live /= 0).  Otherwise, we use the local
;;;    TN number for TN in block to find whether TN has a conflict at Offset in
;;;    that block.
;;; -- If TN is local, then we just check for a conflict in the block it is
;;;    local to.
;;;
(defun offset-conflicts-in-sb (tn sb offset)
53
  (declare (type tn tn) (type finite-sb sb) (type index offset))
ram's avatar
ram committed
54
55
  (let ((confs (tn-global-conflicts tn))
	(kind (tn-kind tn)))
wlott's avatar
wlott committed
56
    (cond
ram's avatar
ram committed
57
     ((eq kind :component)
wlott's avatar
wlott committed
58
      (let ((loc-live (svref (finite-sb-always-live sb) offset)))
59
	(dotimes (i (ir2-block-count *compile-component*) nil)
ram's avatar
ram committed
60
61
	  (when (/= (sbit loc-live i) 0)
	    (return t)))))
wlott's avatar
wlott committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
     (confs
      (let ((loc-confs (svref (finite-sb-conflicts sb) offset))
	    (loc-live (svref (finite-sb-always-live sb) offset)))
	(do ((conf confs (global-conflicts-tn-next conf)))
	    ((null conf)
	     nil)
	  (let* ((block (global-conflicts-block conf))
		 (num (ir2-block-number block)))
	    (if (eq (global-conflicts-kind conf) :live)
		(when (/= (sbit loc-live num) 0)
		  (return t))
		(when (/= (sbit (svref loc-confs num)
				(global-conflicts-number conf))
			  0)
		  (return t)))))))
     (t
      (/= (sbit (svref (svref (finite-sb-conflicts sb) offset)
		       (ir2-block-number (tn-local tn)))
		(tn-local-number tn))
	  0)))))


;;; Conflicts-In-SC  --  Internal
;;;
;;;    Return true if TN has a conflict in SC at the specified offset.
;;;
(defun conflicts-in-sc (tn sc offset)
89
  (declare (type tn tn) (type sc sc) (type index offset))
wlott's avatar
wlott committed
90
91
92
93
94
  (let ((sb (sc-sb sc)))
    (dotimes (i (sc-element-size sc) nil)
      (when (offset-conflicts-in-sb tn sb (+ offset i))
	(return t)))))

ram's avatar
ram committed
95
(declaim (end-block))
wlott's avatar
wlott committed
96
97
98
99
100
101

;;; Add-Location-Conflicts  --  Internal
;;;
;;;    Add TN's conflicts into the conflicts for the location at Offset in SC.
;;; We iterate over each location in TN, adding to the conflicts for that
;;; location:
ram's avatar
ram committed
102
103
104
105
;;; -- If TN is a :Component TN, then iterate over all the blocks, setting
;;;    all of the local conflict bits and the always-live bit.  This records a
;;;    conflict with any TN that has a LTN number in the block, as well as with
;;;    :Always-Live and :Environment TNs.
wlott's avatar
wlott committed
106
107
108
109
110
111
112
113
114
;;; -- If TN is global, then iterate over the blocks TN is live in.  In
;;;    addition to setting the always-live bit to represent the conflict with
;;;    TNs live throughout the block, we also set bits in the local conflicts.
;;;    If TN is :Always-Live in the block, we set all the bits, otherwise we or
;;;    in the local conflict bits.
;;; -- If the TN is local, then we just do the block it is local to, setting
;;;    always-live and OR'ing in the local conflicts.
;;;
(defun add-location-conflicts (tn sc offset)
115
  (declare (type tn tn) (type sc sc) (type index offset))
wlott's avatar
wlott committed
116
  (let ((confs (tn-global-conflicts tn))
ram's avatar
ram committed
117
118
	(sb (sc-sb sc))
	(kind (tn-kind tn)))
wlott's avatar
wlott committed
119
    (dotimes (i (sc-element-size sc))
ram's avatar
ram committed
120
      (declare (type index i))
wlott's avatar
wlott committed
121
122
123
124
      (let* ((this-offset (+ offset i))
	     (loc-confs (svref (finite-sb-conflicts sb) this-offset))
	     (loc-live (svref (finite-sb-always-live sb) this-offset)))
	(cond
ram's avatar
ram committed
125
	 ((eq kind :component)
126
	  (dotimes (num (ir2-block-count *compile-component*) nil)
ram's avatar
ram committed
127
	    (declare (type index num))
ram's avatar
ram committed
128
129
	    (setf (sbit loc-live num) 1)
	    (set-bit-vector (svref loc-confs num))))
wlott's avatar
wlott committed
130
131
132
133
134
135
	 (confs
	  (do ((conf confs (global-conflicts-tn-next conf)))
	      ((null conf))
	    (let* ((block (global-conflicts-block conf))
		   (num (ir2-block-number block))
		   (local-confs (svref loc-confs num)))
ram's avatar
ram committed
136
	      (declare (type local-tn-bit-vector local-confs))
wlott's avatar
wlott committed
137
138
139
140
141
142
143
	      (setf (sbit loc-live num) 1)
	      (if (eq (global-conflicts-kind conf) :live)
		  (set-bit-vector local-confs)
		  (bit-ior local-confs (global-conflicts-conflicts conf) t)))))
	 (t
	  (let ((num (ir2-block-number (tn-local tn))))
	    (setf (sbit loc-live num) 1)
ram's avatar
ram committed
144
145
	    (bit-ior (the local-tn-bit-vector (svref loc-confs num))
		     (tn-local-conflicts tn) t))))))))
wlott's avatar
wlott committed
146
147


148
149
150
151
152
153
;;; IR2-BLOCK-COUNT  --  Internal
;;;
;;;    Return the total number of IR2 blocks in Component.
;;;
(defun ir2-block-count (component)
  (declare (type component component))
154
155
156
157
158
  (do ((2block (block-info (block-next (component-head component)))
	       (ir2-block-next 2block)))
      ((null 2block)
       (error "What?  No ir2 blocks have a non-nil number?"))
    (when (ir2-block-number 2block)
159
      (return (1+ (ir2-block-number 2block))))))
160
161


wlott's avatar
wlott committed
162
163
164
165
166
167
168
;;; Init-SB-Vectors  --  Internal
;;;
;;;    Ensure that the conflicts vectors for each :Finite SB are large enough
;;; for the number of blocks allocated.  Also clear any old conflicts and reset
;;; the current size to the initial size.
;;;
(defun init-sb-vectors (component)
169
  (let ((nblocks (ir2-block-count component)))
170
    (dolist (sb (backend-sb-list *backend*))
wlott's avatar
wlott committed
171
      (unless (eq (sb-kind sb) :non-packed)
ram's avatar
ram committed
172
173
	(let* ((conflicts (finite-sb-conflicts sb))
	       (always-live (finite-sb-always-live sb))
174
175
	       (max-locs (length conflicts))
	       (last-count (finite-sb-last-block-count sb)))
176
	  (unless (zerop max-locs)
177
178
	    (let ((current-size (length (the simple-vector
					     (svref conflicts 0)))))
179
180
	      (cond
	       ((> nblocks current-size)
181
		(let ((new-size (max nblocks (* current-size 2))))
182
183
		  (declare (type index new-size))
		  (dotimes (i max-locs)
184
		    (declare (type index i))
185
		    (let ((new-vec (make-array new-size)))
186
187
188
189
190
191
192
193
194
		      (let ((old (svref conflicts i)))
			(declare (simple-vector old))
			(dotimes (j current-size)
			  (declare (type index j))
			  (setf (svref new-vec j)
				(clear-ltn-bit-vector (svref old j)))))

		      (do ((j current-size (1+ j)))
			  ((= j new-size))
195
			(declare (type index j))
196
			(setf (svref new-vec j)
197
198
			      (make-array local-tn-limit :element-type 'bit
					  :initial-element 0)))
199
		      (setf (svref conflicts i) new-vec))
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
		    (setf (svref always-live i)
			  (make-array new-size :element-type 'bit
				      :initial-element 0)))))
	       (t
		(dotimes (i (finite-sb-current-size sb))
		  (declare (type index i))
		  (let ((conf (svref conflicts i)))
		    (declare (simple-vector conf))
		    (dotimes (j last-count)
		      (declare (type index j))
		      (clear-ltn-bit-vector (svref conf j))))
		  (clear-bit-vector (svref always-live i)))))))

	  (setf (finite-sb-last-block-count sb) nblocks)
	  (setf (finite-sb-current-size sb) (sb-size sb))
	  (setf (finite-sb-last-offset sb) 0))))))
wlott's avatar
wlott committed
216
217
218
219
220
221
222
223
224


;;; Grow-SC  --  Internal
;;;
;;;    Expand the :Unbounded SB backing SC by either the initial size or the SC
;;; element size, whichever is larger.  If Needed-Size is larger, then use that
;;; size.
;;;
(defun grow-sc (sc &optional (needed-size 0))
ram's avatar
ram committed
225
  (declare (type sc sc) (type index needed-size))
wlott's avatar
wlott committed
226
227
  (let* ((sb (sc-sb sc))
	 (size (finite-sb-current-size sb))
ram's avatar
ram committed
228
	 (align-mask (1- (sc-alignment sc)))
229
230
	 (inc (max (sb-size sb)
		   (+ (sc-element-size sc)
ram's avatar
ram committed
231
		      (- (logandc2 (+ size align-mask) align-mask)
232
233
			 size))
		   (- needed-size size)))
wlott's avatar
wlott committed
234
235
	 (new-size (+ size inc))
	 (conflicts (finite-sb-conflicts sb))
236
237
	 (block-size (if (zerop (length conflicts))
			 (ir2-block-count *compile-component*)
238
			 (length (the simple-vector (svref conflicts 0))))))
ram's avatar
ram committed
239
    (declare (type index inc new-size))
wlott's avatar
wlott committed
240
241
242
243
244
245
246
    (assert (eq (sb-kind sb) :unbounded))

    (when (> new-size (length conflicts))
      (let ((new-conf (make-array new-size)))
	(replace new-conf conflicts)
	(do ((i size (1+ i)))
	    ((= i new-size))
ram's avatar
ram committed
247
	  (declare (type index i))
wlott's avatar
wlott committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
	  (let ((loc-confs (make-array block-size)))
	    (dotimes (j block-size)
	      (setf (svref loc-confs j)
		    (make-array local-tn-limit
				:initial-element 0
				:element-type 'bit)))
	    (setf (svref new-conf i) loc-confs)))
	(setf (finite-sb-conflicts sb) new-conf))
      
      (let ((new-live (make-array new-size)))
	(replace new-live (finite-sb-always-live sb))
	(do ((i size (1+ i)))
	    ((= i new-size))
	  (setf (svref new-live i)
		(make-array block-size
			    :initial-element 0
			    :element-type 'bit)))
	(setf (finite-sb-always-live sb) new-live))

      (let ((new-tns (make-array new-size :initial-element nil)))
	(replace new-tns (finite-sb-live-tns sb))
	(fill (finite-sb-live-tns sb) nil) 
	(setf (finite-sb-live-tns sb) new-tns)))

    (setf (finite-sb-current-size sb) new-size))
  (undefined-value))


;;; This variable is true whenever we are in pack (and thus the per-SB
;;; conflicts information is in use.)
;;;
(defvar *in-pack* nil)


;;; Pack-Before-GC-Hook  --  Internal
;;;
;;;    In order to prevent the conflict data structures from growing
;;; arbitrarily large, we clear them whenever a GC happens and we aren't
;;; currently in pack.  We revert to the initial number of locations and 0
;;; blocks.
;;;
(defun pack-before-gc-hook ()
  (unless *in-pack*
291
    (dolist (sb (backend-sb-list *backend*))
wlott's avatar
wlott committed
292
293
      (unless (eq (sb-kind sb) :non-packed)
	(let ((size (sb-size sb)))
toy's avatar
toy committed
294
	  (fill (finite-sb-always-live sb) nil)
wlott's avatar
wlott committed
295
296
297
	  (setf (finite-sb-always-live sb)
		(make-array size :initial-element #*))
	  
toy's avatar
toy committed
298
	  (fill (finite-sb-conflicts sb) nil)
wlott's avatar
wlott committed
299
300
301
	  (setf (finite-sb-conflicts sb)
		(make-array size :initial-element '#()))
	  
toy's avatar
toy committed
302
	  (fill (finite-sb-live-tns sb) nil)
wlott's avatar
wlott committed
303
304
305
306
307
308
309
	  (setf (finite-sb-live-tns sb)
		(make-array size :initial-element nil))))))
  (undefined-value))

(pushnew 'pack-before-gc-hook ext:*before-gc-hooks*)


ram's avatar
ram committed
310
;;;; Internal errors:
ram's avatar
ram committed
311
(declaim (optimize (inhibit-warnings 2)))
ram's avatar
ram committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342

;;; NO-LOAD-FUNCTION-ERROR  --  Internal
;;;
;;;    Give someone a hard time because there isn't any load function defined
;;; to move from Src to Dest.
;;;
(defun no-load-function-error (src dest)
  (let* ((src-sc (tn-sc src))
	 (src-name (sc-name src-sc))
	 (dest-sc (tn-sc dest))
	 (dest-name (sc-name dest-sc)))
    (cond ((eq (sb-kind (sc-sb src-sc)) :non-packed)
	   (unless (member src-sc (sc-constant-scs dest-sc))
	     (error "Loading from an invalid constant SC?~@
	             VM definition inconsistent, try recompiling."))
	   (error "No load function defined to load SC ~S ~
	           from its constant SC ~S."
		  dest-name src-name))
	  ((member src-sc (sc-alternate-scs dest-sc))
	   (error "No load function defined to load SC ~S from its ~
	           alternate SC ~S."
		  dest-name src-name))
	  ((member dest-sc (sc-alternate-scs src-sc))
	   (error "No load function defined to save SC ~S in its ~
	           alternate SC ~S."
		  src-name dest-name))
	  (t
	   (error "Loading to/from SCs that aren't alternates?~@
	           VM definition inconsistent, try recompiling.")))))


343
344
(defvar *debug-pack* nil)

ram's avatar
ram committed
345
346
347
348
349
350
351
352
353
354
355
;;; FAILED-TO-PACK-ERROR  --  Internal
;;;
;;;    Called when we failed to pack TN.  If Restricted is true, then we we
;;; restricted to pack TN in its SC. 
;;;
(defun failed-to-pack-error (tn restricted)
  (declare (type tn tn))
  (let* ((sc (tn-sc tn))
	 (scs (cons sc (sc-alternate-scs sc))))
    (cond
     (restricted
356
357
358
359
360
361
      (when *debug-pack*
	;; Useful for possibly figuring out which vop might be the
	;; source of the conflict.
	(describe tn))
      (error "Failed to pack restricted TN ~S in its SC ~S: ~S"
	     tn (sc-name sc) (tn-sc tn)))
ram's avatar
ram committed
362
363
364
365
366
367
368
369
370
371
372
373
     (t
      (assert (not (find :unbounded scs
			 :key #'(lambda (x) (sb-kind (sc-sb x))))))
      (let ((ptype (tn-primitive-type tn)))
	(cond
	 (ptype
	  (assert (member (sc-number sc) (primitive-type-scs ptype)))
	  (error "SC ~S doesn't have any :Unbounded alternate SCs, but is~@
	          a SC for primitive-type ~S."
		 (sc-name sc) (primitive-type-name ptype)))
	 (t
	  (error "SC ~S doesn't have any :Unbounded alternate SCs."
ram's avatar
ram committed
374
		 (sc-name sc)))))))))
ram's avatar
ram committed
375
376


377
378
379
380
381
382
383
384
385
386
;;; DESCRIBE-TN-USE  --  Internal
;;;
;;;    Return a list of format arguments describing how TN is used in Op's VOP.
;;;
(defun describe-tn-use (loc tn op)
  (let* ((vop (tn-ref-vop op))
	 (args (vop-args vop))
	 (results (vop-results vop))
	 (name (with-output-to-string (stream)
		 (print-tn tn stream)))
387
	 (2comp (component-info *compile-component*))
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
	 temp)
    (cond
     ((setq temp (position-in #'tn-ref-across tn args :key #'tn-ref-tn))
      `("~2D: ~A (~:R argument)" ,loc ,name ,(1+ temp)))
     ((setq temp (position-in #'tn-ref-across tn results :key #'tn-ref-tn))
      `("~2D: ~A (~:R result)" ,loc ,name ,(1+ temp)))
     ((setq temp (position-in #'tn-ref-across tn args :key #'tn-ref-load-tn))
      `("~2D: ~A (~:R argument load TN)" ,loc ,name ,(1+ temp)))
     ((setq temp (position-in #'tn-ref-across tn results :key
			      #'tn-ref-load-tn))
      `("~2D: ~A (~:R result load TN)" ,loc ,name ,(1+ temp)))
     ((setq temp (position-in #'tn-ref-across tn (vop-temps vop)
			      :key #'tn-ref-tn))
      `("~2D: ~A (temporary ~A)" ,loc ,name
	,(operand-parse-name (elt (vop-parse-temps
				   (vop-parse-or-lose
				    (vop-info-name  (vop-info vop))))
				  temp))))
406
407
     ((eq (tn-kind tn) :component)
      `("~2D: ~A (component live)" ,loc ,name))
408
409
410
411
     ((position-in #'tn-next tn (ir2-component-wired-tns 2comp))
      `("~2D: ~A (wired)" ,loc ,name))
     ((position-in #'tn-next tn (ir2-component-restricted-tns 2comp))
      `("~2D: ~A (restricted)" ,loc ,name))
412
413
414
415
     (t
      `("~2D: not referenced?" ,loc)))))


416
;;; FAILED-TO-PACK-LOAD-TN-ERROR  --  Internal
ram's avatar
ram committed
417
418
;;;
;;;    If load TN packing fails, try to give a helpful error message.  We find
419
;;; a TN in each location that conflicts, and print it.
ram's avatar
ram committed
420
;;;
421
422
(defun failed-to-pack-load-tn-error (scs op)
  (declare (list scs) (type tn-ref op))
423
424
  (collect ((used)
	    (unused))
425
426
427
428
429
    (dolist (sc scs)
      (let* ((sb (sc-sb sc))
	     (confs (finite-sb-live-tns sb)))
	(assert (eq (sb-kind sb) :finite))
	(dolist (el (sc-locations sc))
ram's avatar
ram committed
430
	  (declare (type index el))
431
432
433
	  (let ((conf (load-tn-conflicts-in-sc op sc el t)))
	    (if conf
		(used (describe-tn-use el conf op))
ram's avatar
ram committed
434
435
436
437
438
439
		(do ((i el (1+ i))
		     (end (+ el (sc-element-size sc))))
		    ((= i end)
		     (unused el))
		  (declare (type index i end))
		  (let ((victim (svref confs i)))
440
		    (when victim
ram's avatar
ram committed
441
442
		      (used (describe-tn-use el victim op))
		      (return t)))))))))
443
      
444
445
    (multiple-value-bind (arg-p n more-p costs load-scs incon)
			 (get-operand-info op)
446
447
448
449
450
451
452
453
454
455
456
457
458
459
	(declare (ignore costs load-scs))
	(assert (not more-p))
	(error "Unable to pack a Load-TN in SC ~{~A~#[~^~;, or ~:;,~]~} ~
		for the ~:R ~:[result~;argument~] to~@
		the ~S VOP,~@
		~:[since all SC elements are in use:~:{~%~@?~}~%~;~
		~:*but these SC elements are not in use:~%  ~S~%Bug?~*~]~
		~:[~;~@
		Current cost info inconsistent with that in effect at compile ~
		time.  Recompile.~%Compilation order may be incorrect.~]"
	       (mapcar #'sc-name scs)
	       n arg-p
	       (vop-info-name (vop-info (tn-ref-vop op)))
	       (unused) (used)
ram's avatar
ram committed
460
	       incon))))
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480


;;; NO-LOAD-SCS-ALLOWED-BY-PRIMITIVE-TYPE-ERROR  --  Internal
;;;
;;;    Called when none of the SCs that we can load Op into are allowed by Op's
;;; primitive-type.
;;;
(defun no-load-scs-allowed-by-primitive-type-error (ref)
  (declare (type tn-ref ref))
  (let* ((tn (tn-ref-tn ref))
	 (ptype (tn-primitive-type tn)))
    (multiple-value-bind (arg-p pos more-p costs load-scs incon)
			 (get-operand-info ref)
      (declare (ignore costs))
      (assert (not more-p))
      (error "~S is not valid as the ~:R ~:[result~;argument~] to VOP:~
              ~%  ~S,~@
	      since the TN's primitive type ~S doesn't allow any of the SCs~@
	      allowed by the operand restriction:~%  ~S~
	      ~:[~;~@
ram's avatar
ram committed
481
482
	      Current cost info inconsistent with that in effect at compile ~
	      time.  Recompile.~%Compilation order may be incorrect.~]"
483
484
485
486
	     tn pos arg-p
	     (template-name (vop-info (tn-ref-vop ref)))
	     (primitive-type-name ptype)
	     (mapcar #'sc-name (listify-restrictions load-scs))
ram's avatar
ram committed
487
488
489
	     incon))))

(declaim (optimize (inhibit-warnings 1)))
wlott's avatar
wlott committed
490
491
492
493


;;;; Register saving:

ram's avatar
ram committed
494
495
(declaim (start-block optimized-emit-saves emit-saves assign-tn-costs
		      pack-save-tn))
496

497
498
499
500
501
502
503
504
505
506
507
508
;;; Note-Spilled-TN  --  Internal
;;;
;;;    Do stuff to note that TN is spilled at VOP for the debugger's benefit.
;;;
(defun note-spilled-tn (tn vop)
  (when (and (tn-leaf tn) (vop-save-set vop))
    (let ((2comp (component-info *compile-component*)))
      (setf (gethash tn (ir2-component-spilled-tns 2comp)) t)
      (pushnew tn (gethash vop (ir2-component-spilled-vops 2comp)))))
  (undefined-value))


wlott's avatar
wlott committed
509
510
511
512
513
514
515
;;; Pack-Save-TN  --  Internal
;;;
;;;    Make a save TN for TN, pack it, and return it.  We copy various conflict
;;; information from the TN so that pack does the right thing.
;;;    
(defun pack-save-tn (tn)
  (declare (type tn tn))
ram's avatar
ram committed
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
  (let ((res (make-tn 0 :save nil nil)))
    (dolist (alt (sc-alternate-scs (tn-sc tn))
		 (error "No unbounded alternate for SC ~S."
			(sc-name (tn-sc tn))))
      (when (eq (sb-kind (sc-sb alt)) :unbounded)
	(setf (tn-save-tn tn) res)
	(setf (tn-save-tn res) tn)
	(setf (tn-sc res) alt)
	(pack-tn res t)
	(return res)))))


;;; EMIT-OPERAND-LOAD  --  Internal
;;;
;;;    Find the load function for moving from Src to Dest and emit a
;;; MOVE-OPERAND VOP with that function as its info arg.
;;;
533
(defun emit-operand-load (node block src dest before)
ram's avatar
ram committed
534
  (declare (type node node) (type ir2-block block)
535
	   (type tn src dest) (type (or vop null) before))
ram's avatar
ram committed
536
  (emit-load-template node block
537
		      (template-or-lose 'move-operand *backend*)
ram's avatar
ram committed
538
		      src dest
539
		      (list (or (svref (sc-move-functions (tn-sc dest))
ram's avatar
ram committed
540
541
				       (sc-number (tn-sc src)))
				(no-load-function-error src dest)))
542
		      before)
ram's avatar
ram committed
543
  (undefined-value))
wlott's avatar
wlott committed
544

545
546
547
548
549
550
551

;;; REVERSE-FIND-VOP  --  Internal
;;;
;;;    Find the preceding use of the VOP NAME in the emit order, starting with
;;; VOP.  We must find the VOP in the same IR1 block.
;;;
(defun reverse-find-vop (name vop)
552
553
554
  (do* ((block (vop-block vop) (ir2-block-prev block))
	(last vop (ir2-block-last-vop block)))
       (nil)
555
    (assert (eq (ir2-block-block block) (ir2-block-block (vop-block vop))))
556
    (do ((current last (vop-prev current)))
557
558
559
560
561
	((null current))
      (when (eq (vop-info-name (vop-info current)) name)
	(return-from reverse-find-vop current)))))


wlott's avatar
wlott committed
562
563
564
;;; Save-Complex-Writer-TN  --  Internal
;;;
;;;    For TNs that have other than one writer, we save the TN before each
565
566
567
568
569
;;; call.  If a local call (MOVE-ARGS is :LOCAL-CALL), then we scan back for
;;; the ALLOCATE-FRAME VOP, and emit the save there.  This is necessary because
;;; in a self-recursive local call, the registers holding the current arguments
;;; may get trashed by setting up the call arguments.  The ALLOCATE-FRAME VOP
;;; marks a place at which the values are known to be good.
wlott's avatar
wlott committed
570
571
572
573
574
575
576
;;;
(defun save-complex-writer-tn (tn vop)
  (let ((save (or (tn-save-tn tn)
		  (pack-save-tn tn)))
	(node (vop-node vop))
	(block (vop-block vop))
	(next (vop-next vop)))
577
578
579
580
581
582
583
584
    (when (eq (tn-kind save) :specified-save)
      (setf (tn-kind save) :save))
    (assert (eq (tn-kind save) :save))
    (emit-operand-load node block tn save
		       (if (eq (vop-info-move-args (vop-info vop))
			       :local-call)
			   (reverse-find-vop 'allocate-frame vop)
			   vop))
ram's avatar
ram committed
585
    (emit-operand-load node block save tn next)))
wlott's avatar
wlott committed
586
587


588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
;;; FIND-SINGLE-WRITER  --  Internal
;;;
;;;    Return a VOP after which is an o.k. place to save the value of TN.  For
;;; correctness, it is only required that this location be after any possible
;;; write and before any possible restore location.
;;;
;;;    In practice, we return the unique writer VOP, but give up if the TN is
;;; ever read by a VOP with MOVE-ARGS :LOCAL-CALL.  This prevents us from being
;;; confused by non-tail local calls.
;;;
;;; When looking for writes, we have to ignore uses of MOVE-OPERAND, since they
;;; will correspond to restores that we have already done.
;;;
(defun find-single-writer (tn)
  (declare (type tn tn))
  (do ((write (tn-writes tn) (tn-ref-next write))
       (res nil))
      ((null write)
       (when (and res
ram's avatar
ram committed
607
608
609
610
611
612
613
		  (do ((read (tn-reads tn) (tn-ref-next read)))
		      ((not read) t)
		    (when (eq (vop-info-move-args
			       (vop-info
				(tn-ref-vop read)))
			      :local-call)
		      (return nil))))
614
615
616
617
618
619
620
621
	 (tn-ref-vop res)))

    (unless (eq (vop-info-name (vop-info (tn-ref-vop write)))
		'move-operand)
      (when res (return nil))
      (setq res write))))


wlott's avatar
wlott committed
622
623
;;; Save-Single-Writer-TN  --  Internal
;;;
624
625
;;;    Try to save TN at a single location.  If we succeed, return T, otherwise
;;; NIL.
wlott's avatar
wlott committed
626
;;;
627
628
(defun save-single-writer-tn (tn)
  (declare (type tn tn))
wlott's avatar
wlott committed
629
  (let* ((old-save (tn-save-tn tn))
630
631
632
633
634
635
636
637
638
	 (save (or old-save (pack-save-tn tn)))
	 (writer (find-single-writer tn)))
    (when (and writer
	       (or (not old-save)
		   (eq (tn-kind old-save) :specified-save)))
      (emit-operand-load (vop-node writer) (vop-block writer)
			 tn save (vop-next writer))
      (setf (tn-kind save) :save-once)
      t)))
wlott's avatar
wlott committed
639
640


641
642
643
644
645
646
647
648
;;; RESTORE-SINGLE-WRITER-TN  --  Internal
;;;
;;;    Restore a TN with a :SAVE-ONCE save TN.
;;;
(defun restore-single-writer-tn (tn vop)
  (declare (type tn) (type vop vop))
  (let ((save (tn-save-tn tn)))
    (assert (eq (tn-kind save) :save-once))
ram's avatar
ram committed
649
    (emit-operand-load (vop-node vop) (vop-block vop) save tn (vop-next vop)))
wlott's avatar
wlott committed
650
651
652
  (undefined-value))


653
654
655
656
657
658
659
;;; BASIC-SAVE-TN  --  Internal
;;;
;;;    Save a single TN that needs to be saved, choosing save-once if
;;; appropriate.  This is also called by SPILL-AND-PACK-LOAD-TN.
;;;
(defun basic-save-tn (tn vop)
  (declare (type tn tn) (type vop vop))
660
661
662
663
664
665
666
  (let ((save (tn-save-tn tn)))
    (cond ((and save (eq (tn-kind save) :save-once))
	   (restore-single-writer-tn tn vop))
	  ((save-single-writer-tn tn)
	   (restore-single-writer-tn tn vop))
	  (t
	   (save-complex-writer-tn tn vop))))
667
668
669
  (undefined-value))


wlott's avatar
wlott committed
670
671
672
673
674
675
676
677
678
679
;;; Emit-Saves  --  Internal
;;;
;;;    Scan over the VOPs in Block, emiting saving code for TNs noted in the
;;; codegen info that are packed into saved SCs.
;;;
(defun emit-saves (block)
  (declare (type ir2-block block))
  (do ((vop (ir2-block-start-vop block) (vop-next vop)))
      ((null vop))
    (when (eq (vop-info-save-p (vop-info vop)) t)
680
      (do-live-tns (tn (vop-save-set vop) block)
wlott's avatar
wlott committed
681
682
	(when (and (sc-save-p (tn-sc tn))
		   (not (eq (tn-kind tn) :component)))
683
	  (basic-save-tn tn vop)))))
wlott's avatar
wlott committed
684
685
686

  (undefined-value))

687
688
689

;;;; Optimized saving:

690

691
692
693
694
;;; SAVE-IF-NECESSARY  --  Internal
;;;
;;;    Save TN if it isn't a single-writer TN that has already been saved.  If
;;; multi-write, we insert the save Before the specified VOP.  Context is a VOP
695
;;; used to tell which node/block to use for the new VOP.
696
697
698
;;;
(defun save-if-necessary (tn before context)
  (declare (type tn tn) (type (or vop null) before) (type vop context))
699
  (let ((save (tn-save-tn tn)))
700
701
    (when (eq (tn-kind save) :specified-save)
      (setf (tn-kind save) :save))
702
703
    (assert (member (tn-kind save) '(:save :save-once)))
    (unless (eq (tn-kind save) :save-once)
704
705
706
      (or (save-single-writer-tn tn)
	  (emit-operand-load (vop-node context) (vop-block context)
			     tn save before))))
707
  (undefined-value))
708

709

710
711
712
713
714
715
716
717
718
719
720
721
722
723
;;; RESTORE-TN  --  Internal
;;;
;;;    Load the TN from its save location, allocating one if necessary.  The
;;; load is inserted Before the specifier VOP.  Context is a VOP used to tell
;;; which node/block to use for the new VOP.
;;;
(defun restore-tn (tn before context)
  (declare (type tn tn) (type (or vop null) before) (type vop context))
  (let ((save (or (tn-save-tn tn) (pack-save-tn tn))))
    (emit-operand-load (vop-node context) (vop-block context)
		       save tn before))
  (undefined-value))


724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
(eval-when (compile eval)

;;; SAVE-NOTE-READ  --  Internal
;;;
;;;    Do stuff to note a read of TN, for OPTIMIZED-EMIT-SAVES-BLOCK.
;;;
(defmacro save-note-read (tn)
  `(let* ((tn ,tn)
	  (num (tn-number tn)))
     (when (and (sc-save-p (tn-sc tn))
		(zerop (sbit restores num))
		(not (eq (tn-kind tn) :component)))
       (setf (sbit restores num) 1)
       (push tn restores-list))))

); Eval-When (Compile Eval)

741
742
;;; OPTIMIZED-EMIT-SAVES-BLOCK  --  Internal
;;;
743
744
745
;;;    Start scanning backward at the end of Block, looking which TNs are live
;;; and looking for places where we have to save.  We manipulate two sets:
;;; SAVES and RESTORES.
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
;;;
;;;    SAVES is a set of all the TNs that have to be saved because they are
;;; restored after some call.  We normally delay saving until the beginning of
;;; the block, but we must save immediately if we see a write of the saved TN.
;;; We also immediately save all TNs and exit when we see a
;;; NOTE-ENVIRONMENT-START VOP, since saves can't be done before the
;;; environment is properly initialized.
;;;
;;;    RESTORES is a set of all the TNs read (and not written) between here and
;;; the next call, i.e. the set of TNs that must be restored when we reach the
;;; next (earlier) call VOP.   Unlike SAVES, this set is cleared when we do
;;; the restoring after a call.  Any TNs that were in RESTORES are moved into
;;; SAVES to ensure that they are saved at some point.
;;;
;;;    SAVES and RESTORES are represented using both a list and a bit-vector so
;;; that we can quickly iterate and test for membership.  The incoming Saves
762
;;; and Restores args are used for computing these sets (the initial contents
763
764
;;; are ignored.)
;;;
765
;;;    When we hit a VOP with :COMPUTE-ONLY Save-P (an internal error
766
;;; location), we pretend that all live TNs were read, unless (= speed 3), in
767
768
;;; which case we mark all the TNs that are live but not restored as spilled.
;;;
769
770
771
772
773
774
(defun optimized-emit-saves-block (block saves restores)
  (declare (type ir2-block block) (type simple-bit-vector saves restores))
  (let ((1block (ir2-block-block block))
	(saves-list ())
	(restores-list ())
	(skipping nil))
775
    (declare (list saves-list restores-list))
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
    (clear-bit-vector saves)
    (clear-bit-vector restores)
    (do-live-tns (tn (ir2-block-live-in block) block)
      (when (and (sc-save-p (tn-sc tn))
		 (not (eq (tn-kind tn) :component)))
	(let ((num (tn-number tn)))
	  (setf (sbit restores num) 1)
	  (push tn restores-list))))

    (do ((block block (ir2-block-prev block))
	 (prev nil block))
	((not (eq (ir2-block-block block) 1block))
	 (assert (not skipping))
	 (dolist (save saves-list)
	   (let ((start (ir2-block-start-vop prev)))
	     (save-if-necessary save start start)))
	 prev)
      (do ((vop (ir2-block-last-vop block) (vop-prev vop)))
	  ((null vop))
	(let ((info (vop-info vop)))
	  (case (vop-info-name info)
	    (allocate-frame
	     (assert skipping)
	     (setq skipping nil))
	    (note-environment-start
	     (assert (not skipping))
	     (dolist (save saves-list)
	       (save-if-necessary save (vop-next vop) vop))
	     (return-from optimized-emit-saves-block block)))
	  
	  (unless skipping
	    (do ((write (vop-results vop) (tn-ref-across write)))
		((null write))
	      (let* ((tn (tn-ref-tn write))
		     (num (tn-number tn)))
		(unless (zerop (sbit restores num))
		  (setf (sbit restores num) 0)
813
814
		  (setq restores-list
			(delete tn restores-list :test #'eq)))
815
816
817
		(unless (zerop (sbit saves num))
		  (setf (sbit saves num) 0)
		  (save-if-necessary tn (vop-next vop) vop)
818
819
		  (setq saves-list
			(delete tn saves-list :test #'eq))))))
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838

	  (case (vop-info-save-p info)
	    ((t)
	     (dolist (tn restores-list)
	       (restore-tn tn (vop-next vop) vop)
	       (let ((num (tn-number tn)))
		 (when (zerop (sbit saves num))
		   (push tn saves-list)
		   (setf (sbit saves num) 1))))
	     (setq restores-list nil)
	     (clear-bit-vector restores))
	    (:compute-only
	     (cond ((policy (vop-node vop) (= speed 3))
		    (do-live-tns (tn (vop-save-set vop) block)
		      (when (zerop (sbit restores (tn-number tn)))
			(note-spilled-tn tn vop))))
		   (t
		    (do-live-tns (tn (vop-save-set vop) block)
		      (save-note-read tn))))))
839
840
841
842
843
	  
	  (if (eq (vop-info-move-args info) :local-call)
	      (setq skipping t)
	      (do ((read (vop-args vop) (tn-ref-across read)))
		  ((null read))
844
		(save-note-read (tn-ref-tn read)))))))))
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
	

;;; OPTIMIZED-EMIT-SAVES  --  Internal
;;;
;;;    Like EMIT-SAVES, only different.  We avoid redundant saving within the
;;; block, and don't restore values that aren't used before the next call.
;;; This function is just the top-level loop over the blocks in the component,
;;; which locates blocks that need saving done.
;;;
(defun optimized-emit-saves (component)
  (declare (type component component))
  (let* ((gtn-count (1+ (ir2-component-global-tn-counter
			 (component-info component))))
	 (saves (make-array gtn-count :element-type 'bit))
	 (restores (make-array gtn-count :element-type 'bit))
	 (block (ir2-block-prev (block-info (component-tail component))))
	 (head (block-info (component-head component))))
    (loop
      (when (eq block head) (return))
      (when (do ((vop (ir2-block-start-vop block) (vop-next vop)))
		((null vop) nil)
	      (when (eq (vop-info-save-p (vop-info vop)) t)
		(return t)))
	(setq block (optimized-emit-saves-block block saves restores)))
      (setq block (ir2-block-prev block)))))


;;; ASSIGN-TN-COSTS  --  Internal
;;;
;;;    Iterate over the normal TNs, finding the cost of packing on the stack in
;;; units of the number of references.  We count all references as +1, and
;;; subtract out REGISTER-SAVE-PENALTY for each place where we would have to
;;; save a register.
;;;
(defun assign-tn-costs (component)
  (do-ir2-blocks (block component)
    (do ((vop (ir2-block-start-vop block) (vop-next vop)))
	((null vop))
      (when (eq (vop-info-save-p (vop-info vop)) t)
	(do-live-tns (tn (vop-save-set vop) block)
ram's avatar
ram committed
885
886
	  (decf (tn-cost tn)
		(the index (backend-register-save-penalty *backend*)))))))
887
888
889
890
891
892
893
894
895
896
897
898
899
900
  
  (do ((tn (ir2-component-normal-tns (component-info component))
	   (tn-next tn)))
      ((null tn))
    (let ((cost (tn-cost tn)))
      (declare (fixnum cost))
      (do ((ref (tn-reads tn) (tn-ref-next ref)))
	  ((null ref))
	(incf cost))
      (do ((ref (tn-writes tn) (tn-ref-next ref)))
	  ((null ref))
	(incf cost))
      (setf (tn-cost tn) cost))))

ram's avatar
ram committed
901
(declaim (end-block))
wlott's avatar
wlott committed
902
903
904
905


;;;; Load TN packing:

906
(declaim (start-block pack-load-tns load-tn-conflicts-in-sc))
wlott's avatar
wlott committed
907
908
909
910
911
912
913
914

;;; These variables indicate the last location at which we computed the
;;; Live-TNs.  They hold the Block and VOP values that were passed to
;;; Compute-Live-TNs.
;;;
(defvar *live-block*)
(defvar *live-vop*)

915
916
917
918
919
920
;;; If we unpack some TNs, then we mark all affected blocks by sticking them in
;;; this hash-table.  This is initially null.  We create the hashtable if we do
;;; any unpacking.
;;;
(defvar *repack-blocks*)
(declaim (type (or hash-table null) *repack-blocks*))
wlott's avatar
wlott committed
921
922
923
924
925
926
927

;;; Init-Live-TNs  --  Internal
;;;
;;;    Set the Live-TNs vectors in all :Finite SBs to represent the TNs live at
;;; the end of Block.
;;;
(defun init-live-tns (block)
928
  (dolist (sb (backend-sb-list *backend*))
wlott's avatar
wlott committed
929
930
931
    (when (eq (sb-kind sb) :finite)
      (fill (finite-sb-live-tns sb) nil)))

932
  (do-live-tns (tn (ir2-block-live-in block) block)
933
934
    (let* ((sc (tn-sc tn))
	   (sb (sc-sb sc)))
935
      (when (eq (sb-kind sb) :finite)
ram's avatar
ram committed
936
937
938
939
	(do ((offset (tn-offset tn) (1+ offset))
	     (end (+ (tn-offset tn) (sc-element-size sc))))
	    ((= offset end))
	  (declare (type index offset end))
940
	  (setf (svref (finite-sb-live-tns sb) offset) tn)))))
wlott's avatar
wlott committed
941
942
943
944
945
946
947
948
949
950

  (setq *live-block* block)
  (setq *live-vop* (ir2-block-last-vop block))

  (undefined-value))


;;; Compute-Live-TNs  --  Internal
;;;
;;;    Set the Live-TNs in :Finite SBs to represent the TNs live immediately
951
952
953
;;; after the evaluation of VOP in Block, excluding results of the VOP.  If VOP
;;; is null, then compute the live TNs at the beginning of the block.
;;; Sequential calls on the same block must be in reverse VOP order.
wlott's avatar
wlott committed
954
955
;;;
(defun compute-live-tns (block vop)
956
  (declare (type ir2-block block) (type vop vop))
wlott's avatar
wlott committed
957
958
959
960
  (unless (eq block *live-block*)
    (init-live-tns block))
  
  (do ((current *live-vop* (vop-prev current)))
961
962
963
964
      ((eq current vop)
       (do ((res (vop-results vop) (tn-ref-across res)))
	   ((null res))
	 (let* ((tn (tn-ref-tn res))
965
966
		(sc (tn-sc tn))
		(sb (sc-sb sc)))
967
	   (when (eq (sb-kind sb) :finite)
ram's avatar
ram committed
968
969
970
971
	     (do ((offset (tn-offset tn) (1+ offset))
		  (end (+ (tn-offset tn) (sc-element-size sc))))
		 ((= offset end))
	       (declare (type index offset end))
972
	       (setf (svref (finite-sb-live-tns sb) offset) nil))))))
wlott's avatar
wlott committed
973
974
    (do ((ref (vop-refs current) (tn-ref-next-ref ref)))
	((null ref))
975
976
977
978
979
980
      (let ((ltn (tn-ref-load-tn ref)))
	(when ltn
	  (let* ((sc (tn-sc ltn))
		 (sb (sc-sb sc)))
	    (when (eq (sb-kind sb) :finite)
	      (let ((tns (finite-sb-live-tns sb)))
ram's avatar
ram committed
981
982
983
984
		(do ((offset (tn-offset ltn) (1+ offset))
		     (end (+ (tn-offset ltn) (sc-element-size sc))))
		    ((= offset end))
		  (declare (type index offset end))
985
986
		  (assert (null (svref tns offset)))))))))

wlott's avatar
wlott committed
987
      (let* ((tn (tn-ref-tn ref))
988
989
	     (sc (tn-sc tn))
	     (sb (sc-sb sc)))
wlott's avatar
wlott committed
990
	(when (eq (sb-kind sb) :finite)
991
	  (let ((tns (finite-sb-live-tns sb)))
ram's avatar
ram committed
992
993
994
995
	    (do ((offset (tn-offset tn) (1+ offset))
		 (end (+ (tn-offset tn) (sc-element-size sc))))
		((= offset end))
	      (declare (type index offset end))
996
997
998
999
1000
	      (if (tn-ref-write-p ref)
		  (setf (svref tns offset) nil)
		  (let ((old (svref tns offset)))
		    (assert (or (null old) (eq old tn)) (old tn))
		    (setf (svref tns offset) tn)))))))))
wlott's avatar
wlott committed
1001
1002
1003
1004
1005

  (setq *live-vop* vop)
  (undefined-value))


1006
;;; LOAD-TN-OFFSET-CONFLICTS-IN-SB  --  Internal
wlott's avatar
wlott committed
1007
;;;
1008
1009
1010
1011
1012
;;;    Kind of like Offset-Conflicts-In-SB, except that it uses the VOP refs to
;;; determine whether a Load-TN for OP could be packed in the specified
;;; location, disregarding conflicts with TNs not referenced by this VOP.
;;; There is a conflict if either:
;;;  1] The reference is a result, and the same location is either:
1013
1014
;;;     -- Used by some other result.
;;;     -- Used in any way after the reference (exclusive).
1015
;;;  2] The reference is an argument, and the same location is either:
1016
1017
;;;     -- Used by some other argument.
;;;     -- Used in any way before the reference (exclusive).
wlott's avatar
wlott committed
1018
;;;
1019
;;;    In 1 (and 2) above, the first bullet corresponds to result-result
1020
1021
1022
;;; (and argument-argument) conflicts.  We need this case because there aren't
;;; any TN-REFs to represent the implicit reading of results or writing of
;;; arguments.
wlott's avatar
wlott committed
1023
;;;
1024
1025
;;;    The second bullet corresponds conflicts with temporaries or between
;;; arguments and results.
wlott's avatar
wlott committed
1026
;;;
1027
1028
1029
1030
1031
;;;    We consider both the TN-REF-TN and the TN-REF-LOAD-TN (if any) to be
;;; referenced simultaneously and in the same way.  This causes load-TNs to
;;; appear live to the beginning (or end) of the VOP, as appropriate.
;;;
;;; We return a conflicting TN if there is a conflict.
ram's avatar
ram committed
1032
;;;
1033
(defun load-tn-offset-conflicts-in-sb (op sb offset)
1034
  (declare (type tn-ref op) (type finite-sb sb) (type index offset))
wlott's avatar
wlott committed
1035
  (assert (eq (sb-kind sb) :finite))
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
  (let ((vop (tn-ref-vop op)))
    (labels ((tn-overlaps (tn)
	       (let ((sc (tn-sc tn))
		     (tn-offset (tn-offset tn)))
		 (when (and (eq (sc-sb sc) sb)
			    (<= tn-offset offset)
			    (< offset
			       (the index
				    (+ tn-offset (sc-element-size sc)))))
		   tn)))
	     (same (ref)
	       (let ((tn (tn-ref-tn ref))
		     (ltn (tn-ref-load-tn ref)))
		 (or (tn-overlaps tn)
		     (and ltn (tn-overlaps ltn)))))
	     (is-op (ops)
	       (do ((ops ops (tn-ref-across ops)))
		   ((null ops) nil)
1054
1055
1056
		 (let ((found (same ops)))
		   (when (and found (not (eq ops op)))
		     (return found)))))
1057
1058
1059
	     (is-ref (refs end)
	       (do ((refs refs (tn-ref-next-ref refs)))
		   ((eq refs end) nil)
1060
1061
		 (let ((found (same refs)))
		 (when found (return found))))))
1062
1063
1064
1065
1066
1067
      (declare (inline is-op is-ref tn-overlaps))
      (if (tn-ref-write-p op)
	  (or (is-op (vop-results vop))
	      (is-ref (vop-refs vop) op))
	  (or (is-op (vop-args vop))
	      (is-ref (tn-ref-next-ref op) nil))))))
wlott's avatar
wlott committed
1068
1069


1070
1071
1072
1073
1074
1075
;;; LOAD-TN-CONFLICTS-IN-SC  --  Internal
;;;
;;;    Iterate over all the elements in the SB that would be allocated by
;;; allocating a TN in SC at Offset, checking for conflict with load-TNs or
;;; other TNs (live in the LIVE-TNS, which must be set up.)  We also return
;;; true if there aren't enough locations after Offset to hold a TN in SC.
1076
1077
1078
1079
;;; If Ignore-Live is true, then we ignore the live-TNs, considering only
;;; references within Op's VOP.
;;;
;;;    We return a conflicting TN, or :OVERFLOW if the TN won't fit.
1080
;;;
1081
(defun load-tn-conflicts-in-sc (op sc offset ignore-live)
1082
1083
  (let* ((sb (sc-sb sc))
	 (size (finite-sb-current-size sb)))
ram's avatar
ram committed
1084
1085
1086
1087
1088
1089
    (do ((i offset (1+ i))
	 (end (+ offset (sc-element-size sc))))
	((= i end) nil)
      (declare (type index i end))
      (let ((res (or (when (>= i size) :overflow)
		     (and (not ignore-live)
1090
			  (svref (finite-sb-live-tns sb) i))
ram's avatar
ram committed
1091
1092
		     (load-tn-offset-conflicts-in-sb op sb i))))
	(when res (return res))))))
1093
1094


wlott's avatar
wlott committed
1095
1096
1097
1098
1099
1100
1101
;;; Find-Load-TN-Target  --  Internal
;;;
;;;    If a load-TN for Op is targeted to a legal location in SC, then return
;;; the offset, otherwise return NIL.  We see if the target of the operand is
;;; packed, and try that location.  There isn't any need to chain down the
;;; target path, since everything is packed now.
;;;
1102
1103
1104
1105
1106
1107
;;;    We require the target to be in SC (and not merely to overlap with SC).
;;; This prevents SC information from being lost in load TNs (we won't pack a
;;; load TN in ANY-REG when it is targeted to a DESCRIPTOR-REG.)  This
;;; shouldn't hurt the code as long as all relevant overlapping SCs are allowed
;;; in the operand SC restriction.
;;;
wlott's avatar
wlott committed
1108
(defun find-load-tn-target (op sc)
ram's avatar
ram committed
1109
  (declare (inline member))
wlott's avatar
wlott committed
1110
1111
1112
  (let ((target (tn-ref-target op)))
    (when target
      (let* ((tn (tn-ref-tn target))
1113
	     (loc (tn-offset tn)))
1114
	(if (and (eq (tn-sc tn) sc)
1115
		 (member (the index loc) (sc-locations sc))
1116
		 (not (load-tn-conflicts-in-sc op sc loc nil)))
wlott's avatar
wlott committed
1117
1118
1119
1120
1121
1122
1123
	    loc
	    nil)))))


;;; Select-Load-Tn-Location  --  Internal
;;;
;;;    Select a legal location for a load TN for Op in SC.  We just iterate
1124
;;; over the SC's locations.  If we can't find a legal location, return NIL.
wlott's avatar
wlott committed
1125
1126
1127
;;;
(defun select-load-tn-location (op sc)
  (declare (type tn-ref op) (type sc sc))
ram's avatar
ram committed
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138

  ;; Check any target location first.
  (let ((target (tn-ref-target op)))
    (when target
      (let* ((tn (tn-ref-tn target))
	     (loc (tn-offset tn)))
	(when (and (eq (sc-sb sc) (sc-sb (tn-sc tn)))
		   (member (the index loc) (sc-locations sc))
		   (not (load-tn-conflicts-in-sc op sc loc nil)))
	      (return-from select-load-tn-location loc)))))
  
1139
  (dolist (loc (sc-locations sc) nil)
1140
    (unless (load-tn-conflicts-in-sc op sc loc nil)
1141
      (return loc))))
wlott's avatar
wlott committed
1142
1143


1144
(defevent unpack-tn "Unpacked a TN to satisfy operand SC restriction.")
1145

1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
;;; UNPACK-TN  --  Internal
;;;
;;;    Make TN's location the same as for its save TN (allocating a save TN if
;;; necessary.)  Delete any save/restore code that has been emitted thus far.
;;; Mark all blocks containing references as needing to be repacked.
;;;
(defun unpack-tn (tn)
  (event unpack-tn)
  (let ((stn (or (tn-save-tn tn)
		 (pack-save-tn tn))))
    (setf (tn-sc tn) (tn-sc stn))
    (setf (tn-offset tn) (tn-offset stn))
    (flet ((zot (refs)
	     (do ((ref refs (tn-ref-next ref)))
		 ((null ref))
	       (let ((vop (tn-ref-vop ref)))
		 (if (eq (vop-info-name (vop-info vop)) 'move-operand)
		     (delete-vop vop)
		     (setf (gethash (vop-block vop) *repack-blocks*) t))))))
      (zot (tn-reads tn))
      (zot (tn-writes tn))))
1167

1168
  (undefined-value))
wlott's avatar
wlott committed
1169

1170
1171
1172
(defevent unpack-fallback "Unpacked some random operand TN.")

;;; UNPACK-FOR-LOAD-TN  --  Internal
wlott's avatar
wlott committed
1173
;;;
1174
1175
1176
1177
1178
;;;     Called by Pack-Load-TN where there isn't any location free that we can
;;; pack into.  What we do is move some live TN in one of the specified SCs to
;;; memory, then mark this block all blocks that reference the TN as needing
;;; repacking.  If we suceed, we throw to UNPACKED-TN.  If we fail, we return
;;; NIL.
wlott's avatar
wlott committed
1179
;;;
1180
1181
1182
1183
1184
;;; We can unpack any live TN that appears in the NORMAL-TNs list (isn't wired
;;; or restricted.)  We prefer to unpack TNs that are not used by the VOP.  If
;;; we can't find any such TN, then we unpack some random argument or result
;;; TN.  The only way we can fail is if all locations in SC are used by
;;; load-TNs or temporaries in VOP.
wlott's avatar
wlott committed
1185
;;;
1186
(defun unpack-for-load-tn (sc op)
ram's avatar
ram committed
1187
  (declare (type sc sc) (type tn-ref op))
1188
1189
1190
  (let ((sb (sc-sb sc))
	(normal-tns (ir2-component-normal-tns
		     (component-info *compile-component*)))
1191
	(node (vop-node (tn-ref-vop op)))
1192
1193
1194
1195
1196
1197
	(fallback nil))
    (flet ((unpack-em (victims)
	     (unless *repack-blocks*
	       (setq *repack-blocks* (make-hash-table :test #'eq)))
	     (setf (gethash (vop-block (tn-ref-vop op)) *repack-blocks*) t)
	     (dolist (victim victims)
1198
	       (event unpack-tn node)
1199
1200
1201
1202
1203
1204
	       (unpack-tn victim))
	     (throw 'unpacked-tn nil)))
      (dolist (loc (sc-locations sc))
	(declare (type index loc))
	(block SKIP
	  (collect ((victims nil adjoin))
ram's avatar
ram committed
1205
1206
1207
1208
1209
1210
1211
1212
1213
	    (do ((i loc (1+ i))
		 (end (+ loc (sc-element-size sc))))
		((= i end))
	      (declare (type index i end))
	      (let ((victim (svref (finite-sb-live-tns sb) i)))
		(when victim
		  (unless (find-in #'tn-next victim normal-tns)
		    (return-from SKIP))
		  (victims victim))))
1214
	    
1215
1216
1217
1218
1219
	    (let ((conf (load-tn-conflicts-in-sc op sc loc t)))
	      (cond ((not conf)
		     (unpack-em (victims)))
		    ((eq conf :overflow))
		    ((not fallback)
1220
1221
1222
1223
		     (cond ((find conf (victims))
			    (setq fallback (victims)))
			   ((find-in #'tn-next conf normal-tns)
			    (setq fallback (list conf))))))))))
1224
1225
      
      (when fallback
1226
	(event unpack-fallback node)
1227
1228
1229
	(unpack-em fallback))))

  nil)
wlott's avatar
wlott committed
1230
1231
1232
1233


;;; Pack-Load-TN  --  Internal
;;;
1234
1235
;;;    Try to pack a load TN in the SCs indicated by Load-SCs.  If we run out
;;; of SCs, then we unpack some TN and try again.  We return the packed load
1236
;;; TN.
wlott's avatar
wlott committed
1237
;;;
1238
1239
1240
1241
1242
1243
1244
1245
;;; Note: we allow a Load-TN to be packed in the target location even if that
;;; location is in a SC not allowed by the primitive type.  (The SC must still
;;; be allowed by the operand restriction.)  This makes move VOPs more
;;; efficient, since we won't do a move from the stack into a non-descriptor
;;; any-reg though a descriptor argument load-TN.  This does give targeting
;;; some real semantics, making it not a pure advisory to pack.  It allows pack
;;; to do some packing it wouldn't have done before.
;;;
1246
1247
(defun pack-load-tn (load-scs op)
  (declare (type sc-vector load-scs) (type tn-ref op))
ram's avatar
ram committed
1248
1249
1250
  (let ((vop (tn-ref-vop op)))
    (compute-live-tns (vop-block vop) vop))
  
1251
  (let* ((tn (tn-ref-tn op))
1252
1253
1254
1255
	 (ptype (tn-primitive-type tn))
	 (scs (svref load-scs (sc-number (tn-sc tn)))))
    (let ((current-scs scs)
	  (allowed ()))
1256
      (loop
1257
1258
1259
1260
	(cond
	 ((null current-scs)
	  (unless allowed
	    (no-load-scs-allowed-by-primitive-type-error op))
ram's avatar
ram committed
1261
1262
1263
	  (dolist (sc allowed)
	    (unpack-for-load-tn sc op))
	  (failed-to-pack-load-tn-error allowed op))
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
	(t
	 (let* ((sc (svref (backend-sc-numbers *backend*) (pop current-scs)))
		(target (find-load-tn-target op sc)))
	   (when (or target (sc-allowed-by-primitive-type sc ptype))
	     (let ((loc (or target
			    (select-load-tn-location op sc))))
	       (when loc
		 (let ((res (make-tn 0 :load nil sc)))
		   (setf (tn-offset res) loc)
		   (return res))))
	     (push sc allowed)))))))))
wlott's avatar
wlott committed
1275
1276
1277
1278


;;; Check-Operand-Restrictions  --  Internal
;;;
ram's avatar
ram committed
1279
1280
;;;    Scan a list of load-SCs vectors and a list of TN-Refs threaded by
;;; TN-Ref-Across.  When we find a reference whose TN doesn't satisfy the
1281
1282
1283
;;; restriction, we pack a Load-TN and load the operand into it.  If a load-tn
;;; has already been allocated, we can assume that the restriction is
;;; satisfied.
wlott's avatar
wlott committed
1284
;;;
pw's avatar
pw committed
1285
(declaim (inline check-operand-restrictions))
ram's avatar
ram committed
1286
1287
(defun check-operand-restrictions (scs ops)
  (declare (list scs) (type (or tn-ref null) ops))
ram's avatar
ram committed
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304

  ;; Check the targeted operands first.
  (do ((scs scs (cdr scs))
       (op ops (tn-ref-across op)))
      ((null scs))
      (let ((target (tn-ref-target op)))
	(when target
	   (let* ((load-tn (tn-ref-load-tn op))
		  (load-scs (svref (car scs)
				   (sc-number
				    (tn-sc (or load-tn (tn-ref-tn op)))))))
	     (if load-tn
		 (assert (eq load-scs t))
	       (unless (eq load-scs t)
		       (setf (tn-ref-load-tn op)
			     (pack-load-tn (car scs) op))))))))

ram's avatar
ram committed
1305
1306
1307
  (do ((scs scs (cdr scs))
       (op ops (tn-ref-across op)))
      ((null scs))
ram's avatar
ram committed
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
      (let ((target (tn-ref-target op)))
	(unless target
	   (let* ((load-tn (tn-ref-load-tn op))
		  (load-scs (svref (car scs)
				   (sc-number
				    (tn-sc (or load-tn (tn-ref-tn op)))))))
	     (if load-tn
		 (assert (eq load-scs t))
	       (unless (eq load-scs t)
		       (setf (tn-ref-load-tn op)
			     (pack-load-tn (car scs) op))))))))

wlott's avatar
wlott committed
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
  (undefined-value))
	

;;; Pack-Load-TNs  --  Internal
;;;
;;;    Scan the VOPs in Block, looking for operands whose SC restrictions
;;; aren't statisfied.  We do the results first, since they are evaluated
;;; later, and our conflict analysis is a backward scan.
;;;
(defun pack-load-tns (block)
1330
  (catch 'unpacked-tn
1331
1332
1333
1334
1335
1336
1337
1338
1339
    (let ((*live-block* nil)
	  (*live-vop* nil))
      (do ((vop (ir2-block-last-vop block) (vop-prev vop)))
	  ((null vop))
	(let ((info (vop-info vop)))
	  (check-operand-restrictions (vop-info-result-load-scs info)
				      (vop-results vop))
	  (check-operand-restrictions (vop-info-arg-load-scs info)
				      (vop-args vop))))))
wlott's avatar