0.8.15.13:
[sbcl.git] / src / compiler / pack.lisp
1 ;;;; This file contains the implementation-independent code for Pack
2 ;;;; phase in the compiler. Pack is responsible for assigning TNs to
3 ;;;; storage allocations or "register allocation".
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15
16 ;;; for debugging: some parameters controlling which optimizations we
17 ;;; attempt
18 (defvar *pack-assign-costs* t)
19 (defvar *pack-optimize-saves* t)
20 ;;; FIXME: Perhaps SB-FLUID should be renamed to SB-TWEAK and these
21 ;;; should be made conditional on SB-TWEAK.
22
23 (declaim (ftype (function (component) index) ir2-block-count))
24 \f
25 ;;;; conflict determination
26
27 ;;; Return true if the element at the specified offset in SB has a
28 ;;; conflict with TN:
29 ;;; -- If a component-live TN (:COMPONENT kind), then iterate over
30 ;;;    all the blocks. If the element at OFFSET is used anywhere in
31 ;;;    any of the component's blocks (always-live /= 0), then there
32 ;;;    is a conflict.
33 ;;; -- If TN is global (Confs true), then iterate over the blocks TN
34 ;;;    is live in (using TN-GLOBAL-CONFLICTS). If the TN is live
35 ;;;    everywhere in the block (:LIVE), then there is a conflict
36 ;;;    if the element at offset is used anywhere in the block
37 ;;;    (Always-Live /= 0). Otherwise, we use the local TN number for
38 ;;;    TN in block to find whether TN has a conflict at Offset in
39 ;;;    that block.
40 ;;; -- If TN is local, then we just check for a conflict in the block
41 ;;;    it is local to.
42 (defun offset-conflicts-in-sb (tn sb offset)
43   (declare (type tn tn) (type finite-sb sb) (type index offset))
44   (let ((confs (tn-global-conflicts tn))
45         (kind (tn-kind tn)))
46     (cond
47      ((eq kind :component)
48       (let ((loc-live (svref (finite-sb-always-live sb) offset)))
49         (dotimes (i (ir2-block-count *component-being-compiled*) nil)
50           (when (/= (sbit loc-live i) 0)
51             (return t)))))
52      (confs
53       (let ((loc-confs (svref (finite-sb-conflicts sb) offset))
54             (loc-live (svref (finite-sb-always-live sb) offset)))
55         (do ((conf confs (global-conflicts-next-tnwise conf)))
56             ((null conf)
57              nil)
58           (let* ((block (global-conflicts-block conf))
59                  (num (ir2-block-number block)))
60             (if (eq (global-conflicts-kind conf) :live)
61                 (when (/= (sbit loc-live num) 0)
62                   (return t))
63                 (when (/= (sbit (svref loc-confs num)
64                                 (global-conflicts-number conf))
65                           0)
66                   (return t)))))))
67      (t
68       (/= (sbit (svref (svref (finite-sb-conflicts sb) offset)
69                        (ir2-block-number (tn-local tn)))
70                 (tn-local-number tn))
71           0)))))
72
73 ;;; Return true if TN has a conflict in SC at the specified offset.
74 (defun conflicts-in-sc (tn sc offset)
75   (declare (type tn tn) (type sc sc) (type index offset))
76   (let ((sb (sc-sb sc)))
77     (dotimes (i (sc-element-size sc) nil)
78       (when (offset-conflicts-in-sb tn sb (+ offset i))
79         (return t)))))
80
81 ;;; Add TN's conflicts into the conflicts for the location at OFFSET
82 ;;; in SC. We iterate over each location in TN, adding to the
83 ;;; conflicts for that location:
84 ;;; -- If TN is a :COMPONENT TN, then iterate over all the blocks,
85 ;;;    setting all of the local conflict bits and the always-live bit.
86 ;;;    This records a conflict with any TN that has a LTN number in
87 ;;;    the block, as well as with :ALWAYS-LIVE and :ENVIRONMENT TNs.
88 ;;; -- If TN is global, then iterate over the blocks TN is live in. In
89 ;;;    addition to setting the always-live bit to represent the conflict
90 ;;;    with TNs live throughout the block, we also set bits in the
91 ;;;    local conflicts. If TN is :ALWAYS-LIVE in the block, we set all
92 ;;;    the bits, otherwise we OR in the local conflict bits.
93 ;;; -- If the TN is local, then we just do the block it is local to,
94 ;;;    setting always-live and OR'ing in the local conflicts.
95 (defun add-location-conflicts (tn sc offset optimize)
96   (declare (type tn tn) (type sc sc) (type index offset))
97   (let ((confs (tn-global-conflicts tn))
98         (sb (sc-sb sc))
99         (kind (tn-kind tn)))
100     (dotimes (i (sc-element-size sc))
101       (declare (type index i))
102       (let* ((this-offset (+ offset i))
103              (loc-confs (svref (finite-sb-conflicts sb) this-offset))
104              (loc-live (svref (finite-sb-always-live sb) this-offset)))
105         (cond
106          ((eq kind :component)
107           (dotimes (num (ir2-block-count *component-being-compiled*))
108             (declare (type index num))
109             (setf (sbit loc-live num) 1)
110             (set-bit-vector (svref loc-confs num))))
111          (confs
112           (do ((conf confs (global-conflicts-next-tnwise conf)))
113               ((null conf))
114             (let* ((block (global-conflicts-block conf))
115                    (num (ir2-block-number block))
116                    (local-confs (svref loc-confs num)))
117               (declare (type local-tn-bit-vector local-confs))
118               (setf (sbit loc-live num) 1)
119               (if (eq (global-conflicts-kind conf) :live)
120                   (set-bit-vector local-confs)
121                   (bit-ior local-confs (global-conflicts-conflicts conf) t)))))
122          (t
123           (let ((num (ir2-block-number (tn-local tn))))
124             (setf (sbit loc-live num) 1)
125             (bit-ior (the local-tn-bit-vector (svref loc-confs num))
126                      (tn-local-conflicts tn) t))))
127         ;; Calculating ALWAYS-LIVE-COUNT is moderately expensive, and
128         ;; currently the information isn't used unless (> SPEED
129         ;; COMPILE-SPEED).
130         (when optimize
131           (setf (svref (finite-sb-always-live-count sb) this-offset)
132                 (find-location-usage sb this-offset))))))
133   (values))
134
135 ;; A rought measure of how much a given OFFSET in SB is currently
136 ;; used. Current implementation counts the amount of blocks where the
137 ;; offset has been marked as ALWAYS-LIVE.
138 (defun find-location-usage (sb offset)
139   (declare (optimize speed))
140   (declare (type sb sb) (type index offset))
141   (let* ((always-live (svref (finite-sb-always-live sb) offset)))
142     (declare (simple-bit-vector always-live))
143     (count 1 always-live)))
144
145 ;;; Return the total number of IR2-BLOCKs in COMPONENT.
146 (defun ir2-block-count (component)
147   (declare (type component component))
148   (do ((2block (block-info (block-next (component-head component)))
149                (ir2-block-next 2block)))
150       ((null 2block)
151        (error "What?  No ir2 blocks have a non-nil number?"))
152     (when (ir2-block-number 2block)
153       (return (1+ (ir2-block-number 2block))))))
154
155 ;;; Ensure that the conflicts vectors for each :FINITE SB are large
156 ;;; enough for the number of blocks allocated. Also clear any old
157 ;;; conflicts and reset the current size to the initial size.
158 (defun init-sb-vectors (component)
159   (let ((nblocks (ir2-block-count component)))
160     (dolist (sb *backend-sb-list*)
161       (unless (eq (sb-kind sb) :non-packed)
162         (let* ((conflicts (finite-sb-conflicts sb))
163                (always-live (finite-sb-always-live sb))
164                (always-live-count (finite-sb-always-live-count sb))
165                (max-locs (length conflicts))
166                (last-count (finite-sb-last-block-count sb)))
167           (unless (zerop max-locs)
168             (let ((current-size (length (the simple-vector
169                                              (svref conflicts 0)))))
170               (cond
171                ((> nblocks current-size)
172                 (let ((new-size (max nblocks (* current-size 2))))
173                   (declare (type index new-size))
174                   (dotimes (i max-locs)
175                     (declare (type index i))
176                     (let ((new-vec (make-array new-size)))
177                       (let ((old (svref conflicts i)))
178                         (declare (simple-vector old))
179                         (dotimes (j current-size)
180                           (declare (type index j))
181                           (setf (svref new-vec j)
182                                 (clear-bit-vector (svref old j)))))
183
184                       (do ((j current-size (1+ j)))
185                           ((= j new-size))
186                         (declare (type index j))
187                         (setf (svref new-vec j)
188                               (make-array local-tn-limit :element-type 'bit
189                                           :initial-element 0)))
190                       (setf (svref conflicts i) new-vec))
191                     (setf (svref always-live i)
192                           (make-array new-size :element-type 'bit
193                                       :initial-element 0))
194                     (setf (svref always-live-count i) 0))))
195                (t
196                 (dotimes (i (finite-sb-current-size sb))
197                   (declare (type index i))
198                   (let ((conf (svref conflicts i)))
199                     (declare (simple-vector conf))
200                     (dotimes (j last-count)
201                       (declare (type index j))
202                       (clear-bit-vector (svref conf j))))
203                   (clear-bit-vector (svref always-live i))
204                   (setf (svref always-live-count i) 0))))))
205
206           (setf (finite-sb-last-block-count sb) nblocks)
207           (setf (finite-sb-current-size sb) (sb-size sb))
208           (setf (finite-sb-last-offset sb) 0))))))
209
210 ;;; Expand the :UNBOUNDED SB backing SC by either the initial size or
211 ;;; the SC element size, whichever is larger. If NEEDED-SIZE is
212 ;;; larger, then use that size.
213 (defun grow-sc (sc &optional (needed-size 0))
214   (declare (type sc sc) (type index needed-size))
215   (let* ((sb (sc-sb sc))
216          (size (finite-sb-current-size sb))
217          (align-mask (1- (sc-alignment sc)))
218          (inc (max (sb-size sb)
219                    (+ (sc-element-size sc)
220                       (- (logandc2 (+ size align-mask) align-mask)
221                          size))
222                    (- needed-size size)))
223          (new-size (+ size inc))
224          (conflicts (finite-sb-conflicts sb))
225          (block-size (if (zerop (length conflicts))
226                          (ir2-block-count *component-being-compiled*)
227                          (length (the simple-vector (svref conflicts 0))))))
228     (declare (type index inc new-size))
229     (aver (eq (sb-kind sb) :unbounded))
230
231     (when (> new-size (length conflicts))
232       (let ((new-conf (make-array new-size)))
233         (replace new-conf conflicts)
234         (do ((i size (1+ i)))
235             ((= i new-size))
236           (declare (type index i))
237           (let ((loc-confs (make-array block-size)))
238             (dotimes (j block-size)
239               (setf (svref loc-confs j)
240                     (make-array local-tn-limit
241                                 :initial-element 0
242                                 :element-type 'bit)))
243             (setf (svref new-conf i) loc-confs)))
244         (setf (finite-sb-conflicts sb) new-conf))
245
246       (let ((new-live (make-array new-size)))
247         (replace new-live (finite-sb-always-live sb))
248         (do ((i size (1+ i)))
249             ((= i new-size))
250           (setf (svref new-live i)
251                 (make-array block-size
252                             :initial-element 0
253                             :element-type 'bit)))
254         (setf (finite-sb-always-live sb) new-live))
255
256       (let ((new-live-count (make-array new-size)))
257         (declare (optimize speed)) ;; FILL deftransform
258         (replace new-live-count (finite-sb-always-live-count sb))
259         (fill new-live-count 0 :start size)
260         (setf (finite-sb-always-live-count sb) new-live-count))
261         
262       (let ((new-tns (make-array new-size :initial-element nil)))
263         (replace new-tns (finite-sb-live-tns sb))
264         (fill (finite-sb-live-tns sb) nil)
265         (setf (finite-sb-live-tns sb) new-tns)))
266
267     (setf (finite-sb-current-size sb) new-size))
268   (values))
269
270 \f
271 ;;;; internal errors
272
273 ;;; Give someone a hard time because there isn't any load function
274 ;;; defined to move from SRC to DEST.
275 (defun no-load-fun-error (src dest)
276   (let* ((src-sc (tn-sc src))
277          (src-name (sc-name src-sc))
278          (dest-sc (tn-sc dest))
279          (dest-name (sc-name dest-sc)))
280     (cond ((eq (sb-kind (sc-sb src-sc)) :non-packed)
281            (unless (member src-sc (sc-constant-scs dest-sc))
282              (error "loading from an invalid constant SC?~@
283                      VM definition inconsistent, try recompiling."))
284            (error "no load function defined to load SC ~S ~
285                    from its constant SC ~S"
286                   dest-name src-name))
287           ((member src-sc (sc-alternate-scs dest-sc))
288            (error "no load function defined to load SC ~S from its ~
289                    alternate SC ~S"
290                   dest-name src-name))
291           ((member dest-sc (sc-alternate-scs src-sc))
292            (error "no load function defined to save SC ~S in its ~
293                    alternate SC ~S"
294                   src-name dest-name))
295           (t
296            ;; FIXME: "VM definition is inconsistent" shouldn't be a
297            ;; possibility in SBCL.
298            (error "loading to/from SCs that aren't alternates?~@
299                    VM definition is inconsistent, try recompiling.")))))
300
301 ;;; Called when we failed to pack TN. If RESTRICTED is true, then we
302 ;;; are restricted to pack TN in its SC.
303 (defun failed-to-pack-error (tn restricted)
304   (declare (type tn tn))
305   (let* ((sc (tn-sc tn))
306          (scs (cons sc (sc-alternate-scs sc))))
307     (cond
308      (restricted
309       (error "failed to pack restricted TN ~S in its SC ~S"
310              tn (sc-name sc)))
311      (t
312       (aver (not (find :unbounded scs
313                        :key (lambda (x) (sb-kind (sc-sb x))))))
314       (let ((ptype (tn-primitive-type tn)))
315         (cond
316          (ptype
317           (aver (member (sc-number sc) (primitive-type-scs ptype)))
318           (error "SC ~S doesn't have any :UNBOUNDED alternate SCs, but is~@
319                   a SC for primitive-type ~S."
320                  (sc-name sc) (primitive-type-name ptype)))
321          (t
322           (error "SC ~S doesn't have any :UNBOUNDED alternate SCs."
323                  (sc-name sc)))))))))
324
325 ;;; Return a list of format arguments describing how TN is used in
326 ;;; OP's VOP.
327 (defun describe-tn-use (loc tn op)
328   (let* ((vop (tn-ref-vop op))
329          (args (vop-args vop))
330          (results (vop-results vop))
331          (name (with-output-to-string (stream)
332                  (print-tn-guts tn stream)))
333          (2comp (component-info *component-being-compiled*))
334          temp)
335     (cond
336      ((setq temp (position-in #'tn-ref-across tn args :key #'tn-ref-tn))
337       `("~2D: ~A (~:R argument)" ,loc ,name ,(1+ temp)))
338      ((setq temp (position-in #'tn-ref-across tn results :key #'tn-ref-tn))
339       `("~2D: ~A (~:R result)" ,loc ,name ,(1+ temp)))
340      ((setq temp (position-in #'tn-ref-across tn args :key #'tn-ref-load-tn))
341       `("~2D: ~A (~:R argument load TN)" ,loc ,name ,(1+ temp)))
342      ((setq temp (position-in #'tn-ref-across tn results :key
343                               #'tn-ref-load-tn))
344       `("~2D: ~A (~:R result load TN)" ,loc ,name ,(1+ temp)))
345      ((setq temp (position-in #'tn-ref-across tn (vop-temps vop)
346                               :key #'tn-ref-tn))
347       `("~2D: ~A (temporary ~A)" ,loc ,name
348         ,(operand-parse-name (elt (vop-parse-temps
349                                    (vop-parse-or-lose
350                                     (vop-info-name  (vop-info vop))))
351                                   temp))))
352      ((eq (tn-kind tn) :component)
353       `("~2D: ~A (component live)" ,loc ,name))
354      ((position-in #'tn-next tn (ir2-component-wired-tns 2comp))
355       `("~2D: ~A (wired)" ,loc ,name))
356      ((position-in #'tn-next tn (ir2-component-restricted-tns 2comp))
357       `("~2D: ~A (restricted)" ,loc ,name))
358      (t
359       `("~2D: not referenced?" ,loc)))))
360
361 ;;; If load TN packing fails, try to give a helpful error message. We
362 ;;; find a TN in each location that conflicts, and print it.
363 (defun failed-to-pack-load-tn-error (scs op)
364   (declare (list scs) (type tn-ref op))
365   (collect ((used)
366             (unused))
367     (dolist (sc scs)
368       (let* ((sb (sc-sb sc))
369              (confs (finite-sb-live-tns sb)))
370         (aver (eq (sb-kind sb) :finite))
371         (dolist (el (sc-locations sc))
372           (declare (type index el))
373           (let ((conf (load-tn-conflicts-in-sc op sc el t)))
374             (if conf
375                 (used (describe-tn-use el conf op))
376                 (do ((i el (1+ i))
377                      (end (+ el (sc-element-size sc))))
378                     ((= i end)
379                      (unused el))
380                   (declare (type index i end))
381                   (let ((victim (svref confs i)))
382                     (when victim
383                       (used (describe-tn-use el victim op))
384                       (return t)))))))))
385
386     (multiple-value-bind (arg-p n more-p costs load-scs incon)
387         (get-operand-info op)
388       (declare (ignore costs load-scs))
389         (aver (not more-p))
390         (error "unable to pack a Load-TN in SC ~{~A~#[~^~;, or ~:;,~]~} ~
391                 for the ~:R ~:[result~;argument~] to~@
392                 the ~S VOP,~@
393                 ~:[since all SC elements are in use:~:{~%~@?~}~%~;~
394                 ~:*but these SC elements are not in use:~%  ~S~%Bug?~*~]~
395                 ~:[~;~@
396                 Current cost info inconsistent with that in effect at compile ~
397                 time. Recompile.~%Compilation order may be incorrect.~]"
398                (mapcar #'sc-name scs)
399                n arg-p
400                (vop-info-name (vop-info (tn-ref-vop op)))
401                (unused) (used)
402                incon))))
403
404 ;;; This is called when none of the SCs that we can load OP into are
405 ;;; allowed by OP's primitive-type.
406 (defun no-load-scs-allowed-by-primitive-type-error (ref)
407   (declare (type tn-ref ref))
408   (let* ((tn (tn-ref-tn ref))
409          (ptype (tn-primitive-type tn)))
410     (multiple-value-bind (arg-p pos more-p costs load-scs incon)
411         (get-operand-info ref)
412       (declare (ignore costs))
413       (aver (not more-p))
414       (error "~S is not valid as the ~:R ~:[result~;argument~] to VOP:~
415               ~%  ~S,~@
416               since the TN's primitive type ~S doesn't allow any of the SCs~@
417               allowed by the operand restriction:~%  ~S~
418               ~:[~;~@
419               Current cost info inconsistent with that in effect at compile ~
420               time. Recompile.~%Compilation order may be incorrect.~]"
421              tn pos arg-p
422              (template-name (vop-info (tn-ref-vop ref)))
423              (primitive-type-name ptype)
424              (mapcar #'sc-name (listify-restrictions load-scs))
425              incon))))
426 \f
427 ;;;; register saving
428
429 ;;; Do stuff to note that TN is spilled at VOP for the debugger's benefit.
430 (defun note-spilled-tn (tn vop)
431   (when (and (tn-leaf tn) (vop-save-set vop))
432     (let ((2comp (component-info *component-being-compiled*)))
433       (setf (gethash tn (ir2-component-spilled-tns 2comp)) t)
434       (pushnew tn (gethash vop (ir2-component-spilled-vops 2comp)))))
435   (values))
436
437 ;;; Make a save TN for TN, pack it, and return it. We copy various
438 ;;; conflict information from the TN so that pack does the right
439 ;;; thing.
440 (defun pack-save-tn (tn)
441   (declare (type tn tn))
442   (let ((res (make-tn 0 :save nil nil)))
443     (dolist (alt (sc-alternate-scs (tn-sc tn))
444                  (error "no unbounded alternate for SC ~S"
445                         (sc-name (tn-sc tn))))
446       (when (eq (sb-kind (sc-sb alt)) :unbounded)
447         (setf (tn-save-tn tn) res)
448         (setf (tn-save-tn res) tn)
449         (setf (tn-sc res) alt)
450         (pack-tn res t nil)
451         (return res)))))
452
453 ;;; Find the load function for moving from SRC to DEST and emit a
454 ;;; MOVE-OPERAND VOP with that function as its info arg.
455 (defun emit-operand-load (node block src dest before)
456   (declare (type node node) (type ir2-block block)
457            (type tn src dest) (type (or vop null) before))
458   (emit-load-template node block
459                       (template-or-lose 'move-operand)
460                       src dest
461                       (list (or (svref (sc-move-funs (tn-sc dest))
462                                        (sc-number (tn-sc src)))
463                                 (no-load-fun-error src dest)))
464                       before)
465   (values))
466
467 ;;; Find the preceding use of the VOP NAME in the emit order, starting
468 ;;; with VOP. We must find the VOP in the same IR1 block.
469 (defun reverse-find-vop (name vop)
470   (do* ((block (vop-block vop) (ir2-block-prev block))
471         (last vop (ir2-block-last-vop block)))
472        (nil)
473     (aver (eq (ir2-block-block block) (ir2-block-block (vop-block vop))))
474     (do ((current last (vop-prev current)))
475         ((null current))
476       (when (eq (vop-info-name (vop-info current)) name)
477         (return-from reverse-find-vop current)))))
478
479 ;;; For TNs that have other than one writer, we save the TN before
480 ;;; each call. If a local call (MOVE-ARGS is :LOCAL-CALL), then we
481 ;;; scan back for the ALLOCATE-FRAME VOP, and emit the save there.
482 ;;; This is necessary because in a self-recursive local call, the
483 ;;; registers holding the current arguments may get trashed by setting
484 ;;; up the call arguments. The ALLOCATE-FRAME VOP marks a place at
485 ;;; which the values are known to be good.
486 (defun save-complex-writer-tn (tn vop)
487   (let ((save (or (tn-save-tn tn)
488                   (pack-save-tn tn)))
489         (node (vop-node vop))
490         (block (vop-block vop))
491         (next (vop-next vop)))
492     (when (eq (tn-kind save) :specified-save)
493       (setf (tn-kind save) :save))
494     (aver (eq (tn-kind save) :save))
495     (emit-operand-load node block tn save
496                        (if (eq (vop-info-move-args (vop-info vop))
497                                :local-call)
498                            (reverse-find-vop 'allocate-frame vop)
499                            vop))
500     (emit-operand-load node block save tn next)))
501
502 ;;; Return a VOP after which is an OK place to save the value of TN.
503 ;;; For correctness, it is only required that this location be after
504 ;;; any possible write and before any possible restore location.
505 ;;;
506 ;;; In practice, we return the unique writer VOP, but give up if the
507 ;;; TN is ever read by a VOP with MOVE-ARGS :LOCAL-CALL. This prevents
508 ;;; us from being confused by non-tail local calls.
509 ;;;
510 ;;; When looking for writes, we have to ignore uses of MOVE-OPERAND,
511 ;;; since they will correspond to restores that we have already done.
512 (defun find-single-writer (tn)
513   (declare (type tn tn))
514   (do ((write (tn-writes tn) (tn-ref-next write))
515        (res nil))
516       ((null write)
517        (when (and res
518                   (do ((read (tn-reads tn) (tn-ref-next read)))
519                       ((not read) t)
520                     (when (eq (vop-info-move-args
521                                (vop-info
522                                 (tn-ref-vop read)))
523                               :local-call)
524                       (return nil))))
525          (tn-ref-vop res)))
526
527     (unless (eq (vop-info-name (vop-info (tn-ref-vop write)))
528                 'move-operand)
529       (when res (return nil))
530       (setq res write))))
531
532 ;;; Try to save TN at a single location. If we succeed, return T,
533 ;;; otherwise NIL.
534 (defun save-single-writer-tn (tn)
535   (declare (type tn tn))
536   (let* ((old-save (tn-save-tn tn))
537          (save (or old-save (pack-save-tn tn)))
538          (writer (find-single-writer tn)))
539     (when (and writer
540                (or (not old-save)
541                    (eq (tn-kind old-save) :specified-save)))
542       (emit-operand-load (vop-node writer) (vop-block writer)
543                          tn save (vop-next writer))
544       (setf (tn-kind save) :save-once)
545       t)))
546
547 ;;; Restore a TN with a :SAVE-ONCE save TN.
548 (defun restore-single-writer-tn (tn vop)
549   (declare (type tn) (type vop vop))
550   (let ((save (tn-save-tn tn)))
551     (aver (eq (tn-kind save) :save-once))
552     (emit-operand-load (vop-node vop) (vop-block vop) save tn (vop-next vop)))
553   (values))
554
555 ;;; Save a single TN that needs to be saved, choosing save-once if
556 ;;; appropriate. This is also called by SPILL-AND-PACK-LOAD-TN.
557 (defun basic-save-tn (tn vop)
558   (declare (type tn tn) (type vop vop))
559   (let ((save (tn-save-tn tn)))
560     (cond ((and save (eq (tn-kind save) :save-once))
561            (restore-single-writer-tn tn vop))
562           ((save-single-writer-tn tn)
563            (restore-single-writer-tn tn vop))
564           (t
565            (save-complex-writer-tn tn vop))))
566   (values))
567
568 ;;; Scan over the VOPs in BLOCK, emiting saving code for TNs noted in
569 ;;; the codegen info that are packed into saved SCs.
570 (defun emit-saves (block)
571   (declare (type ir2-block block))
572   (do ((vop (ir2-block-start-vop block) (vop-next vop)))
573       ((null vop))
574     (when (eq (vop-info-save-p (vop-info vop)) t)
575       (do-live-tns (tn (vop-save-set vop) block)
576         (when (and (sc-save-p (tn-sc tn))
577                    (not (eq (tn-kind tn) :component)))
578           (basic-save-tn tn vop)))))
579
580   (values))
581 \f
582 ;;;; optimized saving
583
584 ;;; Save TN if it isn't a single-writer TN that has already been
585 ;;; saved. If multi-write, we insert the save BEFORE the specified
586 ;;; VOP. CONTEXT is a VOP used to tell which node/block to use for the
587 ;;; new VOP.
588 (defun save-if-necessary (tn before context)
589   (declare (type tn tn) (type (or vop null) before) (type vop context))
590   (let ((save (tn-save-tn tn)))
591     (when (eq (tn-kind save) :specified-save)
592       (setf (tn-kind save) :save))
593     (aver (member (tn-kind save) '(:save :save-once)))
594     (unless (eq (tn-kind save) :save-once)
595       (or (save-single-writer-tn tn)
596           (emit-operand-load (vop-node context) (vop-block context)
597                              tn save before))))
598   (values))
599
600 ;;; Load the TN from its save location, allocating one if necessary.
601 ;;; The load is inserted BEFORE the specifier VOP. CONTEXT is a VOP
602 ;;; used to tell which node/block to use for the new VOP.
603 (defun restore-tn (tn before context)
604   (declare (type tn tn) (type (or vop null) before) (type vop context))
605   (let ((save (or (tn-save-tn tn) (pack-save-tn tn))))
606     (emit-operand-load (vop-node context) (vop-block context)
607                        save tn before))
608   (values))
609
610 (eval-when (:compile-toplevel :execute)
611
612 ;;; Do stuff to note a read of TN, for OPTIMIZED-EMIT-SAVES-BLOCK.
613 (defmacro save-note-read (tn)
614   `(let* ((tn ,tn)
615           (num (tn-number tn)))
616      (when (and (sc-save-p (tn-sc tn))
617                 (zerop (sbit restores num))
618                 (not (eq (tn-kind tn) :component)))
619        (setf (sbit restores num) 1)
620        (push tn restores-list))))
621
622 ) ; EVAL-WHEN
623
624 ;;; Start scanning backward at the end of BLOCK, looking which TNs are
625 ;;; live and looking for places where we have to save. We manipulate
626 ;;; two sets: SAVES and RESTORES.
627 ;;;
628 ;;; SAVES is a set of all the TNs that have to be saved because they
629 ;;; are restored after some call. We normally delay saving until the
630 ;;; beginning of the block, but we must save immediately if we see a
631 ;;; write of the saved TN. We also immediately save all TNs and exit
632 ;;; when we see a NOTE-ENVIRONMENT-START VOP, since saves can't be
633 ;;; done before the environment is properly initialized.
634 ;;;
635 ;;; RESTORES is a set of all the TNs read (and not written) between
636 ;;; here and the next call, i.e. the set of TNs that must be restored
637 ;;; when we reach the next (earlier) call VOP. Unlike SAVES, this set
638 ;;; is cleared when we do the restoring after a call. Any TNs that
639 ;;; were in RESTORES are moved into SAVES to ensure that they are
640 ;;; saved at some point.
641 ;;;
642 ;;; SAVES and RESTORES are represented using both a list and a
643 ;;; bit-vector so that we can quickly iterate and test for membership.
644 ;;; The incoming SAVES and RESTORES args are used for computing these
645 ;;; sets (the initial contents are ignored.)
646 ;;;
647 ;;; When we hit a VOP with :COMPUTE-ONLY SAVE-P (an internal error
648 ;;; location), we pretend that all live TNs were read, unless (= speed
649 ;;; 3), in which case we mark all the TNs that are live but not
650 ;;; restored as spilled.
651 (defun optimized-emit-saves-block (block saves restores)
652   (declare (type ir2-block block) (type simple-bit-vector saves restores))
653   (let ((1block (ir2-block-block block))
654         (saves-list ())
655         (restores-list ())
656         (skipping nil))
657     (declare (list saves-list restores-list))
658     (clear-bit-vector saves)
659     (clear-bit-vector restores)
660     (do-live-tns (tn (ir2-block-live-in block) block)
661       (when (and (sc-save-p (tn-sc tn))
662                  (not (eq (tn-kind tn) :component)))
663         (let ((num (tn-number tn)))
664           (setf (sbit restores num) 1)
665           (push tn restores-list))))
666
667     (do ((block block (ir2-block-prev block))
668          (prev nil block))
669         ((not (eq (ir2-block-block block) 1block))
670          (aver (not skipping))
671          (dolist (save saves-list)
672            (let ((start (ir2-block-start-vop prev)))
673              (save-if-necessary save start start)))
674          prev)
675       (do ((vop (ir2-block-last-vop block) (vop-prev vop)))
676           ((null vop))
677         (let ((info (vop-info vop)))
678           (case (vop-info-name info)
679             (allocate-frame
680              (aver skipping)
681              (setq skipping nil))
682             (note-environment-start
683              (aver (not skipping))
684              (dolist (save saves-list)
685                (save-if-necessary save (vop-next vop) vop))
686              (return-from optimized-emit-saves-block block)))
687
688           (unless skipping
689             (do ((write (vop-results vop) (tn-ref-across write)))
690                 ((null write))
691               (let* ((tn (tn-ref-tn write))
692                      (num (tn-number tn)))
693                 (unless (zerop (sbit restores num))
694                   (setf (sbit restores num) 0)
695                   (setq restores-list
696                         (delete tn restores-list :test #'eq)))
697                 (unless (zerop (sbit saves num))
698                   (setf (sbit saves num) 0)
699                   (save-if-necessary tn (vop-next vop) vop)
700                   (setq saves-list
701                         (delete tn saves-list :test #'eq))))))
702
703           (macrolet (;; Do stuff to note a read of TN, for
704                      ;; OPTIMIZED-EMIT-SAVES-BLOCK.
705                      (save-note-read (tn)
706                        `(let* ((tn ,tn)
707                                (num (tn-number tn)))
708                           (when (and (sc-save-p (tn-sc tn))
709                                      (zerop (sbit restores num))
710                                      (not (eq (tn-kind tn) :component)))
711                           (setf (sbit restores num) 1)
712                           (push tn restores-list)))))
713
714             (case (vop-info-save-p info)
715               ((t)
716                (dolist (tn restores-list)
717                  (restore-tn tn (vop-next vop) vop)
718                  (let ((num (tn-number tn)))
719                    (when (zerop (sbit saves num))
720                      (push tn saves-list)
721                      (setf (sbit saves num) 1))))
722                (setq restores-list nil)
723                (clear-bit-vector restores))
724               (:compute-only
725                (cond ((policy (vop-node vop) (= speed 3))
726                       (do-live-tns (tn (vop-save-set vop) block)
727                         (when (zerop (sbit restores (tn-number tn)))
728                           (note-spilled-tn tn vop))))
729                      (t
730                       (do-live-tns (tn (vop-save-set vop) block)
731                         (save-note-read tn))))))
732
733             (if (eq (vop-info-move-args info) :local-call)
734                 (setq skipping t)
735                 (do ((read (vop-args vop) (tn-ref-across read)))
736                     ((null read))
737                   (save-note-read (tn-ref-tn read))))))))))
738
739 ;;; This is like EMIT-SAVES, only different. We avoid redundant saving
740 ;;; within the block, and don't restore values that aren't used before
741 ;;; the next call. This function is just the top level loop over the
742 ;;; blocks in the component, which locates blocks that need saving
743 ;;; done.
744 (defun optimized-emit-saves (component)
745   (declare (type component component))
746   (let* ((gtn-count (1+ (ir2-component-global-tn-counter
747                          (component-info component))))
748          (saves (make-array gtn-count :element-type 'bit))
749          (restores (make-array gtn-count :element-type 'bit))
750          (block (ir2-block-prev (block-info (component-tail component))))
751          (head (block-info (component-head component))))
752     (loop
753       (when (eq block head) (return))
754       (when (do ((vop (ir2-block-start-vop block) (vop-next vop)))
755                 ((null vop) nil)
756               (when (eq (vop-info-save-p (vop-info vop)) t)
757                 (return t)))
758         (setq block (optimized-emit-saves-block block saves restores)))
759       (setq block (ir2-block-prev block)))))
760
761 ;;; Iterate over the normal TNs, finding the cost of packing on the
762 ;;; stack in units of the number of references. We count all
763 ;;; references as +1, and subtract out REGISTER-SAVE-PENALTY for each
764 ;;; place where we would have to save a register.
765 (defun assign-tn-costs (component)
766   (do-ir2-blocks (block component)
767     (do ((vop (ir2-block-start-vop block) (vop-next vop)))
768         ((null vop))
769       (when (eq (vop-info-save-p (vop-info vop)) t)
770         (do-live-tns (tn (vop-save-set vop) block)
771           (decf (tn-cost tn) *backend-register-save-penalty*)))))
772
773   (do ((tn (ir2-component-normal-tns (component-info component))
774            (tn-next tn)))
775       ((null tn))
776     (let ((cost (tn-cost tn)))
777       (declare (fixnum cost))
778       (do ((ref (tn-reads tn) (tn-ref-next ref)))
779           ((null ref))
780         (incf cost))
781       (do ((ref (tn-writes tn) (tn-ref-next ref)))
782           ((null ref))
783         (incf cost))
784       (setf (tn-cost tn) cost))))
785
786 ;;; Iterate over the normal TNs, storing the depth of the deepest loop
787 ;;; that the TN is used in TN-LOOP-DEPTH.
788 (defun assign-tn-depths (component)
789   (when *loop-analyze* 
790     (do-ir2-blocks (block component)
791       (do ((vop (ir2-block-start-vop block)
792                 (vop-next vop)))
793           ((null vop))
794         (flet ((find-all-tns (head-fun)
795                  (collect ((tns))
796                    (do ((ref (funcall head-fun vop) (tn-ref-across ref)))
797                        ((null ref))
798                      (tns (tn-ref-tn ref)))
799                    (tns))))
800           (dolist (tn (nconc (find-all-tns #'vop-args)
801                              (find-all-tns #'vop-results)
802                              (find-all-tns #'vop-temps)
803                              ;; What does "references in this VOP
804                              ;; mean"? Probably something that isn't
805                              ;; useful in this context, since these
806                              ;; TN-REFs are linked with TN-REF-NEXT
807                              ;; instead of TN-REF-ACROSS. --JES
808                              ;; 2004-09-11
809                              ;; (find-all-tns #'vop-refs)
810                              ))
811             (setf (tn-loop-depth tn)
812                   (max (tn-loop-depth tn)
813                        (let* ((ir1-block (ir2-block-block (vop-block vop)))
814                               (loop (block-loop ir1-block)))
815                          (if loop
816                              (loop-depth loop)
817                              0))))))))))
818
819 \f
820 ;;;; load TN packing
821
822 ;;; These variables indicate the last location at which we computed
823 ;;; the Live-TNs. They hold the BLOCK and VOP values that were passed
824 ;;; to COMPUTE-LIVE-TNS.
825 (defvar *live-block*)
826 (defvar *live-vop*)
827
828 ;;; If we unpack some TNs, then we mark all affected blocks by
829 ;;; sticking them in this hash-table. This is initially null. We
830 ;;; create the hashtable if we do any unpacking.
831 (defvar *repack-blocks*)
832 (declaim (type (or hash-table null) *repack-blocks*))
833
834 ;;; Set the LIVE-TNS vectors in all :FINITE SBs to represent the TNs
835 ;;; live at the end of BLOCK.
836 (defun init-live-tns (block)
837   (dolist (sb *backend-sb-list*)
838     (when (eq (sb-kind sb) :finite)
839       (fill (finite-sb-live-tns sb) nil)))
840
841   (do-live-tns (tn (ir2-block-live-in block) block)
842     (let* ((sc (tn-sc tn))
843            (sb (sc-sb sc)))
844       (when (eq (sb-kind sb) :finite)
845         (do ((offset (tn-offset tn) (1+ offset))
846              (end (+ (tn-offset tn) (sc-element-size sc))))
847             ((= offset end))
848           (declare (type index offset end))
849           (setf (svref (finite-sb-live-tns sb) offset) tn)))))
850
851   (setq *live-block* block)
852   (setq *live-vop* (ir2-block-last-vop block))
853
854   (values))
855
856 ;;; Set the LIVE-TNs in :FINITE SBs to represent the TNs live
857 ;;; immediately after the evaluation of VOP in BLOCK, excluding
858 ;;; results of the VOP. If VOP is null, then compute the live TNs at
859 ;;; the beginning of the block. Sequential calls on the same block
860 ;;; must be in reverse VOP order.
861 (defun compute-live-tns (block vop)
862   (declare (type ir2-block block) (type vop vop))
863   (unless (eq block *live-block*)
864     (init-live-tns block))
865
866   (do ((current *live-vop* (vop-prev current)))
867       ((eq current vop)
868        (do ((res (vop-results vop) (tn-ref-across res)))
869            ((null res))
870          (let* ((tn (tn-ref-tn res))
871                 (sc (tn-sc tn))
872                 (sb (sc-sb sc)))
873            (when (eq (sb-kind sb) :finite)
874              (do ((offset (tn-offset tn) (1+ offset))
875                   (end (+ (tn-offset tn) (sc-element-size sc))))
876                  ((= offset end))
877                (declare (type index offset end))
878                (setf (svref (finite-sb-live-tns sb) offset) nil))))))
879     (do ((ref (vop-refs current) (tn-ref-next-ref ref)))
880         ((null ref))
881       (let ((ltn (tn-ref-load-tn ref)))
882         (when ltn
883           (let* ((sc (tn-sc ltn))
884                  (sb (sc-sb sc)))
885             (when (eq (sb-kind sb) :finite)
886               (let ((tns (finite-sb-live-tns sb)))
887                 (do ((offset (tn-offset ltn) (1+ offset))
888                      (end (+ (tn-offset ltn) (sc-element-size sc))))
889                     ((= offset end))
890                   (declare (type index offset end))
891                   (aver (null (svref tns offset)))))))))
892
893       (let* ((tn (tn-ref-tn ref))
894              (sc (tn-sc tn))
895              (sb (sc-sb sc)))
896         (when (eq (sb-kind sb) :finite)
897           (let ((tns (finite-sb-live-tns sb)))
898             (do ((offset (tn-offset tn) (1+ offset))
899                  (end (+ (tn-offset tn) (sc-element-size sc))))
900                 ((= offset end))
901               (declare (type index offset end))
902               (if (tn-ref-write-p ref)
903                   (setf (svref tns offset) nil)
904                   (let ((old (svref tns offset)))
905                     (aver (or (null old) (eq old tn)))
906                     (setf (svref tns offset) tn)))))))))
907
908   (setq *live-vop* vop)
909   (values))
910
911 ;;; This is kind of like OFFSET-CONFLICTS-IN-SB, except that it uses
912 ;;; the VOP refs to determine whether a Load-TN for OP could be packed
913 ;;; in the specified location, disregarding conflicts with TNs not
914 ;;; referenced by this VOP. There is a conflict if either:
915 ;;;  1. The reference is a result, and the same location is either:
916 ;;;     -- Used by some other result.
917 ;;;     -- Used in any way after the reference (exclusive).
918 ;;;  2. The reference is an argument, and the same location is either:
919 ;;;     -- Used by some other argument.
920 ;;;     -- Used in any way before the reference (exclusive).
921 ;;;
922 ;;; In 1 (and 2) above, the first bullet corresponds to result-result
923 ;;; (and argument-argument) conflicts. We need this case because there
924 ;;; aren't any TN-REFs to represent the implicit reading of results or
925 ;;; writing of arguments.
926 ;;;
927 ;;; The second bullet corresponds conflicts with temporaries or between
928 ;;; arguments and results.
929 ;;;
930 ;;; We consider both the TN-REF-TN and the TN-REF-LOAD-TN (if any) to
931 ;;; be referenced simultaneously and in the same way. This causes
932 ;;; load-TNs to appear live to the beginning (or end) of the VOP, as
933 ;;; appropriate.
934 ;;;
935 ;;; We return a conflicting TN if there is a conflict.
936 (defun load-tn-offset-conflicts-in-sb (op sb offset)
937   (declare (type tn-ref op) (type finite-sb sb) (type index offset))
938   (aver (eq (sb-kind sb) :finite))
939   (let ((vop (tn-ref-vop op)))
940     (labels ((tn-overlaps (tn)
941                (let ((sc (tn-sc tn))
942                      (tn-offset (tn-offset tn)))
943                  (when (and (eq (sc-sb sc) sb)
944                             (<= tn-offset offset)
945                             (< offset
946                                (the index
947                                     (+ tn-offset (sc-element-size sc)))))
948                    tn)))
949              (same (ref)
950                (let ((tn (tn-ref-tn ref))
951                      (ltn (tn-ref-load-tn ref)))
952                  (or (tn-overlaps tn)
953                      (and ltn (tn-overlaps ltn)))))
954              (is-op (ops)
955                (do ((ops ops (tn-ref-across ops)))
956                    ((null ops) nil)
957                  (let ((found (same ops)))
958                    (when (and found (not (eq ops op)))
959                      (return found)))))
960              (is-ref (refs end)
961                (do ((refs refs (tn-ref-next-ref refs)))
962                    ((eq refs end) nil)
963                  (let ((found (same refs)))
964                  (when found (return found))))))
965       (declare (inline is-op is-ref tn-overlaps))
966       (if (tn-ref-write-p op)
967           (or (is-op (vop-results vop))
968               (is-ref (vop-refs vop) op))
969           (or (is-op (vop-args vop))
970               (is-ref (tn-ref-next-ref op) nil))))))
971
972 ;;; Iterate over all the elements in the SB that would be allocated by
973 ;;; allocating a TN in SC at Offset, checking for conflict with
974 ;;; load-TNs or other TNs (live in the LIVE-TNS, which must be set
975 ;;; up.) We also return true if there aren't enough locations after
976 ;;; Offset to hold a TN in SC. If Ignore-Live is true, then we ignore
977 ;;; the live-TNs, considering only references within Op's VOP.
978 ;;;
979 ;;; We return a conflicting TN, or :OVERFLOW if the TN won't fit.
980 (defun load-tn-conflicts-in-sc (op sc offset ignore-live)
981   (let* ((sb (sc-sb sc))
982          (size (finite-sb-current-size sb)))
983     (do ((i offset (1+ i))
984          (end (+ offset (sc-element-size sc))))
985         ((= i end) nil)
986       (declare (type index i end))
987       (let ((res (or (when (>= i size) :overflow)
988                      (and (not ignore-live)
989                           (svref (finite-sb-live-tns sb) i))
990                      (load-tn-offset-conflicts-in-sb op sb i))))
991         (when res (return res))))))
992
993 ;;; If a load-TN for OP is targeted to a legal location in SC, then
994 ;;; return the offset, otherwise return NIL. We see whether the target
995 ;;; of the operand is packed, and try that location. There isn't any
996 ;;; need to chain down the target path, since everything is packed
997 ;;; now.
998 ;;;
999 ;;; We require the target to be in SC (and not merely to overlap with
1000 ;;; SC). This prevents SC information from being lost in load TNs (we
1001 ;;; won't pack a load TN in ANY-REG when it is targeted to a
1002 ;;; DESCRIPTOR-REG.) This shouldn't hurt the code as long as all
1003 ;;; relevant overlapping SCs are allowed in the operand SC
1004 ;;; restriction.
1005 (defun find-load-tn-target (op sc)
1006   (declare (inline member))
1007   (let ((target (tn-ref-target op)))
1008     (when target
1009       (let* ((tn (tn-ref-tn target))
1010              (loc (tn-offset tn)))
1011         (if (and (eq (tn-sc tn) sc)
1012                  (member (the index loc) (sc-locations sc))
1013                  (not (load-tn-conflicts-in-sc op sc loc nil)))
1014             loc
1015             nil)))))
1016
1017 ;;; Select a legal location for a load TN for Op in SC. We just
1018 ;;; iterate over the SC's locations. If we can't find a legal
1019 ;;; location, return NIL.
1020 (defun select-load-tn-location (op sc)
1021   (declare (type tn-ref op) (type sc sc))
1022
1023   ;; Check any target location first.
1024   (let ((target (tn-ref-target op)))
1025     (when target
1026       (let* ((tn (tn-ref-tn target))
1027              (loc (tn-offset tn)))
1028         (when (and (eq (sc-sb sc) (sc-sb (tn-sc tn)))
1029                    (member (the index loc) (sc-locations sc))
1030                    (not (load-tn-conflicts-in-sc op sc loc nil)))
1031               (return-from select-load-tn-location loc)))))
1032
1033   (dolist (loc (sc-locations sc) nil)
1034     (unless (load-tn-conflicts-in-sc op sc loc nil)
1035       (return loc))))
1036
1037 (defevent unpack-tn "Unpacked a TN to satisfy operand SC restriction.")
1038
1039 ;;; Make TN's location the same as for its save TN (allocating a save
1040 ;;; TN if necessary.) Delete any save/restore code that has been
1041 ;;; emitted thus far. Mark all blocks containing references as needing
1042 ;;; to be repacked.
1043 (defun unpack-tn (tn)
1044   (event unpack-tn)
1045   (let ((stn (or (tn-save-tn tn)
1046                  (pack-save-tn tn))))
1047     (setf (tn-sc tn) (tn-sc stn))
1048     (setf (tn-offset tn) (tn-offset stn))
1049     (flet ((zot (refs)
1050              (do ((ref refs (tn-ref-next ref)))
1051                  ((null ref))
1052                (let ((vop (tn-ref-vop ref)))
1053                  (if (eq (vop-info-name (vop-info vop)) 'move-operand)
1054                      (delete-vop vop)
1055                      (setf (gethash (vop-block vop) *repack-blocks*) t))))))
1056       (zot (tn-reads tn))
1057       (zot (tn-writes tn))))
1058
1059   (values))
1060
1061 (defevent unpack-fallback "Unpacked some operand TN.")
1062
1063 ;;; This is called by PACK-LOAD-TN where there isn't any location free
1064 ;;; that we can pack into. What we do is move some live TN in one of
1065 ;;; the specified SCs to memory, then mark this block all blocks that
1066 ;;; reference the TN as needing repacking. If we succeed, we throw to
1067 ;;; UNPACKED-TN. If we fail, we return NIL.
1068 ;;;
1069 ;;; We can unpack any live TN that appears in the NORMAL-TNs list
1070 ;;; (isn't wired or restricted.) We prefer to unpack TNs that are not
1071 ;;; used by the VOP. If we can't find any such TN, then we unpack some
1072 ;;; argument or result TN. The only way we can fail is if all
1073 ;;; locations in SC are used by load-TNs or temporaries in VOP.
1074 (defun unpack-for-load-tn (sc op)
1075   (declare (type sc sc) (type tn-ref op))
1076   (let ((sb (sc-sb sc))
1077         (normal-tns (ir2-component-normal-tns
1078                      (component-info *component-being-compiled*)))
1079         (node (vop-node (tn-ref-vop op)))
1080         (fallback nil))
1081     (flet ((unpack-em (victims)
1082              (unless *repack-blocks*
1083                (setq *repack-blocks* (make-hash-table :test 'eq)))
1084              (setf (gethash (vop-block (tn-ref-vop op)) *repack-blocks*) t)
1085              (dolist (victim victims)
1086                (event unpack-tn node)
1087                (unpack-tn victim))
1088              (throw 'unpacked-tn nil)))
1089       (dolist (loc (sc-locations sc))
1090         (declare (type index loc))
1091         (block SKIP
1092           (collect ((victims nil adjoin))
1093             (do ((i loc (1+ i))
1094                  (end (+ loc (sc-element-size sc))))
1095                 ((= i end))
1096               (declare (type index i end))
1097               (let ((victim (svref (finite-sb-live-tns sb) i)))
1098                 (when victim
1099                   (unless (find-in #'tn-next victim normal-tns)
1100                     (return-from SKIP))
1101                   (victims victim))))
1102
1103             (let ((conf (load-tn-conflicts-in-sc op sc loc t)))
1104               (cond ((not conf)
1105                      (unpack-em (victims)))
1106                     ((eq conf :overflow))
1107                     ((not fallback)
1108                      (cond ((find conf (victims))
1109                             (setq fallback (victims)))
1110                            ((find-in #'tn-next conf normal-tns)
1111                             (setq fallback (list conf))))))))))
1112
1113       (when fallback
1114         (event unpack-fallback node)
1115         (unpack-em fallback))))
1116
1117   nil)
1118
1119 ;;; Try to pack a load TN in the SCs indicated by Load-SCs. If we run
1120 ;;; out of SCs, then we unpack some TN and try again. We return the
1121 ;;; packed load TN.
1122 ;;;
1123 ;;; Note: we allow a Load-TN to be packed in the target location even
1124 ;;; if that location is in a SC not allowed by the primitive type.
1125 ;;; (The SC must still be allowed by the operand restriction.) This
1126 ;;; makes move VOPs more efficient, since we won't do a move from the
1127 ;;; stack into a non-descriptor any-reg though a descriptor argument
1128 ;;; load-TN. This does give targeting some real semantics, making it
1129 ;;; not a pure advisory to pack. It allows pack to do some packing it
1130 ;;; wouldn't have done before.
1131 (defun pack-load-tn (load-scs op)
1132   (declare (type sc-vector load-scs) (type tn-ref op))
1133   (let ((vop (tn-ref-vop op)))
1134     (compute-live-tns (vop-block vop) vop))
1135
1136   (let* ((tn (tn-ref-tn op))
1137          (ptype (tn-primitive-type tn))
1138          (scs (svref load-scs (sc-number (tn-sc tn)))))
1139     (let ((current-scs scs)
1140           (allowed ()))
1141       (loop
1142         (cond
1143          ((null current-scs)
1144           (unless allowed
1145             (no-load-scs-allowed-by-primitive-type-error op))
1146           (dolist (sc allowed)
1147             (unpack-for-load-tn sc op))
1148           (failed-to-pack-load-tn-error allowed op))
1149         (t
1150          (let* ((sc (svref *backend-sc-numbers* (pop current-scs)))
1151                 (target (find-load-tn-target op sc)))
1152            (when (or target (sc-allowed-by-primitive-type sc ptype))
1153              (let ((loc (or target
1154                             (select-load-tn-location op sc))))
1155                (when loc
1156                  (let ((res (make-tn 0 :load nil sc)))
1157                    (setf (tn-offset res) loc)
1158                    (return res))))
1159              (push sc allowed)))))))))
1160
1161 ;;; Scan a list of load-SCs vectors and a list of TN-REFS threaded by
1162 ;;; TN-REF-ACROSS. When we find a reference whose TN doesn't satisfy
1163 ;;; the restriction, we pack a Load-TN and load the operand into it.
1164 ;;; If a load-tn has already been allocated, we can assume that the
1165 ;;; restriction is satisfied.
1166 #!-sb-fluid (declaim (inline check-operand-restrictions))
1167 (defun check-operand-restrictions (scs ops)
1168   (declare (list scs) (type (or tn-ref null) ops))
1169
1170   ;; Check the targeted operands first.
1171   (do ((scs scs (cdr scs))
1172        (op ops (tn-ref-across op)))
1173       ((null scs))
1174       (let ((target (tn-ref-target op)))
1175         (when target
1176            (let* ((load-tn (tn-ref-load-tn op))
1177                   (load-scs (svref (car scs)
1178                                    (sc-number
1179                                     (tn-sc (or load-tn (tn-ref-tn op)))))))
1180              (if load-tn
1181                  (aver (eq load-scs t))
1182                (unless (eq load-scs t)
1183                        (setf (tn-ref-load-tn op)
1184                              (pack-load-tn (car scs) op))))))))
1185
1186   (do ((scs scs (cdr scs))
1187        (op ops (tn-ref-across op)))
1188       ((null scs))
1189       (let ((target (tn-ref-target op)))
1190         (unless target
1191            (let* ((load-tn (tn-ref-load-tn op))
1192                   (load-scs (svref (car scs)
1193                                    (sc-number
1194                                     (tn-sc (or load-tn (tn-ref-tn op)))))))
1195              (if load-tn
1196                  (aver (eq load-scs t))
1197                (unless (eq load-scs t)
1198                        (setf (tn-ref-load-tn op)
1199                              (pack-load-tn (car scs) op))))))))
1200
1201   (values))
1202
1203 ;;; Scan the VOPs in BLOCK, looking for operands whose SC restrictions
1204 ;;; aren't satisfied. We do the results first, since they are
1205 ;;; evaluated later, and our conflict analysis is a backward scan.
1206 (defun pack-load-tns (block)
1207   (catch 'unpacked-tn
1208     (let ((*live-block* nil)
1209           (*live-vop* nil))
1210       (do ((vop (ir2-block-last-vop block) (vop-prev vop)))
1211           ((null vop))
1212         (let ((info (vop-info vop)))
1213           (check-operand-restrictions (vop-info-result-load-scs info)
1214                                       (vop-results vop))
1215           (check-operand-restrictions (vop-info-arg-load-scs info)
1216                                       (vop-args vop))))))
1217   (values))
1218 \f
1219 ;;;; targeting
1220
1221 ;;; Link the TN-REFS READ and WRITE together using the TN-REF-TARGET
1222 ;;; when this seems like a good idea. Currently we always do, as this
1223 ;;; increases the success of load-TN targeting.
1224 (defun target-if-desirable (read write)
1225   (declare (type tn-ref read write))
1226   ;; As per the comments at the definition of TN-REF-TARGET, read and
1227   ;; write refs are always paired, with TARGET in the read pointing to
1228   ;; the write and vice versa.
1229   (aver (eq (tn-ref-write-p read)
1230             (not (tn-ref-write-p write))))
1231   (setf (tn-ref-target read) write)
1232   (setf (tn-ref-target write) read))
1233
1234 ;;; If TN can be packed into SC so as to honor a preference to TARGET,
1235 ;;; then return the offset to pack at, otherwise return NIL. TARGET
1236 ;;; must be already packed.
1237 (defun check-ok-target (target tn sc)
1238   (declare (type tn target tn) (type sc sc) (inline member))
1239   (let* ((loc (tn-offset target))
1240          (target-sc (tn-sc target))
1241          (target-sb (sc-sb target-sc)))
1242     (declare (type index loc))
1243     ;; We can honor a preference if:
1244     ;; -- TARGET's location is in SC's locations.
1245     ;; -- The element sizes of the two SCs are the same.
1246     ;; -- TN doesn't conflict with target's location.
1247     (if (and (eq target-sb (sc-sb sc))
1248              (or (eq (sb-kind target-sb) :unbounded)
1249                  (member loc (sc-locations sc)))
1250              (= (sc-element-size target-sc) (sc-element-size sc))
1251              (not (conflicts-in-sc tn sc loc))
1252              (zerop (mod loc (sc-alignment sc))))
1253         loc
1254         nil)))
1255
1256 ;;; Scan along the target path from TN, looking at readers or writers.
1257 ;;; When we find a packed TN, return CHECK-OK-TARGET of that TN. If
1258 ;;; there is no target, or if the TN has multiple readers (writers),
1259 ;;; then we return NIL. We also always return NIL after 10 iterations
1260 ;;; to get around potential circularity problems.
1261 ;;;
1262 ;;; FIXME: (30 minutes of reverse engineering?) It'd be nice to
1263 ;;; rewrite the header comment here to explain the interface and its
1264 ;;; motivation, and move remarks about implementation details (like
1265 ;;; 10!) inside.
1266 (defun find-ok-target-offset (tn sc)
1267   (declare (type tn tn) (type sc sc))
1268   (flet ((frob-slot (slot-fun)
1269            (declare (type function slot-fun))
1270            (let ((count 10)
1271                  (current tn))
1272              (declare (type index count))
1273              (loop
1274               (let ((refs (funcall slot-fun current)))
1275                 (unless (and (plusp count)
1276                              refs
1277                              (not (tn-ref-next refs)))
1278                   (return nil))
1279                 (let ((target (tn-ref-target refs)))
1280                   (unless target (return nil))
1281                   (setq current (tn-ref-tn target))
1282                   (when (tn-offset current)
1283                     (return (check-ok-target current tn sc)))
1284                   (decf count)))))))
1285     (declare (inline frob-slot)) ; until DYNAMIC-EXTENT works
1286     (or (frob-slot #'tn-reads)
1287         (frob-slot #'tn-writes))))
1288 \f
1289 ;;;; location selection
1290
1291 ;;; Select some location for TN in SC, returning the offset if we
1292 ;;; succeed, and NIL if we fail.
1293 ;;;
1294 ;;; For :UNBOUNDED SCs just find the smallest correctly aligned offset
1295 ;;; where the TN doesn't conflict with the TNs that have already been
1296 ;;; packed. For :FINITE SCs try to pack the TN into the most heavily
1297 ;;; used locations first (as estimated in FIND-LOCATION-USAGE).
1298 ;;;
1299 ;;; Historically SELECT-LOCATION tried did the opposite and tried to
1300 ;;; distribute the TNs evenly across the available locations. At least
1301 ;;; on register-starved architectures (x86) this seems to be a bad
1302 ;;; strategy. -- JES 2004-09-11
1303 (defun select-location (tn sc &key use-reserved-locs optimize)
1304   (declare (type tn tn) (type sc sc) (inline member))
1305   (let* ((sb (sc-sb sc))
1306          (element-size (sc-element-size sc))
1307          (alignment (sc-alignment sc))
1308          (align-mask (1- alignment))
1309          (size (finite-sb-current-size sb)))
1310     (flet ((attempt-location (start-offset)
1311              (dotimes (i element-size
1312                        (return-from select-location start-offset))
1313                (declare (type index i))
1314                (let ((offset (+ start-offset i)))
1315                  (when (offset-conflicts-in-sb tn sb offset)
1316                    (return (logandc2 (the index (+ (the index (1+ offset))
1317                                                    align-mask))
1318                                      align-mask)))))))
1319       (if (eq (sb-kind sb) :unbounded)
1320           (loop with offset = 0
1321                 until (> (+ offset element-size) size) do
1322                 (setf offset (attempt-location offset)))        
1323           (let ((locations (sc-locations sc)))
1324             (when optimize
1325               (setf locations
1326                     (stable-sort (copy-list locations) #'>
1327                                  :key (lambda (location-offset)
1328                                         (loop for offset from location-offset
1329                                               repeat element-size
1330                                               maximize (svref
1331                                                         (finite-sb-always-live-count sb)
1332                                                         offset))))))
1333             (dolist (offset locations)
1334               (when (or use-reserved-locs
1335                         (not (member offset
1336                                      (sc-reserve-locations sc))))
1337                 (attempt-location offset))))))))
1338
1339 ;;; If a save TN, return the saved TN, otherwise return TN. This is
1340 ;;; useful for getting the conflicts of a TN that might be a save TN.
1341 (defun original-tn (tn)
1342   (declare (type tn tn))
1343   (if (member (tn-kind tn) '(:save :save-once :specified-save))
1344       (tn-save-tn tn)
1345       tn))
1346 \f
1347 ;;;; pack interface
1348
1349 ;;; Attempt to pack TN in all possible SCs, first in the SC chosen by
1350 ;;; representation selection, then in the alternate SCs in the order
1351 ;;; they were specified in the SC definition. If the TN-COST is
1352 ;;; negative, then we don't attempt to pack in SCs that must be saved.
1353 ;;; If Restricted, then we can only pack in TN-SC, not in any
1354 ;;; Alternate-SCs.
1355 ;;;
1356 ;;; If we are attempting to pack in the SC of the save TN for a TN
1357 ;;; with a :SPECIFIED-SAVE TN, then we pack in that location, instead
1358 ;;; of allocating a new stack location.
1359 (defun pack-tn (tn restricted optimize)
1360   (declare (type tn tn))
1361   (let* ((original (original-tn tn))
1362          (fsc (tn-sc tn))
1363          (alternates (unless restricted (sc-alternate-scs fsc)))
1364          (save (tn-save-tn tn))
1365          (specified-save-sc
1366           (when (and save
1367                      (eq (tn-kind save) :specified-save))
1368             (tn-sc save))))
1369     (do ((sc fsc (pop alternates)))
1370         ((null sc)
1371          (failed-to-pack-error tn restricted))
1372       (when (eq sc specified-save-sc)
1373         (unless (tn-offset save)
1374           (pack-tn save nil optimize))
1375         (setf (tn-offset tn) (tn-offset save))
1376         (setf (tn-sc tn) (tn-sc save))
1377         (return))
1378       (when (or restricted
1379                 (not (and (minusp (tn-cost tn)) (sc-save-p sc))))
1380         (let ((loc (or (find-ok-target-offset original sc)
1381                        (select-location original sc)
1382                        (and restricted
1383                             (select-location original sc :use-reserved-locs t))
1384                        (when (eq (sb-kind (sc-sb sc)) :unbounded)
1385                          (grow-sc sc)
1386                          (or (select-location original sc)
1387                              (error "failed to pack after growing SC?"))))))
1388           (when loc
1389             (add-location-conflicts original sc loc optimize)
1390             (setf (tn-sc tn) sc)
1391             (setf (tn-offset tn) loc)
1392             (return))))))
1393   (values))
1394
1395 ;;; Pack a wired TN, checking that the offset is in bounds for the SB,
1396 ;;; and that the TN doesn't conflict with some other TN already packed
1397 ;;; in that location. If the TN is wired to a location beyond the end
1398 ;;; of a :UNBOUNDED SB, then grow the SB enough to hold the TN.
1399 ;;;
1400 ;;; ### Checking for conflicts is disabled for :SPECIFIED-SAVE TNs.
1401 ;;; This is kind of a hack to make specifying wired stack save
1402 ;;; locations for local call arguments (such as OLD-FP) work, since
1403 ;;; the caller and callee OLD-FP save locations may conflict when the
1404 ;;; save locations don't really (due to being in different frames.)
1405 (defun pack-wired-tn (tn optimize)
1406   (declare (type tn tn))
1407   (let* ((sc (tn-sc tn))
1408          (sb (sc-sb sc))
1409          (offset (tn-offset tn))
1410          (end (+ offset (sc-element-size sc)))
1411          (original (original-tn tn)))
1412     (when (> end (finite-sb-current-size sb))
1413       (unless (eq (sb-kind sb) :unbounded)
1414         (error "~S is wired to a location that is out of bounds." tn))
1415       (grow-sc sc end))
1416
1417     ;; For non-x86 ports the presence of a save-tn associated with a
1418     ;; tn is used to identify the old-fp and return-pc tns. It depends
1419     ;; on the old-fp and return-pc being passed in registers.
1420     #!-x86
1421     (when (and (not (eq (tn-kind tn) :specified-save))
1422                (conflicts-in-sc original sc offset))
1423       (error "~S is wired to a location that it conflicts with." tn))
1424
1425     ;; Use the above check, but only print a verbose warning. This can
1426     ;; be helpful for debugging the x86 port.
1427     #+nil
1428     (when (and (not (eq (tn-kind tn) :specified-save))
1429                (conflicts-in-sc original sc offset))
1430           (format t "~&* Pack-wired-tn possible conflict:~%  ~
1431                      tn: ~S; tn-kind: ~S~%  ~
1432                      sc: ~S~%  ~
1433                      sb: ~S; sb-name: ~S; sb-kind: ~S~%  ~
1434                      offset: ~S; end: ~S~%  ~
1435                      original ~S~%  ~
1436                      tn-save-tn: ~S; tn-kind of tn-save-tn: ~S~%"
1437                   tn (tn-kind tn) sc
1438                   sb (sb-name sb) (sb-kind sb)
1439                   offset end
1440                   original
1441                   (tn-save-tn tn) (tn-kind (tn-save-tn tn))))
1442
1443     ;; On the x86 ports the old-fp and return-pc are often passed on
1444     ;; the stack so the above hack for the other ports does not always
1445     ;; work. Here the old-fp and return-pc tns are identified by being
1446     ;; on the stack in their standard save locations.
1447     #!+x86
1448     (when (and (not (eq (tn-kind tn) :specified-save))
1449                (not (and (string= (sb-name sb) "STACK")
1450                          (or (= offset 0)
1451                              (= offset 1))))
1452                (conflicts-in-sc original sc offset))
1453       (error "~S is wired to a location that it conflicts with." tn))
1454
1455     (add-location-conflicts original sc offset optimize)))
1456
1457 (defevent repack-block "Repacked a block due to TN unpacking.")
1458
1459 ;;; KLUDGE: Prior to SBCL version 0.8.9.xx, this function was known as
1460 ;;; PACK-BEFORE-GC-HOOK, but was non-functional since approximately
1461 ;;; version 0.8.3.xx since the removal of GC hooks from the system.
1462 ;;; This currently (as of 2004-04-12) runs now after every call to
1463 ;;; PACK, rather than -- as was originally intended -- once per GC
1464 ;;; cycle; this is probably non-optimal, and might require tuning,
1465 ;;; maybe to be called when the data structures exceed a certain size,
1466 ;;; or maybe once every N times.  The KLUDGE is that this rewrite has
1467 ;;; done nothing to improve the reentrance or threadsafety of the
1468 ;;; compiler; it still fails to be callable from several threads at
1469 ;;; the same time.
1470 ;;;
1471 ;;; Brief experiments indicate that during a compilation cycle this
1472 ;;; causes about 10% more consing, and takes about 1%-2% more time.
1473 ;;;
1474 ;;; -- CSR, 2004-04-12
1475 (defun clean-up-pack-structures ()
1476   (dolist (sb *backend-sb-list*)
1477     (unless (eq (sb-kind sb) :non-packed)
1478       (let ((size (sb-size sb)))
1479         (fill (finite-sb-always-live sb) nil)
1480         (setf (finite-sb-always-live sb)
1481               (make-array size
1482                           :initial-element
1483                           #-sb-xc #*
1484                           ;; The cross-compiler isn't very good at
1485                           ;; dumping specialized arrays, so we delay
1486                           ;; construction of this SIMPLE-BIT-VECTOR
1487                           ;; until runtime.
1488                           #+sb-xc (make-array 0 :element-type 'bit)))
1489         (setf (finite-sb-always-live-count sb)
1490               (make-array size
1491                           :initial-element    
1492                           #-sb-xc #*
1493                           ;; Ibid
1494                           #+sb-xc (make-array 0 :element-type 'fixnum)))
1495         
1496         (fill (finite-sb-conflicts sb) nil)
1497         (setf (finite-sb-conflicts sb)
1498               (make-array size :initial-element '#()))
1499         
1500         (fill (finite-sb-live-tns sb) nil)
1501         (setf (finite-sb-live-tns sb)
1502               (make-array size :initial-element nil))))))
1503
1504 (defun pack (component)
1505   (unwind-protect
1506        (let ((optimize nil)
1507              (2comp (component-info component)))
1508          (init-sb-vectors component)
1509
1510          ;; Determine whether we want to do more expensive packing by
1511          ;; checking whether any blocks in the component have (> SPEED
1512          ;; COMPILE-SPEED).
1513          ;; 
1514          ;; FIXME: This means that a declaration can have a minor
1515          ;; effect even outside its scope, and as the packing is done
1516          ;; component-globally it'd be tricky to use strict scoping. I
1517          ;; think this is still acceptable since it's just a tradeoff
1518          ;; between compilation speed and allocation quality and
1519          ;; doesn't affect the semantics of the generated code in any
1520          ;; way. -- JES 2004-10-06
1521          (do-ir2-blocks (block component)
1522            (when (policy (block-last (ir2-block-block block))
1523                          (> speed compilation-speed))
1524              (setf optimize t)
1525              (return)))
1526          
1527          ;; Call the target functions.
1528          (do-ir2-blocks (block component)
1529            (do ((vop (ir2-block-start-vop block) (vop-next vop)))
1530                ((null vop))
1531              (let ((target-fun (vop-info-target-fun (vop-info vop))))
1532                (when target-fun
1533                  (funcall target-fun vop)))))
1534          
1535          ;; Pack wired TNs first.
1536          (do ((tn (ir2-component-wired-tns 2comp) (tn-next tn)))
1537              ((null tn))
1538            (pack-wired-tn tn optimize))
1539          
1540          ;; Pack restricted component TNs.
1541          (do ((tn (ir2-component-restricted-tns 2comp) (tn-next tn)))
1542              ((null tn))
1543            (when (eq (tn-kind tn) :component)
1544              (pack-tn tn t optimize)))
1545          
1546          ;; Pack other restricted TNs.
1547          (do ((tn (ir2-component-restricted-tns 2comp) (tn-next tn)))
1548              ((null tn))
1549            (unless (tn-offset tn)
1550              (pack-tn tn t optimize)))
1551          
1552          ;; Assign costs to normal TNs so we know which ones should
1553          ;; always be packed on the stack.
1554          (when *pack-assign-costs*
1555            (assign-tn-costs component)
1556            (assign-tn-depths component))
1557
1558          ;; Allocate normal TNs, starting with the TNs that are used
1559          ;; in deep loops.
1560          (collect ((tns))
1561            (do-ir2-blocks (block component)
1562              (let ((ltns (ir2-block-local-tns block)))
1563                (do ((i (1- (ir2-block-local-tn-count block)) (1- i)))
1564                    ((minusp i))
1565                  (declare (fixnum i))
1566                  (let ((tn (svref ltns i)))
1567                    (unless (or (null tn)
1568                                (eq tn :more)
1569                                (tn-offset tn))
1570                      ;; If loop analysis has been disabled we might as
1571                      ;; well revert to the old behaviour of just
1572                      ;; packing TNs linearly as they appear.
1573                      (unless *loop-analyze*
1574                        (pack-tn tn nil optimize))
1575                      (tns tn))))))
1576            (dolist (tn (stable-sort (tns)
1577                                     (lambda (a b)
1578                                       (cond
1579                                         ((> (tn-loop-depth a)
1580                                             (tn-loop-depth b))
1581                                          t)
1582                                         ((= (tn-loop-depth a)
1583                                             (tn-loop-depth b))
1584                                          (> (tn-cost a) (tn-cost b)))
1585                                         (t nil)))))
1586              (unless (tn-offset tn)
1587                (pack-tn tn nil optimize))))
1588            
1589          ;; Pack any leftover normal TNs. This is to deal with :MORE TNs,
1590          ;; which could possibly not appear in any local TN map.
1591          (do ((tn (ir2-component-normal-tns 2comp) (tn-next tn)))
1592              ((null tn))
1593            (unless (tn-offset tn)
1594              (pack-tn tn nil optimize)))
1595          
1596          ;; Do load TN packing and emit saves.
1597          (let ((*repack-blocks* nil))
1598            (cond ((and optimize *pack-optimize-saves*)
1599                   (optimized-emit-saves component)
1600                   (do-ir2-blocks (block component)
1601                     (pack-load-tns block)))
1602                  (t
1603                   (do-ir2-blocks (block component)
1604                     (emit-saves block)
1605                     (pack-load-tns block))))
1606            (when *repack-blocks*
1607              (loop
1608                  (when (zerop (hash-table-count *repack-blocks*)) (return))
1609                  (maphash (lambda (block v)
1610                             (declare (ignore v))
1611                             (remhash block *repack-blocks*)
1612                             (event repack-block)
1613                             (pack-load-tns block))
1614                           *repack-blocks*))))
1615          
1616          (values))
1617     (clean-up-pack-structures)))