tweak tail merging logic
[sbcl.git] / src / compiler / ir1util.lisp
1 ;;;; This file contains miscellaneous utilities used for manipulating
2 ;;;; the IR1 representation.
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14 \f
15 ;;;; cleanup hackery
16
17 ;;; Return the innermost cleanup enclosing NODE, or NIL if there is
18 ;;; none in its function. If NODE has no cleanup, but is in a LET,
19 ;;; then we must still check the environment that the call is in.
20 (defun node-enclosing-cleanup (node)
21   (declare (type node node))
22   (do ((lexenv (node-lexenv node)
23                (lambda-call-lexenv (lexenv-lambda lexenv))))
24       ((null lexenv) nil)
25     (let ((cup (lexenv-cleanup lexenv)))
26       (when cup (return cup)))))
27
28 ;;; Convert the FORM in a block inserted between BLOCK1 and BLOCK2 as
29 ;;; an implicit MV-PROG1. The inserted block is returned. NODE is used
30 ;;; for IR1 context when converting the form. Note that the block is
31 ;;; not assigned a number, and is linked into the DFO at the
32 ;;; beginning. We indicate that we have trashed the DFO by setting
33 ;;; COMPONENT-REANALYZE. If CLEANUP is supplied, then convert with
34 ;;; that cleanup.
35 (defun insert-cleanup-code (block1 block2 node form &optional cleanup)
36   (declare (type cblock block1 block2) (type node node)
37            (type (or cleanup null) cleanup))
38   (setf (component-reanalyze (block-component block1)) t)
39   (with-ir1-environment-from-node node
40     (with-component-last-block (*current-component*
41                                 (block-next (component-head *current-component*)))
42       (let* ((start (make-ctran))
43              (block (ctran-starts-block start))
44              (next (make-ctran))
45              (*lexenv* (if cleanup
46                            (make-lexenv :cleanup cleanup)
47                            *lexenv*)))
48         (change-block-successor block1 block2 block)
49         (link-blocks block block2)
50         (ir1-convert start next nil form)
51         (setf (block-last block) (ctran-use next))
52         (setf (node-next (block-last block)) nil)
53         block))))
54 \f
55 ;;;; lvar use hacking
56
57 ;;; Return a list of all the nodes which use LVAR.
58 (declaim (ftype (sfunction (lvar) list) find-uses))
59 (defun find-uses (lvar)
60   (let ((uses (lvar-uses lvar)))
61     (if (listp uses)
62         uses
63         (list uses))))
64
65 (declaim (ftype (sfunction (lvar) lvar) principal-lvar))
66 (defun principal-lvar (lvar)
67   (labels ((pl (lvar)
68              (let ((use (lvar-uses lvar)))
69                (if (cast-p use)
70                    (pl (cast-value use))
71                    lvar))))
72     (pl lvar)))
73
74 (defun principal-lvar-use (lvar)
75   (labels ((plu (lvar)
76              (declare (type lvar lvar))
77              (let ((use (lvar-uses lvar)))
78                (if (cast-p use)
79                    (plu (cast-value use))
80                    use))))
81     (plu lvar)))
82
83 ;;; Update lvar use information so that NODE is no longer a use of its
84 ;;; LVAR.
85 ;;;
86 ;;; Note: if you call this function, you may have to do a
87 ;;; REOPTIMIZE-LVAR to inform IR1 optimization that something has
88 ;;; changed.
89 (declaim (ftype (sfunction (node) (values))
90                 delete-lvar-use
91                 %delete-lvar-use))
92 ;;; Just delete NODE from its LVAR uses; LVAR is preserved so it may
93 ;;; be given a new use.
94 (defun %delete-lvar-use (node)
95   (let ((lvar (node-lvar node)))
96     (when lvar
97       (if (listp (lvar-uses lvar))
98           (let ((new-uses (delq node (lvar-uses lvar))))
99             (setf (lvar-uses lvar)
100                   (if (singleton-p new-uses)
101                       (first new-uses)
102                       new-uses)))
103           (setf (lvar-uses lvar) nil))
104       (setf (node-lvar node) nil)))
105   (values))
106 ;;; Delete NODE from its LVAR uses; if LVAR has no other uses, delete
107 ;;; its DEST's block, which must be unreachable.
108 (defun delete-lvar-use (node)
109   (let ((lvar (node-lvar node)))
110     (when lvar
111       (%delete-lvar-use node)
112       (if (null (lvar-uses lvar))
113           (binding* ((dest (lvar-dest lvar) :exit-if-null)
114                      (() (not (node-deleted dest)) :exit-if-null)
115                      (block (node-block dest)))
116             (mark-for-deletion block))
117           (reoptimize-lvar lvar))))
118   (values))
119
120 ;;; Update lvar use information so that NODE uses LVAR.
121 ;;;
122 ;;; Note: if you call this function, you may have to do a
123 ;;; REOPTIMIZE-LVAR to inform IR1 optimization that something has
124 ;;; changed.
125 (declaim (ftype (sfunction (node (or lvar null)) (values)) add-lvar-use))
126 (defun add-lvar-use (node lvar)
127   (aver (not (node-lvar node)))
128   (when lvar
129     (let ((uses (lvar-uses lvar)))
130       (setf (lvar-uses lvar)
131             (cond ((null uses)
132                    node)
133                   ((listp uses)
134                    (cons node uses))
135                   (t
136                    (list node uses))))
137       (setf (node-lvar node) lvar)))
138
139   (values))
140
141 ;;; Return true if LVAR destination is executed immediately after
142 ;;; NODE. Cleanups are ignored.
143 (defun immediately-used-p (lvar node)
144   (declare (type lvar lvar) (type node node))
145   (aver (eq (node-lvar node) lvar))
146   (let ((dest (lvar-dest lvar)))
147     (acond ((node-next node)
148             (eq (ctran-next it) dest))
149            (t (eq (block-start (first (block-succ (node-block node))))
150                   (node-prev dest))))))
151
152 ;;; Returns the defined (usually untrusted) type of the combination,
153 ;;; or NIL if we couldn't figure it out.
154 (defun combination-defined-type (combination)
155   (let ((use (principal-lvar-use (basic-combination-fun combination))))
156     (or (when (ref-p use)
157           (let ((type (leaf-defined-type (ref-leaf use))))
158             (when (fun-type-p type)
159               (fun-type-returns type))))
160         *wild-type*)))
161
162 ;;; Return true if LVAR destination is executed after node with only
163 ;;; uninteresting nodes intervening.
164 ;;;
165 ;;; Uninteresting nodes are nodes in the same block which are either
166 ;;; REFs, external CASTs to the same destination, or known combinations
167 ;;; that never unwind.
168 (defun almost-immediately-used-p (lvar node)
169   (declare (type lvar lvar)
170            (type node node))
171   (aver (eq (node-lvar node) lvar))
172   (let ((dest (lvar-dest lvar)))
173     (tagbody
174      :next
175        (let ((ctran (node-next node)))
176          (cond (ctran
177                 (setf node (ctran-next ctran))
178                 (if (eq node dest)
179                     (return-from almost-immediately-used-p t)
180                     (typecase node
181                       (ref
182                        (go :next))
183                       (cast
184                        (when (and (eq :external (cast-type-check node))
185                                   (eq dest (node-dest node)))
186                          (go :next)))
187                       (combination
188                        ;; KLUDGE: Unfortunately we don't have an attribute for
189                        ;; "never unwinds", so we just special case
190                        ;; %ALLOCATE-CLOSURES: it is easy to run into with eg.
191                        ;; FORMAT and a non-constant first argument.
192                        (when (eq '%allocate-closures (combination-fun-source-name node nil))
193                          (go :next))))))
194                (t
195                 (when (eq (block-start (first (block-succ (node-block node))))
196                           (node-prev dest))
197                   (return-from almost-immediately-used-p t))))))))
198 \f
199 ;;;; lvar substitution
200
201 ;;; In OLD's DEST, replace OLD with NEW. NEW's DEST must initially be
202 ;;; NIL. We do not flush OLD's DEST.
203 (defun substitute-lvar (new old)
204   (declare (type lvar old new))
205   (aver (not (lvar-dest new)))
206   (let ((dest (lvar-dest old)))
207     (etypecase dest
208       ((or ref bind))
209       (cif (setf (if-test dest) new))
210       (cset (setf (set-value dest) new))
211       (creturn (setf (return-result dest) new))
212       (exit (setf (exit-value dest) new))
213       (basic-combination
214        (if (eq old (basic-combination-fun dest))
215            (setf (basic-combination-fun dest) new)
216            (setf (basic-combination-args dest)
217                  (nsubst new old (basic-combination-args dest)))))
218       (cast (setf (cast-value dest) new)))
219
220     (setf (lvar-dest old) nil)
221     (setf (lvar-dest new) dest)
222     (flush-lvar-externally-checkable-type new))
223   (values))
224
225 ;;; Replace all uses of OLD with uses of NEW, where NEW has an
226 ;;; arbitary number of uses. NEW is supposed to be "later" than OLD.
227 (defun substitute-lvar-uses (new old propagate-dx)
228   (declare (type lvar old)
229            (type (or lvar null) new)
230            (type boolean propagate-dx))
231
232   (cond (new
233          (do-uses (node old)
234            (%delete-lvar-use node)
235            (add-lvar-use node new))
236          (reoptimize-lvar new)
237          (awhen (and propagate-dx (lvar-dynamic-extent old))
238            (setf (lvar-dynamic-extent old) nil)
239            (unless (lvar-dynamic-extent new)
240              (setf (lvar-dynamic-extent new) it)
241              (setf (cleanup-info it) (subst new old (cleanup-info it)))))
242          (when (lvar-dynamic-extent new)
243            (do-uses (node new)
244              (node-ends-block node))))
245         (t (flush-dest old)))
246
247   (values))
248 \f
249 ;;;; block starting/creation
250
251 ;;; Return the block that CTRAN is the start of, making a block if
252 ;;; necessary. This function is called by IR1 translators which may
253 ;;; cause a CTRAN to be used more than once. Every CTRAN which may be
254 ;;; used more than once must start a block by the time that anyone
255 ;;; does a USE-CTRAN on it.
256 ;;;
257 ;;; We also throw the block into the next/prev list for the
258 ;;; *CURRENT-COMPONENT* so that we keep track of which blocks we have
259 ;;; made.
260 (defun ctran-starts-block (ctran)
261   (declare (type ctran ctran))
262   (ecase (ctran-kind ctran)
263     (:unused
264      (aver (not (ctran-block ctran)))
265      (let* ((next (component-last-block *current-component*))
266             (prev (block-prev next))
267             (new-block (make-block ctran)))
268        (setf (block-next new-block) next
269              (block-prev new-block) prev
270              (block-prev next) new-block
271              (block-next prev) new-block
272              (ctran-block ctran) new-block
273              (ctran-kind ctran) :block-start)
274        (aver (not (ctran-use ctran)))
275        new-block))
276     (:block-start
277      (ctran-block ctran))))
278
279 ;;; Ensure that CTRAN is the start of a block so that the use set can
280 ;;; be freely manipulated.
281 (defun ensure-block-start (ctran)
282   (declare (type ctran ctran))
283   (let ((kind (ctran-kind ctran)))
284     (ecase kind
285       ((:block-start))
286       ((:unused)
287        (setf (ctran-block ctran)
288              (make-block-key :start ctran))
289        (setf (ctran-kind ctran) :block-start))
290       ((:inside-block)
291        (node-ends-block (ctran-use ctran)))))
292   (values))
293
294 ;;; CTRAN must be the last ctran in an incomplete block; finish the
295 ;;; block and start a new one if necessary.
296 (defun start-block (ctran)
297   (declare (type ctran ctran))
298   (aver (not (ctran-next ctran)))
299   (ecase (ctran-kind ctran)
300     (:inside-block
301      (let ((block (ctran-block ctran))
302            (node (ctran-use ctran)))
303        (aver (not (block-last block)))
304        (aver node)
305        (setf (block-last block) node)
306        (setf (node-next node) nil)
307        (setf (ctran-use ctran) nil)
308        (setf (ctran-kind ctran) :unused)
309        (setf (ctran-block ctran) nil)
310        (link-blocks block (ctran-starts-block ctran))))
311     (:block-start)))
312 \f
313 ;;;;
314
315 ;;; Filter values of LVAR through FORM, which must be an ordinary/mv
316 ;;; call. First argument must be 'DUMMY, which will be replaced with
317 ;;; LVAR. In case of an ordinary call the function should not have
318 ;;; return type NIL. We create a new "filtered" lvar.
319 ;;;
320 ;;; TODO: remove preconditions.
321 (defun filter-lvar (lvar form)
322   (declare (type lvar lvar) (type list form))
323   (let* ((dest (lvar-dest lvar))
324          (ctran (node-prev dest)))
325     (with-ir1-environment-from-node dest
326
327       (ensure-block-start ctran)
328       (let* ((old-block (ctran-block ctran))
329              (new-start (make-ctran))
330              (filtered-lvar (make-lvar))
331              (new-block (ctran-starts-block new-start)))
332
333         ;; Splice in the new block before DEST, giving the new block
334         ;; all of DEST's predecessors.
335         (dolist (block (block-pred old-block))
336           (change-block-successor block old-block new-block))
337
338         (ir1-convert new-start ctran filtered-lvar form)
339
340         ;; KLUDGE: Comments at the head of this function in CMU CL
341         ;; said that somewhere in here we
342         ;;   Set the new block's start and end cleanups to the *start*
343         ;;   cleanup of PREV's block. This overrides the incorrect
344         ;;   default from WITH-IR1-ENVIRONMENT-FROM-NODE.
345         ;; Unfortunately I can't find any code which corresponds to this.
346         ;; Perhaps it was a stale comment? Or perhaps I just don't
347         ;; understand.. -- WHN 19990521
348
349         ;; Replace 'DUMMY with the LVAR. (We can find 'DUMMY because
350         ;; no LET conversion has been done yet.) The [mv-]combination
351         ;; code from the call in the form will be the use of the new
352         ;; check lvar. We substitute for the first argument of
353         ;; this node.
354         (let* ((node (lvar-use filtered-lvar))
355                (args (basic-combination-args node))
356                (victim (first args)))
357           (aver (eq (constant-value (ref-leaf (lvar-use victim)))
358                     'dummy))
359
360           (substitute-lvar filtered-lvar lvar)
361           (substitute-lvar lvar victim)
362           (flush-dest victim))
363
364         ;; Invoking local call analysis converts this call to a LET.
365         (locall-analyze-component *current-component*))))
366   (values))
367
368 ;;; Delete NODE and VALUE. It may result in some calls becoming tail.
369 (defun delete-filter (node lvar value)
370   (aver (eq (lvar-dest value) node))
371   (aver (eq (node-lvar node) lvar))
372   (cond (lvar (collect ((merges))
373                 (when (return-p (lvar-dest lvar))
374                   (do-uses (use value)
375                     (when (and (basic-combination-p use)
376                                (eq (basic-combination-kind use) :local))
377                       (merges use))))
378                 (substitute-lvar-uses lvar value
379                                       (and lvar (eq (lvar-uses lvar) node)))
380                 (%delete-lvar-use node)
381                 (prog1
382                     (unlink-node node)
383                   (dolist (merge (merges))
384                     (merge-tail-sets merge)))))
385         (t (flush-dest value)
386            (unlink-node node))))
387
388 ;;; Make a CAST and insert it into IR1 before node NEXT.
389 (defun insert-cast-before (next lvar type policy)
390   (declare (type node next) (type lvar lvar) (type ctype type))
391   (with-ir1-environment-from-node next
392     (let* ((ctran (node-prev next))
393            (cast (make-cast lvar type policy))
394            (internal-ctran (make-ctran)))
395       (setf (ctran-next ctran) cast
396             (node-prev cast) ctran)
397       (use-ctran cast internal-ctran)
398       (link-node-to-previous-ctran next internal-ctran)
399       (setf (lvar-dest lvar) cast)
400       (reoptimize-lvar lvar)
401       (when (return-p next)
402         (node-ends-block cast))
403       (setf (block-attributep (block-flags (node-block cast))
404                               type-check type-asserted)
405             t)
406       cast)))
407 \f
408 ;;;; miscellaneous shorthand functions
409
410 ;;; Return the home (i.e. enclosing non-LET) CLAMBDA for NODE. Since
411 ;;; the LEXENV-LAMBDA may be deleted, we must chain up the
412 ;;; LAMBDA-CALL-LEXENV thread until we find a CLAMBDA that isn't
413 ;;; deleted, and then return its home.
414 (defun node-home-lambda (node)
415   (declare (type node node))
416   (do ((fun (lexenv-lambda (node-lexenv node))
417             (lexenv-lambda (lambda-call-lexenv fun))))
418       ((not (memq (functional-kind fun) '(:deleted :zombie)))
419        (lambda-home fun))
420     (when (eq (lambda-home fun) fun)
421       (return fun))))
422
423 #!-sb-fluid (declaim (inline node-block))
424 (defun node-block (node)
425   (ctran-block (node-prev node)))
426 (declaim (ftype (sfunction (node) component) node-component))
427 (defun node-component (node)
428   (block-component (node-block node)))
429 (declaim (ftype (sfunction (node) physenv) node-physenv))
430 (defun node-physenv (node)
431   (lambda-physenv (node-home-lambda node)))
432 #!-sb-fluid (declaim (inline node-dest))
433 (defun node-dest (node)
434   (awhen (node-lvar node) (lvar-dest it)))
435
436 #!-sb-fluid (declaim (inline node-stack-allocate-p))
437 (defun node-stack-allocate-p (node)
438   (awhen (node-lvar node)
439     (lvar-dynamic-extent it)))
440
441 (defun flushable-combination-p (call)
442   (declare (type combination call))
443   (let ((kind (combination-kind call))
444         (info (combination-fun-info call)))
445     (when (and (eq kind :known) (fun-info-p info))
446       (let ((attr (fun-info-attributes info)))
447         (when (and (not (ir1-attributep attr call))
448                    ;; FIXME: For now, don't consider potentially flushable
449                    ;; calls flushable when they have the CALL attribute.
450                    ;; Someday we should look at the functional args to
451                    ;; determine if they have any side effects.
452                    (if (policy call (= safety 3))
453                        (ir1-attributep attr flushable)
454                        (ir1-attributep attr unsafely-flushable)))
455           t)))))
456
457 ;;;; DYNAMIC-EXTENT related
458
459 (defun note-no-stack-allocation (lvar &key flush)
460   (do-uses (use (principal-lvar lvar))
461     (unless (or
462              ;; Don't complain about not being able to stack allocate constants.
463              (and (ref-p use) (constant-p (ref-leaf use)))
464              ;; If we're flushing, don't complain if we can flush the combination.
465              (and flush (combination-p use) (flushable-combination-p use)))
466       (let ((*compiler-error-context* use))
467         (compiler-notify "could not stack allocate the result of ~S"
468                          (find-original-source (node-source-path use)))))))
469
470 (defun use-good-for-dx-p (use dx &optional component)
471   ;; FIXME: Can casts point to LVARs in other components?
472   ;; RECHECK-DYNAMIC-EXTENT-LVARS assumes that they can't -- that is, that the
473   ;; PRINCIPAL-LVAR is always in the same component as the original one. It
474   ;; would be either good to have an explanation of why casts don't point
475   ;; across components, or an explanation of when they do it. ...in the
476   ;; meanwhile AVER that our assumption holds true.
477   (aver (or (not component) (eq component (node-component use))))
478   (or (dx-combination-p use dx)
479       (and (cast-p use)
480            (not (cast-type-check use))
481            (lvar-good-for-dx-p (cast-value use) dx component))
482       (and (trivial-lambda-var-ref-p use)
483            (let ((uses (lvar-uses (trivial-lambda-var-ref-lvar use))))
484              (or (eq use uses)
485                  (lvar-good-for-dx-p (trivial-lambda-var-ref-lvar use) dx component))))))
486
487 (defun lvar-good-for-dx-p (lvar dx &optional component)
488   (let ((uses (lvar-uses lvar)))
489     (if (listp uses)
490         (when uses
491           (every (lambda (use)
492                    (use-good-for-dx-p use dx component))
493                  uses))
494         (use-good-for-dx-p uses dx component))))
495
496 (defun known-dx-combination-p (use dx)
497   (and (eq (combination-kind use) :known)
498        (let ((info (combination-fun-info use)))
499          (or (awhen (fun-info-stack-allocate-result info)
500                (funcall it use dx))
501              (awhen (fun-info-result-arg info)
502                (let ((args (combination-args use)))
503                  (lvar-good-for-dx-p (if (zerop it)
504                                          (car args)
505                                          (nth it args))
506                                      dx)))))))
507
508 (defun dx-combination-p (use dx)
509   (and (combination-p use)
510        (or
511         ;; Known, and can do DX.
512         (known-dx-combination-p use dx)
513         ;; Possibly a not-yet-eliminated lambda which ends up returning the
514         ;; results of an actual known DX combination.
515         (let* ((fun (combination-fun use))
516                (ref (principal-lvar-use fun))
517                (clambda (when (ref-p ref)
518                           (ref-leaf ref)))
519                (creturn (when (lambda-p clambda)
520                           (lambda-return clambda)))
521                (result-use (when (return-p creturn)
522                              (principal-lvar-use (return-result creturn)))))
523           ;; FIXME: We should be able to deal with multiple uses here as well.
524           (and (dx-combination-p result-use dx)
525                (combination-args-flow-cleanly-p use result-use dx))))))
526
527 (defun combination-args-flow-cleanly-p (combination1 combination2 dx)
528   (labels ((recurse (combination)
529              (or (eq combination combination2)
530                  (if (known-dx-combination-p combination dx)
531                      (let ((dest (lvar-dest (combination-lvar combination))))
532                        (and (combination-p dest)
533                             (recurse dest)))
534                      (let* ((fun1 (combination-fun combination))
535                             (ref1 (principal-lvar-use fun1))
536                             (clambda1 (when (ref-p ref1) (ref-leaf ref1))))
537                        (when (lambda-p clambda1)
538                          (dolist (var (lambda-vars clambda1) t)
539                            (dolist (var-ref (lambda-var-refs var))
540                              (let ((dest (lvar-dest (ref-lvar var-ref))))
541                                (unless (and (combination-p dest) (recurse dest))
542                                  (return-from combination-args-flow-cleanly-p nil)))))))))))
543     (recurse combination1)))
544
545 (defun trivial-lambda-var-ref-p (use)
546   (and (ref-p use)
547        (let ((var (ref-leaf use)))
548          ;; lambda-var, no SETS, not explicitly indefinite-extent.
549          (when (and (lambda-var-p var) (not (lambda-var-sets var))
550                     (neq :indefinite (lambda-var-extent var)))
551            (let ((home (lambda-var-home var))
552                  (refs (lambda-var-refs var)))
553              ;; bound by a system lambda, no other REFS
554              (when (and (lambda-system-lambda-p home)
555                         (eq use (car refs)) (not (cdr refs)))
556                ;; the LAMBDA this var is bound by has only a single REF, going
557                ;; to a combination
558                (let* ((lambda-refs (lambda-refs home))
559                       (primary (car lambda-refs)))
560                  (and (ref-p primary)
561                       (not (cdr lambda-refs))
562                       (combination-p (lvar-dest (ref-lvar primary)))))))))))
563
564 (defun trivial-lambda-var-ref-lvar (use)
565   (let* ((this (ref-leaf use))
566          (home (lambda-var-home this)))
567     (multiple-value-bind (fun vars)
568         (values home (lambda-vars home))
569       (let* ((combination (lvar-dest (ref-lvar (car (lambda-refs fun)))))
570              (args (combination-args combination)))
571         (assert (= (length vars) (length args)))
572         (loop for var in vars
573               for arg in args
574               when (eq var this)
575               return arg)))))
576
577 ;;; This needs to play nice with LVAR-GOOD-FOR-DX-P and friends.
578 (defun handle-nested-dynamic-extent-lvars (dx lvar &optional recheck-component)
579   (let ((uses (lvar-uses lvar)))
580     ;; DX value generators must end their blocks: see UPDATE-UVL-LIVE-SETS.
581     ;; Uses of mupltiple-use LVARs already end their blocks, so we just need
582     ;; to process uses of single-use LVARs.
583     (when (node-p uses)
584       (node-ends-block uses))
585     ;; If this LVAR's USE is good for DX, it is either a CAST, or it
586     ;; must be a regular combination whose arguments are potentially DX as well.
587     (flet ((recurse (use)
588              (etypecase use
589                (cast
590                 (handle-nested-dynamic-extent-lvars
591                  dx (cast-value use) recheck-component))
592                (combination
593                 (loop for arg in (combination-args use)
594                       ;; deleted args show up as NIL here
595                       when (and arg
596                                 (lvar-good-for-dx-p arg dx recheck-component))
597                       append (handle-nested-dynamic-extent-lvars
598                               dx arg recheck-component)))
599                (ref
600                 (let* ((other (trivial-lambda-var-ref-lvar use)))
601                   (print (list :ref use other))
602                   (unless (eq other lvar)
603                     (handle-nested-dynamic-extent-lvars
604                      dx other recheck-component)))))))
605       (cons (cons dx lvar)
606             (if (listp uses)
607                 (loop for use in uses
608                       when (use-good-for-dx-p use dx recheck-component)
609                       nconc (recurse use))
610                 (when (use-good-for-dx-p uses dx recheck-component)
611                   (recurse uses)))))))
612
613 ;;;;; BLOCK UTILS
614
615 (declaim (inline block-to-be-deleted-p))
616 (defun block-to-be-deleted-p (block)
617   (or (block-delete-p block)
618       (eq (functional-kind (block-home-lambda block)) :deleted)))
619
620 ;;; Checks whether NODE is in a block to be deleted
621 (declaim (inline node-to-be-deleted-p))
622 (defun node-to-be-deleted-p (node)
623   (block-to-be-deleted-p (node-block node)))
624
625 (declaim (ftype (sfunction (clambda) cblock) lambda-block))
626 (defun lambda-block (clambda)
627   (node-block (lambda-bind clambda)))
628 (declaim (ftype (sfunction (clambda) component) lambda-component))
629 (defun lambda-component (clambda)
630   (block-component (lambda-block clambda)))
631
632 (declaim (ftype (sfunction (cblock) node) block-start-node))
633 (defun block-start-node (block)
634   (ctran-next (block-start block)))
635
636 ;;; Return the enclosing cleanup for environment of the first or last
637 ;;; node in BLOCK.
638 (defun block-start-cleanup (block)
639   (node-enclosing-cleanup (block-start-node block)))
640 (defun block-end-cleanup (block)
641   (node-enclosing-cleanup (block-last block)))
642
643 ;;; Return the non-LET LAMBDA that holds BLOCK's code, or NIL
644 ;;; if there is none.
645 ;;;
646 ;;; There can legitimately be no home lambda in dead code early in the
647 ;;; IR1 conversion process, e.g. when IR1-converting the SETQ form in
648 ;;;   (BLOCK B (RETURN-FROM B) (SETQ X 3))
649 ;;; where the block is just a placeholder during parsing and doesn't
650 ;;; actually correspond to code which will be written anywhere.
651 (declaim (ftype (sfunction (cblock) (or clambda null)) block-home-lambda-or-null))
652 (defun block-home-lambda-or-null (block)
653   (if (node-p (block-last block))
654       ;; This is the old CMU CL way of doing it.
655       (node-home-lambda (block-last block))
656       ;; Now that SBCL uses this operation more aggressively than CMU
657       ;; CL did, the old CMU CL way of doing it can fail in two ways.
658       ;;   1. It can fail in a few cases even when a meaningful home
659       ;;      lambda exists, e.g. in IR1-CONVERT of one of the legs of
660       ;;      an IF.
661       ;;   2. It can fail when converting a form which is born orphaned
662       ;;      so that it never had a meaningful home lambda, e.g. a form
663       ;;      which follows a RETURN-FROM or GO form.
664       (let ((pred-list (block-pred block)))
665         ;; To deal with case 1, we reason that
666         ;; previous-in-target-execution-order blocks should be in the
667         ;; same lambda, and that they seem in practice to be
668         ;; previous-in-compilation-order blocks too, so we look back
669         ;; to find one which is sufficiently initialized to tell us
670         ;; what the home lambda is.
671         (if pred-list
672             ;; We could get fancy about this, flooding through the
673             ;; graph of all the previous blocks, but in practice it
674             ;; seems to work just to grab the first previous block and
675             ;; use it.
676             (node-home-lambda (block-last (first pred-list)))
677             ;; In case 2, we end up with an empty PRED-LIST and
678             ;; have to punt: There's no home lambda.
679             nil))))
680
681 ;;; Return the non-LET LAMBDA that holds BLOCK's code.
682 (declaim (ftype (sfunction (cblock) clambda) block-home-lambda))
683 (defun block-home-lambda (block)
684   (block-home-lambda-or-null block))
685
686 ;;; Return the IR1 physical environment for BLOCK.
687 (declaim (ftype (sfunction (cblock) physenv) block-physenv))
688 (defun block-physenv (block)
689   (lambda-physenv (block-home-lambda block)))
690
691 ;;; Return the Top Level Form number of PATH, i.e. the ordinal number
692 ;;; of its original source's top level form in its compilation unit.
693 (defun source-path-tlf-number (path)
694   (declare (list path))
695   (car (last path)))
696
697 ;;; Return the (reversed) list for the PATH in the original source
698 ;;; (with the Top Level Form number last).
699 (defun source-path-original-source (path)
700   (declare (list path) (inline member))
701   (cddr (member 'original-source-start path :test #'eq)))
702
703 ;;; Return the Form Number of PATH's original source inside the Top
704 ;;; Level Form that contains it. This is determined by the order that
705 ;;; we walk the subforms of the top level source form.
706 (defun source-path-form-number (path)
707   (declare (list path) (inline member))
708   (cadr (member 'original-source-start path :test #'eq)))
709
710 ;;; Return a list of all the enclosing forms not in the original
711 ;;; source that converted to get to this form, with the immediate
712 ;;; source for node at the start of the list.
713 (defun source-path-forms (path)
714   (subseq path 0 (position 'original-source-start path)))
715
716 ;;; Return the innermost source form for NODE.
717 (defun node-source-form (node)
718   (declare (type node node))
719   (let* ((path (node-source-path node))
720          (forms (source-path-forms path)))
721     (if forms
722         (first forms)
723         (values (find-original-source path)))))
724
725 ;;; Return NODE-SOURCE-FORM, T if lvar has a single use, otherwise
726 ;;; NIL, NIL.
727 (defun lvar-source (lvar)
728   (let ((use (lvar-uses lvar)))
729     (if (listp use)
730         (values nil nil)
731         (values (node-source-form use) t))))
732
733 ;;; Return the unique node, delivering a value to LVAR.
734 #!-sb-fluid (declaim (inline lvar-use))
735 (defun lvar-use (lvar)
736   (the (not list) (lvar-uses lvar)))
737
738 #!-sb-fluid (declaim (inline lvar-has-single-use-p))
739 (defun lvar-has-single-use-p (lvar)
740   (typep (lvar-uses lvar) '(not list)))
741
742 ;;; Return the LAMBDA that is CTRAN's home, or NIL if there is none.
743 (declaim (ftype (sfunction (ctran) (or clambda null))
744                 ctran-home-lambda-or-null))
745 (defun ctran-home-lambda-or-null (ctran)
746   ;; KLUDGE: This function is a post-CMU-CL hack by WHN, and this
747   ;; implementation might not be quite right, or might be uglier than
748   ;; necessary. It appears that the original Python never found a need
749   ;; to do this operation. The obvious things based on
750   ;; NODE-HOME-LAMBDA of CTRAN-USE usually work; then if that fails,
751   ;; BLOCK-HOME-LAMBDA of CTRAN-BLOCK works, given that we
752   ;; generalize it enough to grovel harder when the simple CMU CL
753   ;; approach fails, and furthermore realize that in some exceptional
754   ;; cases it might return NIL. -- WHN 2001-12-04
755   (cond ((ctran-use ctran)
756          (node-home-lambda (ctran-use ctran)))
757         ((ctran-block ctran)
758          (block-home-lambda-or-null (ctran-block ctran)))
759         (t
760          (bug "confused about home lambda for ~S" ctran))))
761
762 ;;; Return the LAMBDA that is CTRAN's home.
763 (declaim (ftype (sfunction (ctran) clambda) ctran-home-lambda))
764 (defun ctran-home-lambda (ctran)
765   (ctran-home-lambda-or-null ctran))
766
767 (declaim (inline cast-single-value-p))
768 (defun cast-single-value-p (cast)
769   (not (values-type-p (cast-asserted-type cast))))
770
771 #!-sb-fluid (declaim (inline lvar-single-value-p))
772 (defun lvar-single-value-p (lvar)
773   (or (not lvar)
774       (let ((dest (lvar-dest lvar)))
775         (typecase dest
776           ((or creturn exit)
777            nil)
778           (mv-combination
779            (eq (basic-combination-fun dest) lvar))
780           (cast
781            (locally
782                (declare (notinline lvar-single-value-p))
783              (and (cast-single-value-p dest)
784                   (lvar-single-value-p (node-lvar dest)))))
785           (t
786            t)))))
787
788 (defun principal-lvar-end (lvar)
789   (loop for prev = lvar then (node-lvar dest)
790         for dest = (and prev (lvar-dest prev))
791         while (cast-p dest)
792         finally (return (values dest prev))))
793
794 (defun principal-lvar-single-valuify (lvar)
795   (loop for prev = lvar then (node-lvar dest)
796         for dest = (and prev (lvar-dest prev))
797         while (cast-p dest)
798         do (setf (node-derived-type dest)
799                  (make-short-values-type (list (single-value-type
800                                                 (node-derived-type dest)))))
801         (reoptimize-lvar prev)))
802 \f
803 ;;; Return a new LEXENV just like DEFAULT except for the specified
804 ;;; slot values. Values for the alist slots are NCONCed to the
805 ;;; beginning of the current value, rather than replacing it entirely.
806 (defun make-lexenv (&key (default *lexenv*)
807                          funs vars blocks tags
808                          type-restrictions
809                          (lambda (lexenv-lambda default))
810                          (cleanup (lexenv-cleanup default))
811                          (handled-conditions (lexenv-handled-conditions default))
812                          (disabled-package-locks
813                           (lexenv-disabled-package-locks default))
814                          (policy (lexenv-policy default))
815                          (user-data (lexenv-user-data default)))
816   (macrolet ((frob (var slot)
817                `(let ((old (,slot default)))
818                   (if ,var
819                       (nconc ,var old)
820                       old))))
821     (internal-make-lexenv
822      (frob funs lexenv-funs)
823      (frob vars lexenv-vars)
824      (frob blocks lexenv-blocks)
825      (frob tags lexenv-tags)
826      (frob type-restrictions lexenv-type-restrictions)
827      lambda
828      cleanup handled-conditions disabled-package-locks
829      policy
830      user-data)))
831
832 ;;; Makes a LEXENV, suitable for using in a MACROLET introduced
833 ;;; macroexpander
834 (defun make-restricted-lexenv (lexenv)
835   (flet ((fun-good-p (fun)
836            (destructuring-bind (name . thing) fun
837              (declare (ignore name))
838              (etypecase thing
839                (functional nil)
840                (global-var t)
841                (cons (aver (eq (car thing) 'macro))
842                      t))))
843          (var-good-p (var)
844            (destructuring-bind (name . thing) var
845              (declare (ignore name))
846              (etypecase thing
847                ;; The evaluator will mark lexicals with :BOGUS when it
848                ;; translates an interpreter lexenv to a compiler
849                ;; lexenv.
850                ((or leaf #!+sb-eval (member :bogus)) nil)
851                (cons (aver (eq (car thing) 'macro))
852                      t)
853                (heap-alien-info nil)))))
854     (internal-make-lexenv
855      (remove-if-not #'fun-good-p (lexenv-funs lexenv))
856      (remove-if-not #'var-good-p (lexenv-vars lexenv))
857      nil
858      nil
859      (lexenv-type-restrictions lexenv) ; XXX
860      nil
861      nil
862      (lexenv-handled-conditions lexenv)
863      (lexenv-disabled-package-locks lexenv)
864      (lexenv-policy lexenv)
865      (lexenv-user-data lexenv))))
866 \f
867 ;;;; flow/DFO/component hackery
868
869 ;;; Join BLOCK1 and BLOCK2.
870 (defun link-blocks (block1 block2)
871   (declare (type cblock block1 block2))
872   (setf (block-succ block1)
873         (if (block-succ block1)
874             (%link-blocks block1 block2)
875             (list block2)))
876   (push block1 (block-pred block2))
877   (values))
878 (defun %link-blocks (block1 block2)
879   (declare (type cblock block1 block2))
880   (let ((succ1 (block-succ block1)))
881     (aver (not (memq block2 succ1)))
882     (cons block2 succ1)))
883
884 ;;; This is like LINK-BLOCKS, but we separate BLOCK1 and BLOCK2. If
885 ;;; this leaves a successor with a single predecessor that ends in an
886 ;;; IF, then set BLOCK-TEST-MODIFIED so that any test constraint will
887 ;;; now be able to be propagated to the successor.
888 (defun unlink-blocks (block1 block2)
889   (declare (type cblock block1 block2))
890   (let ((succ1 (block-succ block1)))
891     (if (eq block2 (car succ1))
892         (setf (block-succ block1) (cdr succ1))
893         (do ((succ (cdr succ1) (cdr succ))
894              (prev succ1 succ))
895             ((eq (car succ) block2)
896              (setf (cdr prev) (cdr succ)))
897           (aver succ))))
898
899   (let ((new-pred (delq block1 (block-pred block2))))
900     (setf (block-pred block2) new-pred)
901     (when (singleton-p new-pred)
902       (let ((pred-block (first new-pred)))
903         (when (if-p (block-last pred-block))
904           (setf (block-test-modified pred-block) t)))))
905   (values))
906
907 ;;; Swing the succ/pred link between BLOCK and OLD to be between BLOCK
908 ;;; and NEW. If BLOCK ends in an IF, then we have to fix up the
909 ;;; consequent/alternative blocks to point to NEW. We also set
910 ;;; BLOCK-TEST-MODIFIED so that any test constraint will be applied to
911 ;;; the new successor.
912 (defun change-block-successor (block old new)
913   (declare (type cblock new old block))
914   (unlink-blocks block old)
915   (let ((last (block-last block))
916         (comp (block-component block)))
917     (setf (component-reanalyze comp) t)
918     (typecase last
919       (cif
920        (setf (block-test-modified block) t)
921        (let* ((succ-left (block-succ block))
922               (new (if (and (eq new (component-tail comp))
923                             succ-left)
924                        (first succ-left)
925                        new)))
926          (unless (memq new succ-left)
927            (link-blocks block new))
928          (macrolet ((frob (slot)
929                       `(when (eq (,slot last) old)
930                          (setf (,slot last) new))))
931            (frob if-consequent)
932            (frob if-alternative)
933            (when (eq (if-consequent last)
934                      (if-alternative last))
935              (reoptimize-component (block-component block) :maybe)))))
936       (t
937        (unless (memq new (block-succ block))
938          (link-blocks block new)))))
939
940   (values))
941
942 ;;; Unlink a block from the next/prev chain. We also null out the
943 ;;; COMPONENT.
944 (declaim (ftype (sfunction (cblock) (values)) remove-from-dfo))
945 (defun remove-from-dfo (block)
946   (let ((next (block-next block))
947         (prev (block-prev block)))
948     (setf (block-component block) nil)
949     (setf (block-next prev) next)
950     (setf (block-prev next) prev))
951   (values))
952
953 ;;; Add BLOCK to the next/prev chain following AFTER. We also set the
954 ;;; COMPONENT to be the same as for AFTER.
955 (defun add-to-dfo (block after)
956   (declare (type cblock block after))
957   (let ((next (block-next after))
958         (comp (block-component after)))
959     (aver (not (eq (component-kind comp) :deleted)))
960     (setf (block-component block) comp)
961     (setf (block-next after) block)
962     (setf (block-prev block) after)
963     (setf (block-next block) next)
964     (setf (block-prev next) block))
965   (values))
966
967 ;;; List all NLX-INFOs which BLOCK can exit to.
968 ;;;
969 ;;; We hope that no cleanup actions are performed in the middle of
970 ;;; BLOCK, so it is enough to look only at cleanups in the block
971 ;;; end. The tricky thing is a special cleanup block; all its nodes
972 ;;; have the same cleanup info, corresponding to the start, so the
973 ;;; same approach returns safe result.
974 (defun map-block-nlxes (fun block &optional dx-cleanup-fun)
975   (loop for cleanup = (block-end-cleanup block)
976         then (node-enclosing-cleanup (cleanup-mess-up cleanup))
977         while cleanup
978         do (let ((mess-up (cleanup-mess-up cleanup)))
979              (case (cleanup-kind cleanup)
980                ((:block :tagbody)
981                 (aver (entry-p mess-up))
982                 (loop for exit in (entry-exits mess-up)
983                       for nlx-info = (exit-nlx-info exit)
984                       do (funcall fun nlx-info)))
985                ((:catch :unwind-protect)
986                 (aver (combination-p mess-up))
987                 (let* ((arg-lvar (first (basic-combination-args mess-up)))
988                        (nlx-info (constant-value (ref-leaf (lvar-use arg-lvar)))))
989                 (funcall fun nlx-info)))
990                ((:dynamic-extent)
991                 (when dx-cleanup-fun
992                   (funcall dx-cleanup-fun cleanup)))))))
993
994 ;;; Set the FLAG for all the blocks in COMPONENT to NIL, except for
995 ;;; the head and tail which are set to T.
996 (declaim (ftype (sfunction (component) (values)) clear-flags))
997 (defun clear-flags (component)
998   (let ((head (component-head component))
999         (tail (component-tail component)))
1000     (setf (block-flag head) t)
1001     (setf (block-flag tail) t)
1002     (do-blocks (block component)
1003       (setf (block-flag block) nil)))
1004   (values))
1005
1006 ;;; Make a component with no blocks in it. The BLOCK-FLAG is initially
1007 ;;; true in the head and tail blocks.
1008 (declaim (ftype (sfunction () component) make-empty-component))
1009 (defun make-empty-component ()
1010   (let* ((head (make-block-key :start nil :component nil))
1011          (tail (make-block-key :start nil :component nil))
1012          (res (make-component head tail)))
1013     (setf (block-flag head) t)
1014     (setf (block-flag tail) t)
1015     (setf (block-component head) res)
1016     (setf (block-component tail) res)
1017     (setf (block-next head) tail)
1018     (setf (block-prev tail) head)
1019     res))
1020
1021 ;;; Make NODE the LAST node in its block, splitting the block if necessary.
1022 ;;; The new block is added to the DFO immediately following NODE's block.
1023 (defun node-ends-block (node)
1024   (declare (type node node))
1025   (let* ((block (node-block node))
1026          (start (node-next node))
1027          (last (block-last block)))
1028     (check-type last node)
1029     (unless (eq last node)
1030       (aver (and (eq (ctran-kind start) :inside-block)
1031                  (not (block-delete-p block))))
1032       (let* ((succ (block-succ block))
1033              (new-block
1034               (make-block-key :start start
1035                               :component (block-component block)
1036                               :succ succ :last last)))
1037         (setf (ctran-kind start) :block-start)
1038         (setf (ctran-use start) nil)
1039         (setf (block-last block) node)
1040         (setf (node-next node) nil)
1041         (dolist (b succ)
1042           (setf (block-pred b)
1043                 (cons new-block (remove block (block-pred b)))))
1044         (setf (block-succ block) ())
1045         (link-blocks block new-block)
1046         (add-to-dfo new-block block)
1047         (setf (component-reanalyze (block-component block)) t)
1048
1049         (do ((ctran start (node-next (ctran-next ctran))))
1050             ((not ctran))
1051           (setf (ctran-block ctran) new-block))
1052
1053         (setf (block-type-asserted block) t)
1054         (setf (block-test-modified block) t))))
1055   (values))
1056 \f
1057 ;;;; deleting stuff
1058
1059 ;;; Deal with deleting the last (read) reference to a LAMBDA-VAR.
1060 (defun delete-lambda-var (leaf)
1061   (declare (type lambda-var leaf))
1062
1063   (setf (lambda-var-deleted leaf) t)
1064   ;; Iterate over all local calls flushing the corresponding argument,
1065   ;; allowing the computation of the argument to be deleted. We also
1066   ;; mark the LET for reoptimization, since it may be that we have
1067   ;; deleted its last variable.
1068   (let* ((fun (lambda-var-home leaf))
1069          (n (position leaf (lambda-vars fun))))
1070     (dolist (ref (leaf-refs fun))
1071       (let* ((lvar (node-lvar ref))
1072              (dest (and lvar (lvar-dest lvar))))
1073         (when (and (combination-p dest)
1074                    (eq (basic-combination-fun dest) lvar)
1075                    (eq (basic-combination-kind dest) :local))
1076           (let* ((args (basic-combination-args dest))
1077                  (arg (elt args n)))
1078             (reoptimize-lvar arg)
1079             (flush-dest arg)
1080             (setf (elt args n) nil))))))
1081
1082   ;; The LAMBDA-VAR may still have some SETs, but this doesn't cause
1083   ;; too much difficulty, since we can efficiently implement
1084   ;; write-only variables. We iterate over the SETs, marking their
1085   ;; blocks for dead code flushing, since we can delete SETs whose
1086   ;; value is unused.
1087   (dolist (set (lambda-var-sets leaf))
1088     (setf (block-flush-p (node-block set)) t))
1089
1090   (values))
1091
1092 ;;; Note that something interesting has happened to VAR.
1093 (defun reoptimize-lambda-var (var)
1094   (declare (type lambda-var var))
1095   (let ((fun (lambda-var-home var)))
1096     ;; We only deal with LET variables, marking the corresponding
1097     ;; initial value arg as needing to be reoptimized.
1098     (when (and (eq (functional-kind fun) :let)
1099                (leaf-refs var))
1100       (do ((args (basic-combination-args
1101                   (lvar-dest (node-lvar (first (leaf-refs fun)))))
1102                  (cdr args))
1103            (vars (lambda-vars fun) (cdr vars)))
1104           ((eq (car vars) var)
1105            (reoptimize-lvar (car args))))))
1106   (values))
1107
1108 ;;; Delete a function that has no references. This need only be called
1109 ;;; on functions that never had any references, since otherwise
1110 ;;; DELETE-REF will handle the deletion.
1111 (defun delete-functional (fun)
1112   (aver (and (null (leaf-refs fun))
1113              (not (functional-entry-fun fun))))
1114   (etypecase fun
1115     (optional-dispatch (delete-optional-dispatch fun))
1116     (clambda (delete-lambda fun)))
1117   (values))
1118
1119 ;;; Deal with deleting the last reference to a CLAMBDA, which means
1120 ;;; that the lambda is unreachable, so that its body may be
1121 ;;; deleted. We set FUNCTIONAL-KIND to :DELETED and rely on
1122 ;;; IR1-OPTIMIZE to delete its blocks.
1123 (defun delete-lambda (clambda)
1124   (declare (type clambda clambda))
1125   (let ((original-kind (functional-kind clambda))
1126         (bind (lambda-bind clambda)))
1127     (aver (not (member original-kind '(:deleted :toplevel))))
1128     (aver (not (functional-has-external-references-p clambda)))
1129     (aver (or (eq original-kind :zombie) bind))
1130     (setf (functional-kind clambda) :deleted)
1131     (setf (lambda-bind clambda) nil)
1132
1133     (labels ((delete-children (lambda)
1134                (dolist (child (lambda-children lambda))
1135                  (cond ((eq (functional-kind child) :deleted)
1136                         (delete-children child))
1137                        (t
1138                         (delete-lambda child))))
1139                (setf (lambda-children lambda) nil)
1140                (setf (lambda-parent lambda) nil)))
1141       (delete-children clambda))
1142
1143     ;; (The IF test is (FUNCTIONAL-SOMEWHAT-LETLIKE-P CLAMBDA), except
1144     ;; that we're using the old value of the KIND slot, not the
1145     ;; current slot value, which has now been set to :DELETED.)
1146     (case original-kind
1147       (:zombie)
1148       ((:let :mv-let :assignment)
1149        (let ((bind-block (node-block bind)))
1150          (mark-for-deletion bind-block))
1151        (let ((home (lambda-home clambda)))
1152          (setf (lambda-lets home) (delete clambda (lambda-lets home))))
1153        ;; KLUDGE: In presence of NLEs we cannot always understand that
1154        ;; LET's BIND dominates its body [for a LET "its" body is not
1155        ;; quite its]; let's delete too dangerous for IR2 stuff. --
1156        ;; APD, 2004-01-01
1157        (dolist (var (lambda-vars clambda))
1158          (flet ((delete-node (node)
1159                   (mark-for-deletion (node-block node))))
1160          (mapc #'delete-node (leaf-refs var))
1161          (mapc #'delete-node (lambda-var-sets var)))))
1162       (t
1163        ;; Function has no reachable references.
1164        (dolist (ref (lambda-refs clambda))
1165          (mark-for-deletion (node-block ref)))
1166        ;; If the function isn't a LET, we unlink the function head
1167        ;; and tail from the component head and tail to indicate that
1168        ;; the code is unreachable. We also delete the function from
1169        ;; COMPONENT-LAMBDAS (it won't be there before local call
1170        ;; analysis, but no matter.) If the lambda was never
1171        ;; referenced, we give a note.
1172        (let* ((bind-block (node-block bind))
1173               (component (block-component bind-block))
1174               (return (lambda-return clambda))
1175               (return-block (and return (node-block return))))
1176          (unless (leaf-ever-used clambda)
1177            (let ((*compiler-error-context* bind))
1178              (compiler-notify 'code-deletion-note
1179                               :format-control "deleting unused function~:[.~;~:*~%  ~S~]"
1180                               :format-arguments (list (leaf-debug-name clambda)))))
1181          (unless (block-delete-p bind-block)
1182            (unlink-blocks (component-head component) bind-block))
1183          (when (and return-block (not (block-delete-p return-block)))
1184            (mark-for-deletion return-block)
1185            (unlink-blocks return-block (component-tail component)))
1186          (setf (component-reanalyze component) t)
1187          (let ((tails (lambda-tail-set clambda)))
1188            (setf (tail-set-funs tails)
1189                  (delete clambda (tail-set-funs tails)))
1190            (setf (lambda-tail-set clambda) nil))
1191          (setf (component-lambdas component)
1192                (delq clambda (component-lambdas component))))))
1193
1194     ;; If the lambda is an XEP, then we null out the ENTRY-FUN in its
1195     ;; ENTRY-FUN so that people will know that it is not an entry
1196     ;; point anymore.
1197     (when (eq original-kind :external)
1198       (let ((fun (functional-entry-fun clambda)))
1199         (setf (functional-entry-fun fun) nil)
1200         (when (optional-dispatch-p fun)
1201           (delete-optional-dispatch fun)))))
1202
1203   (values))
1204
1205 ;;; Deal with deleting the last reference to an OPTIONAL-DISPATCH. We
1206 ;;; have to be a bit more careful than with lambdas, since DELETE-REF
1207 ;;; is used both before and after local call analysis. Afterward, all
1208 ;;; references to still-existing OPTIONAL-DISPATCHes have been moved
1209 ;;; to the XEP, leaving it with no references at all. So we look at
1210 ;;; the XEP to see whether an optional-dispatch is still really being
1211 ;;; used. But before local call analysis, there are no XEPs, and all
1212 ;;; references are direct.
1213 ;;;
1214 ;;; When we do delete the OPTIONAL-DISPATCH, we grovel all of its
1215 ;;; entry-points, making them be normal lambdas, and then deleting the
1216 ;;; ones with no references. This deletes any e-p lambdas that were
1217 ;;; either never referenced, or couldn't be deleted when the last
1218 ;;; reference was deleted (due to their :OPTIONAL kind.)
1219 ;;;
1220 ;;; Note that the last optional entry point may alias the main entry,
1221 ;;; so when we process the main entry, its KIND may have been changed
1222 ;;; to NIL or even converted to a LETlike value.
1223 (defun delete-optional-dispatch (leaf)
1224   (declare (type optional-dispatch leaf))
1225   (let ((entry (functional-entry-fun leaf)))
1226     (unless (and entry (leaf-refs entry))
1227       (aver (or (not entry) (eq (functional-kind entry) :deleted)))
1228       (setf (functional-kind leaf) :deleted)
1229
1230       (flet ((frob (fun)
1231                (unless (eq (functional-kind fun) :deleted)
1232                  (aver (eq (functional-kind fun) :optional))
1233                  (setf (functional-kind fun) nil)
1234                  (let ((refs (leaf-refs fun)))
1235                    (cond ((null refs)
1236                           (delete-lambda fun))
1237                          ((null (rest refs))
1238                           (or (maybe-let-convert fun)
1239                               (maybe-convert-to-assignment fun)))
1240                          (t
1241                           (maybe-convert-to-assignment fun)))))))
1242
1243         (dolist (ep (optional-dispatch-entry-points leaf))
1244           (when (promise-ready-p ep)
1245             (frob (force ep))))
1246         (when (optional-dispatch-more-entry leaf)
1247           (frob (optional-dispatch-more-entry leaf)))
1248         (let ((main (optional-dispatch-main-entry leaf)))
1249           (when entry
1250             (setf (functional-entry-fun entry) main)
1251             (setf (functional-entry-fun main) entry))
1252           (when (eq (functional-kind main) :optional)
1253             (frob main))))))
1254
1255   (values))
1256
1257 (defun note-local-functional (fun)
1258   (declare (type functional fun))
1259   (when (and (leaf-has-source-name-p fun)
1260              (eq (leaf-source-name fun) (functional-debug-name fun)))
1261     (let ((name (leaf-source-name fun)))
1262       (let ((defined-fun (gethash name *free-funs*)))
1263         (when (and defined-fun
1264                    (defined-fun-p defined-fun)
1265                    (eq (defined-fun-functional defined-fun) fun))
1266           (remhash name *free-funs*))))))
1267
1268 ;;; Return functional for DEFINED-FUN which has been converted in policy
1269 ;;; corresponding to the current one, or NIL if no such functional exists.
1270 ;;;
1271 ;;; Also check that the parent of the functional is visible in the current
1272 ;;; environment.
1273 (defun defined-fun-functional (defined-fun)
1274   (let ((functionals (defined-fun-functionals defined-fun)))
1275     (when functionals
1276       (let* ((sample (car functionals))
1277              (there (lambda-parent (if (lambda-p sample)
1278                                        sample
1279                                        (optional-dispatch-main-entry sample)))))
1280         (when there
1281           (labels ((lookup (here)
1282                      (unless (eq here there)
1283                        (if here
1284                            (lookup (lambda-parent here))
1285                            ;; We looked up all the way up, and didn't find the parent
1286                            ;; of the functional -- therefore it is nested in a lambda
1287                            ;; we don't see, so return nil.
1288                            (return-from defined-fun-functional nil)))))
1289             (lookup (lexenv-lambda *lexenv*)))))
1290       ;; Now find a functional whose policy matches the current one, if we already
1291       ;; have one.
1292       (let ((policy (lexenv-%policy *lexenv*)))
1293         (dolist (functional functionals)
1294           (when (equal policy (lexenv-%policy (functional-lexenv functional)))
1295             (return functional)))))))
1296
1297 ;;; Do stuff to delete the semantic attachments of a REF node. When
1298 ;;; this leaves zero or one reference, we do a type dispatch off of
1299 ;;; the leaf to determine if a special action is appropriate.
1300 (defun delete-ref (ref)
1301   (declare (type ref ref))
1302   (let* ((leaf (ref-leaf ref))
1303          (refs (delq ref (leaf-refs leaf))))
1304     (setf (leaf-refs leaf) refs)
1305
1306     (cond ((null refs)
1307            (typecase leaf
1308              (lambda-var
1309               (delete-lambda-var leaf))
1310              (clambda
1311               (ecase (functional-kind leaf)
1312                 ((nil :let :mv-let :assignment :escape :cleanup)
1313                  (aver (null (functional-entry-fun leaf)))
1314                  (delete-lambda leaf))
1315                 (:external
1316                  (unless (functional-has-external-references-p leaf)
1317                    (delete-lambda leaf)))
1318                 ((:deleted :zombie :optional))))
1319              (optional-dispatch
1320               (unless (eq (functional-kind leaf) :deleted)
1321                 (delete-optional-dispatch leaf)))))
1322           ((null (rest refs))
1323            (typecase leaf
1324              (clambda (or (maybe-let-convert leaf)
1325                           (maybe-convert-to-assignment leaf)))
1326              (lambda-var (reoptimize-lambda-var leaf))))
1327           (t
1328            (typecase leaf
1329              (clambda (maybe-convert-to-assignment leaf))))))
1330
1331   (values))
1332
1333 ;;; This function is called by people who delete nodes; it provides a
1334 ;;; way to indicate that the value of a lvar is no longer used. We
1335 ;;; null out the LVAR-DEST, set FLUSH-P in the blocks containing uses
1336 ;;; of LVAR and set COMPONENT-REOPTIMIZE.
1337 (defun flush-dest (lvar)
1338   (declare (type (or lvar null) lvar))
1339   (unless (null lvar)
1340     (when (lvar-dynamic-extent lvar)
1341       (note-no-stack-allocation lvar :flush t))
1342     (setf (lvar-dest lvar) nil)
1343     (flush-lvar-externally-checkable-type lvar)
1344     (do-uses (use lvar)
1345       (let ((prev (node-prev use)))
1346         (let ((block (ctran-block prev)))
1347           (reoptimize-component (block-component block) t)
1348           (setf (block-attributep (block-flags block)
1349                                   flush-p type-asserted type-check)
1350                 t)))
1351       (setf (node-lvar use) nil))
1352     (setf (lvar-uses lvar) nil))
1353   (values))
1354
1355 (defun delete-dest (lvar)
1356   (when lvar
1357     (let* ((dest (lvar-dest lvar))
1358            (prev (node-prev dest)))
1359       (let ((block (ctran-block prev)))
1360         (unless (block-delete-p block)
1361           (mark-for-deletion block))))))
1362
1363 ;;; Queue the block for deletion
1364 (defun delete-block-lazily (block)
1365   (declare (type cblock block))
1366   (unless (block-delete-p block)
1367     (setf (block-delete-p block) t)
1368     (push block (component-delete-blocks (block-component block)))))
1369
1370 ;;; Do a graph walk backward from BLOCK, marking all predecessor
1371 ;;; blocks with the DELETE-P flag.
1372 (defun mark-for-deletion (block)
1373   (declare (type cblock block))
1374   (let* ((component (block-component block))
1375          (head (component-head component)))
1376     (labels ((helper (block)
1377                (delete-block-lazily block)
1378                (dolist (pred (block-pred block))
1379                  (unless (or (block-delete-p pred)
1380                              (eq pred head))
1381                    (helper pred)))))
1382       (unless (block-delete-p block)
1383         (helper block)
1384         (setf (component-reanalyze component) t))))
1385   (values))
1386
1387 ;;; This function does what is necessary to eliminate the code in it
1388 ;;; from the IR1 representation. This involves unlinking it from its
1389 ;;; predecessors and successors and deleting various node-specific
1390 ;;; semantic information. BLOCK must be already removed from
1391 ;;; COMPONENT-DELETE-BLOCKS.
1392 (defun delete-block (block &optional silent)
1393   (declare (type cblock block))
1394   (aver (block-component block))      ; else block is already deleted!
1395   #!+high-security (aver (not (memq block (component-delete-blocks (block-component block)))))
1396   (unless silent
1397     (note-block-deletion block))
1398   (setf (block-delete-p block) t)
1399
1400   (dolist (b (block-pred block))
1401     (unlink-blocks b block)
1402     ;; In bug 147 the almost-all-blocks-have-a-successor invariant was
1403     ;; broken when successors were deleted without setting the
1404     ;; BLOCK-DELETE-P flags of their predececessors. Make sure that
1405     ;; doesn't happen again.
1406     (aver (not (and (null (block-succ b))
1407                     (not (block-delete-p b))
1408                     (not (eq b (component-head (block-component b))))))))
1409   (dolist (b (block-succ block))
1410     (unlink-blocks block b))
1411
1412   (do-nodes-carefully (node block)
1413     (when (valued-node-p node)
1414       (delete-lvar-use node))
1415     (etypecase node
1416       (ref (delete-ref node))
1417       (cif (flush-dest (if-test node)))
1418       ;; The next two cases serve to maintain the invariant that a LET
1419       ;; always has a well-formed COMBINATION, REF and BIND. We delete
1420       ;; the lambda whenever we delete any of these, but we must be
1421       ;; careful that this LET has not already been partially deleted.
1422       (basic-combination
1423        (when (and (eq (basic-combination-kind node) :local)
1424                   ;; Guards COMBINATION-LAMBDA agains the REF being deleted.
1425                   (lvar-uses (basic-combination-fun node)))
1426          (let ((fun (combination-lambda node)))
1427            ;; If our REF was the second-to-last ref, and has been
1428            ;; deleted, then FUN may be a LET for some other
1429            ;; combination.
1430            (when (and (functional-letlike-p fun)
1431                       (eq (let-combination fun) node))
1432              (delete-lambda fun))))
1433        (flush-dest (basic-combination-fun node))
1434        (dolist (arg (basic-combination-args node))
1435          (when arg (flush-dest arg))))
1436       (bind
1437        (let ((lambda (bind-lambda node)))
1438          (unless (eq (functional-kind lambda) :deleted)
1439            (delete-lambda lambda))))
1440       (exit
1441        (let ((value (exit-value node))
1442              (entry (exit-entry node)))
1443          (when value
1444            (flush-dest value))
1445          (when entry
1446            (setf (entry-exits entry)
1447                  (delq node (entry-exits entry))))))
1448       (entry
1449        (dolist (exit (entry-exits node))
1450          (mark-for-deletion (node-block exit)))
1451        (let ((home (node-home-lambda node)))
1452          (setf (lambda-entries home) (delq node (lambda-entries home)))))
1453       (creturn
1454        (flush-dest (return-result node))
1455        (delete-return node))
1456       (cset
1457        (flush-dest (set-value node))
1458        (let ((var (set-var node)))
1459          (setf (basic-var-sets var)
1460                (delete node (basic-var-sets var)))))
1461       (cast
1462        (flush-dest (cast-value node)))))
1463
1464   (remove-from-dfo block)
1465   (values))
1466
1467 ;;; Do stuff to indicate that the return node NODE is being deleted.
1468 (defun delete-return (node)
1469   (declare (type creturn node))
1470   (let* ((fun (return-lambda node))
1471          (tail-set (lambda-tail-set fun)))
1472     (aver (lambda-return fun))
1473     (setf (lambda-return fun) nil)
1474     (when (and tail-set (not (find-if #'lambda-return
1475                                       (tail-set-funs tail-set))))
1476       (setf (tail-set-type tail-set) *empty-type*)))
1477   (values))
1478
1479 ;;; If any of the VARS in FUN was never referenced and was not
1480 ;;; declared IGNORE, then complain.
1481 (defun note-unreferenced-vars (fun)
1482   (declare (type clambda fun))
1483   (dolist (var (lambda-vars fun))
1484     (unless (or (leaf-ever-used var)
1485                 (lambda-var-ignorep var))
1486       (let ((*compiler-error-context* (lambda-bind fun)))
1487         (unless (policy *compiler-error-context* (= inhibit-warnings 3))
1488           ;; ANSI section "3.2.5 Exceptional Situations in the Compiler"
1489           ;; requires this to be no more than a STYLE-WARNING.
1490           #-sb-xc-host
1491           (compiler-style-warn "The variable ~S is defined but never used."
1492                                (leaf-debug-name var))
1493           ;; There's no reason to accept this kind of equivocation
1494           ;; when compiling our own code, though.
1495           #+sb-xc-host
1496           (warn "The variable ~S is defined but never used."
1497                 (leaf-debug-name var)))
1498         (setf (leaf-ever-used var) t)))) ; to avoid repeated warnings? -- WHN
1499   (values))
1500
1501 (defvar *deletion-ignored-objects* '(t nil))
1502
1503 ;;; Return true if we can find OBJ in FORM, NIL otherwise. We bound
1504 ;;; our recursion so that we don't get lost in circular structures. We
1505 ;;; ignore the car of forms if they are a symbol (to prevent confusing
1506 ;;; function referencess with variables), and we also ignore anything
1507 ;;; inside ' or #'.
1508 (defun present-in-form (obj form depth)
1509   (declare (type (integer 0 20) depth))
1510   (cond ((= depth 20) nil)
1511         ((eq obj form) t)
1512         ((atom form) nil)
1513         (t
1514          (let ((first (car form))
1515                (depth (1+ depth)))
1516            (if (member first '(quote function))
1517                nil
1518                (or (and (not (symbolp first))
1519                         (present-in-form obj first depth))
1520                    (do ((l (cdr form) (cdr l))
1521                         (n 0 (1+ n)))
1522                        ((or (atom l) (> n 100))
1523                         nil)
1524                      (declare (fixnum n))
1525                      (when (present-in-form obj (car l) depth)
1526                        (return t)))))))))
1527
1528 ;;; This function is called on a block immediately before we delete
1529 ;;; it. We check to see whether any of the code about to die appeared
1530 ;;; in the original source, and emit a note if so.
1531 ;;;
1532 ;;; If the block was in a lambda is now deleted, then we ignore the
1533 ;;; whole block, since this case is picked off in DELETE-LAMBDA. We
1534 ;;; also ignore the deletion of CRETURN nodes, since it is somewhat
1535 ;;; reasonable for a function to not return, and there is a different
1536 ;;; note for that case anyway.
1537 ;;;
1538 ;;; If the actual source is an atom, then we use a bunch of heuristics
1539 ;;; to guess whether this reference really appeared in the original
1540 ;;; source:
1541 ;;; -- If a symbol, it must be interned and not a keyword.
1542 ;;; -- It must not be an easily introduced constant (T or NIL, a fixnum
1543 ;;;    or a character.)
1544 ;;; -- The atom must be "present" in the original source form, and
1545 ;;;    present in all intervening actual source forms.
1546 (defun note-block-deletion (block)
1547   (let ((home (block-home-lambda block)))
1548     (unless (eq (functional-kind home) :deleted)
1549       (do-nodes (node nil block)
1550         (let* ((path (node-source-path node))
1551                (first (first path)))
1552           (when (or (eq first 'original-source-start)
1553                     (and (atom first)
1554                          (or (not (symbolp first))
1555                              (let ((pkg (symbol-package first)))
1556                                (and pkg
1557                                     (not (eq pkg (symbol-package :end))))))
1558                          (not (member first *deletion-ignored-objects*))
1559                          (not (typep first '(or fixnum character)))
1560                          (every (lambda (x)
1561                                   (present-in-form first x 0))
1562                                 (source-path-forms path))
1563                          (present-in-form first (find-original-source path)
1564                                           0)))
1565             (unless (return-p node)
1566               (let ((*compiler-error-context* node))
1567                 (compiler-notify 'code-deletion-note
1568                                  :format-control "deleting unreachable code"
1569                                  :format-arguments nil)))
1570             (return))))))
1571   (values))
1572
1573 ;;; Delete a node from a block, deleting the block if there are no
1574 ;;; nodes left. We remove the node from the uses of its LVAR.
1575 ;;;
1576 ;;; If the node is the last node, there must be exactly one successor.
1577 ;;; We link all of our precedessors to the successor and unlink the
1578 ;;; block. In this case, we return T, otherwise NIL. If no nodes are
1579 ;;; left, and the block is a successor of itself, then we replace the
1580 ;;; only node with a degenerate exit node. This provides a way to
1581 ;;; represent the bodyless infinite loop, given the prohibition on
1582 ;;; empty blocks in IR1.
1583 (defun unlink-node (node)
1584   (declare (type node node))
1585   (when (valued-node-p node)
1586     (delete-lvar-use node))
1587
1588   (let* ((ctran (node-next node))
1589          (next (and ctran (ctran-next ctran)))
1590          (prev (node-prev node))
1591          (block (ctran-block prev))
1592          (prev-kind (ctran-kind prev))
1593          (last (block-last block)))
1594
1595     (setf (block-type-asserted block) t)
1596     (setf (block-test-modified block) t)
1597
1598     (cond ((or (eq prev-kind :inside-block)
1599                (and (eq prev-kind :block-start)
1600                     (not (eq node last))))
1601            (cond ((eq node last)
1602                   (setf (block-last block) (ctran-use prev))
1603                   (setf (node-next (ctran-use prev)) nil))
1604                  (t
1605                   (setf (ctran-next prev) next)
1606                   (setf (node-prev next) prev)
1607                   (when (if-p next) ; AOP wanted
1608                     (reoptimize-lvar (if-test next)))))
1609            (setf (node-prev node) nil)
1610            nil)
1611           (t
1612            (aver (eq prev-kind :block-start))
1613            (aver (eq node last))
1614            (let* ((succ (block-succ block))
1615                   (next (first succ)))
1616              (aver (singleton-p succ))
1617              (cond
1618               ((eq block (first succ))
1619                (with-ir1-environment-from-node node
1620                  (let ((exit (make-exit)))
1621                    (setf (ctran-next prev) nil)
1622                    (link-node-to-previous-ctran exit prev)
1623                    (setf (block-last block) exit)))
1624                (setf (node-prev node) nil)
1625                nil)
1626               (t
1627                (aver (eq (block-start-cleanup block)
1628                          (block-end-cleanup block)))
1629                (unlink-blocks block next)
1630                (dolist (pred (block-pred block))
1631                  (change-block-successor pred block next))
1632                (when (block-delete-p block)
1633                  (let ((component (block-component block)))
1634                    (setf (component-delete-blocks component)
1635                          (delq block (component-delete-blocks component)))))
1636                (remove-from-dfo block)
1637                (setf (block-delete-p block) t)
1638                (setf (node-prev node) nil)
1639                t)))))))
1640
1641 ;;; Return true if CTRAN has been deleted, false if it is still a valid
1642 ;;; part of IR1.
1643 (defun ctran-deleted-p (ctran)
1644   (declare (type ctran ctran))
1645   (let ((block (ctran-block ctran)))
1646     (or (not (block-component block))
1647         (block-delete-p block))))
1648
1649 ;;; Return true if NODE has been deleted, false if it is still a valid
1650 ;;; part of IR1.
1651 (defun node-deleted (node)
1652   (declare (type node node))
1653   (let ((prev (node-prev node)))
1654     (or (not prev)
1655         (ctran-deleted-p prev))))
1656
1657 ;;; Delete all the blocks and functions in COMPONENT. We scan first
1658 ;;; marking the blocks as DELETE-P to prevent weird stuff from being
1659 ;;; triggered by deletion.
1660 (defun delete-component (component)
1661   (declare (type component component))
1662   (aver (null (component-new-functionals component)))
1663   (setf (component-kind component) :deleted)
1664   (do-blocks (block component)
1665     (delete-block-lazily block))
1666   (dolist (fun (component-lambdas component))
1667     (unless (eq (functional-kind fun) :deleted)
1668       (setf (functional-kind fun) nil)
1669       (setf (functional-entry-fun fun) nil)
1670       (setf (leaf-refs fun) nil)
1671       (delete-functional fun)))
1672   (clean-component component)
1673   (values))
1674
1675 ;;; Remove all pending blocks to be deleted. Return the nearest live
1676 ;;; block after or equal to BLOCK.
1677 (defun clean-component (component &optional block)
1678   (loop while (component-delete-blocks component)
1679         ;; actual deletion of a block may queue new blocks
1680         do (let ((current (pop (component-delete-blocks component))))
1681              (when (eq block current)
1682                (setq block (block-next block)))
1683              (delete-block current)))
1684   block)
1685
1686 ;;; Convert code of the form
1687 ;;;   (FOO ... (FUN ...) ...)
1688 ;;; to
1689 ;;;   (FOO ...    ...    ...).
1690 ;;; In other words, replace the function combination FUN by its
1691 ;;; arguments. If there are any problems with doing this, use GIVE-UP
1692 ;;; to blow out of whatever transform called this. Note, as the number
1693 ;;; of arguments changes, the transform must be prepared to return a
1694 ;;; lambda with a new lambda-list with the correct number of
1695 ;;; arguments.
1696 (defun splice-fun-args (lvar fun num-args)
1697   #!+sb-doc
1698   "If LVAR is a call to FUN with NUM-ARGS args, change those arguments to feed
1699 directly to the LVAR-DEST of LVAR, which must be a combination. If FUN
1700 is :ANY, the function name is not checked."
1701   (declare (type lvar lvar)
1702            (type symbol fun)
1703            (type index num-args))
1704   (let ((outside (lvar-dest lvar))
1705         (inside (lvar-uses lvar)))
1706     (aver (combination-p outside))
1707     (unless (combination-p inside)
1708       (give-up-ir1-transform))
1709     (let ((inside-fun (combination-fun inside)))
1710       (unless (or (eq fun :any)
1711                   (eq (lvar-fun-name inside-fun) fun))
1712         (give-up-ir1-transform))
1713       (let ((inside-args (combination-args inside)))
1714         (unless (= (length inside-args) num-args)
1715           (give-up-ir1-transform))
1716         (let* ((outside-args (combination-args outside))
1717                (arg-position (position lvar outside-args))
1718                (before-args (subseq outside-args 0 arg-position))
1719                (after-args (subseq outside-args (1+ arg-position))))
1720           (dolist (arg inside-args)
1721             (setf (lvar-dest arg) outside)
1722             (flush-lvar-externally-checkable-type arg))
1723           (setf (combination-args inside) nil)
1724           (setf (combination-args outside)
1725                 (append before-args inside-args after-args))
1726           (change-ref-leaf (lvar-uses inside-fun)
1727                            (find-free-fun 'list "???"))
1728           (setf (combination-fun-info inside) (info :function :info 'list)
1729                 (combination-kind inside) :known)
1730           (setf (node-derived-type inside) *wild-type*)
1731           (flush-dest lvar)
1732           inside-args)))))
1733
1734 ;;; Eliminate keyword arguments from the call (leaving the
1735 ;;; parameters in place.
1736 ;;;
1737 ;;;    (FOO ... :BAR X :QUUX Y)
1738 ;;; becomes
1739 ;;;    (FOO ... X Y)
1740 ;;;
1741 ;;; SPECS is a list of (:KEYWORD PARAMETER) specifications.
1742 ;;; Returns the list of specified parameters names in the
1743 ;;; order they appeared in the call. N-POSITIONAL is the
1744 ;;; number of positional arguments in th call.
1745 (defun eliminate-keyword-args (call n-positional specs)
1746   (let* ((specs (copy-tree specs))
1747          (all (combination-args call))
1748          (new-args (reverse (subseq all 0 n-positional)))
1749          (key-args (subseq all n-positional))
1750          (parameters nil)
1751          (flushed-keys nil))
1752     (loop while key-args
1753           do (let* ((key (pop key-args))
1754                     (val (pop key-args))
1755                     (keyword (if (constant-lvar-p key)
1756                                  (lvar-value key)
1757                                  (give-up-ir1-transform)))
1758                     (spec (or (assoc keyword specs :test #'eq)
1759                               (give-up-ir1-transform))))
1760                (push val new-args)
1761                (push key flushed-keys)
1762                (push (second spec) parameters)
1763                ;; In case of duplicate keys.
1764                (setf (second spec) (gensym))))
1765     (dolist (key flushed-keys)
1766       (flush-dest key))
1767     (setf (combination-args call) (reverse new-args))
1768     (reverse parameters)))
1769
1770 (defun extract-fun-args (lvar fun num-args)
1771   (declare (type lvar lvar)
1772            (type (or symbol list) fun)
1773            (type index num-args))
1774   (let ((fun (if (listp fun) fun (list fun))))
1775     (let ((inside (lvar-uses lvar)))
1776       (unless (combination-p inside)
1777         (give-up-ir1-transform))
1778       (let ((inside-fun (combination-fun inside)))
1779         (unless (member (lvar-fun-name inside-fun) fun)
1780           (give-up-ir1-transform))
1781         (let ((inside-args (combination-args inside)))
1782           (unless (= (length inside-args) num-args)
1783             (give-up-ir1-transform))
1784           (values (lvar-fun-name inside-fun) inside-args))))))
1785
1786 (defun flush-combination (combination)
1787   (declare (type combination combination))
1788   (flush-dest (combination-fun combination))
1789   (dolist (arg (combination-args combination))
1790     (flush-dest arg))
1791   (unlink-node combination)
1792   (values))
1793
1794 \f
1795 ;;;; leaf hackery
1796
1797 ;;; Change the LEAF that a REF refers to.
1798 (defun change-ref-leaf (ref leaf)
1799   (declare (type ref ref) (type leaf leaf))
1800   (unless (eq (ref-leaf ref) leaf)
1801     (push ref (leaf-refs leaf))
1802     (delete-ref ref)
1803     (setf (ref-leaf ref) leaf)
1804     (setf (leaf-ever-used leaf) t)
1805     (let* ((ltype (leaf-type leaf))
1806            (vltype (make-single-value-type ltype)))
1807       (if (let* ((lvar (node-lvar ref))
1808                  (dest (and lvar (lvar-dest lvar))))
1809             (and (basic-combination-p dest)
1810                  (eq lvar (basic-combination-fun dest))
1811                  (csubtypep ltype (specifier-type 'function))))
1812           (setf (node-derived-type ref) vltype)
1813           (derive-node-type ref vltype)))
1814     (reoptimize-lvar (node-lvar ref)))
1815   (values))
1816
1817 ;;; Change all REFS for OLD-LEAF to NEW-LEAF.
1818 (defun substitute-leaf (new-leaf old-leaf)
1819   (declare (type leaf new-leaf old-leaf))
1820   (dolist (ref (leaf-refs old-leaf))
1821     (change-ref-leaf ref new-leaf))
1822   (values))
1823
1824 ;;; like SUBSITUTE-LEAF, only there is a predicate on the REF to tell
1825 ;;; whether to substitute
1826 (defun substitute-leaf-if (test new-leaf old-leaf)
1827   (declare (type leaf new-leaf old-leaf) (type function test))
1828   (dolist (ref (leaf-refs old-leaf))
1829     (when (funcall test ref)
1830       (change-ref-leaf ref new-leaf)))
1831   (values))
1832
1833 ;;; Return a LEAF which represents the specified constant object. If
1834 ;;; the object is not in *CONSTANTS*, then we create a new constant
1835 ;;; LEAF and enter it. If we are producing a fasl file, make sure that
1836 ;;; MAKE-LOAD-FORM gets used on any parts of the constant that it
1837 ;;; needs to be.
1838 ;;;
1839 ;;; We are allowed to coalesce things like EQUAL strings and bit-vectors
1840 ;;; when file-compiling, but not when using COMPILE.
1841 (defun find-constant (object &optional (name nil namep))
1842   (let ((faslp (producing-fasl-file)))
1843     (labels ((make-it ()
1844                (when faslp
1845                  (if namep
1846                      (maybe-emit-make-load-forms object name)
1847                      (maybe-emit-make-load-forms object)))
1848                (make-constant object))
1849              (core-coalesce-p (x)
1850                ;; True for things which retain their identity under EQUAL,
1851                ;; so we can safely share the same CONSTANT leaf between
1852                ;; multiple references.
1853                (or (typep x '(or symbol number character))
1854                    ;; Amusingly enough, we see CLAMBDAs --among other things--
1855                    ;; here, from compiling things like %ALLOCATE-CLOSUREs forms.
1856                    ;; No point in stuffing them in the hash-table.
1857                    (and (typep x 'instance)
1858                         (not (or (leaf-p x) (node-p x))))))
1859              (file-coalesce-p (x)
1860                ;; CLHS 3.2.4.2.2: We are also allowed to coalesce various
1861                ;; other things when file-compiling.
1862                (or (core-coalesce-p x)
1863                    (if (consp x)
1864                        (if (eq +code-coverage-unmarked+ (cdr x))
1865                            ;; These are already coalesced, and the CAR should
1866                            ;; always be OK, so no need to check.
1867                            t
1868                            (unless (maybe-cyclic-p x) ; safe for EQUAL?
1869                              (do ((y x (cdr y)))
1870                                  ((atom y) (file-coalesce-p y))
1871                                (unless (file-coalesce-p (car y))
1872                                  (return nil)))))
1873                        ;; We *could* coalesce base-strings as well,
1874                        ;; but we'd need a separate hash-table for
1875                        ;; that, since we are not allowed to coalesce
1876                        ;; base-strings with non-base-strings.
1877                        (typep x
1878                               '(or bit-vector
1879                                 ;; in the cross-compiler, we coalesce
1880                                 ;; all strings with the same contents,
1881                                 ;; because we will end up dumping them
1882                                 ;; as base-strings anyway.  In the
1883                                 ;; real compiler, we're not allowed to
1884                                 ;; coalesce regardless of string
1885                                 ;; specialized element type, so we
1886                                 ;; KLUDGE by coalescing only character
1887                                 ;; strings (the common case) and
1888                                 ;; punting on the other types.
1889                                 #+sb-xc-host
1890                                 string
1891                                 #-sb-xc-host
1892                                 (vector character))))))
1893              (coalescep (x)
1894                (if faslp (file-coalesce-p x) (core-coalesce-p x))))
1895       (if (and (boundp '*constants*) (coalescep object))
1896           (or (gethash object *constants*)
1897               (setf (gethash object *constants*)
1898                     (make-it)))
1899           (make-it)))))
1900 \f
1901 ;;; Return true if VAR would have to be closed over if environment
1902 ;;; analysis ran now (i.e. if there are any uses that have a different
1903 ;;; home lambda than VAR's home.)
1904 (defun closure-var-p (var)
1905   (declare (type lambda-var var))
1906   (let ((home (lambda-var-home var)))
1907     (cond ((eq (functional-kind home) :deleted)
1908            nil)
1909           (t (let ((home (lambda-home home)))
1910                (flet ((frob (l)
1911                         (find home l
1912                               :key #'node-home-lambda
1913                               :test #'neq)))
1914                  (or (frob (leaf-refs var))
1915                      (frob (basic-var-sets var)))))))))
1916
1917 ;;; If there is a non-local exit noted in ENTRY's environment that
1918 ;;; exits to CONT in that entry, then return it, otherwise return NIL.
1919 (defun find-nlx-info (exit)
1920   (declare (type exit exit))
1921   (let* ((entry (exit-entry exit))
1922          (cleanup (entry-cleanup entry))
1923         (block (first (block-succ (node-block exit)))))
1924     (dolist (nlx (physenv-nlx-info (node-physenv entry)) nil)
1925       (when (and (eq (nlx-info-block nlx) block)
1926                  (eq (nlx-info-cleanup nlx) cleanup))
1927         (return nlx)))))
1928
1929 (defun nlx-info-lvar (nlx)
1930   (declare (type nlx-info nlx))
1931   (node-lvar (block-last (nlx-info-target nlx))))
1932 \f
1933 ;;;; functional hackery
1934
1935 (declaim (ftype (sfunction (functional) clambda) main-entry))
1936 (defun main-entry (functional)
1937   (etypecase functional
1938     (clambda functional)
1939     (optional-dispatch
1940      (optional-dispatch-main-entry functional))))
1941
1942 ;;; RETURN true if FUNCTIONAL is a thing that can be treated like
1943 ;;; MV-BIND when it appears in an MV-CALL. All fixed arguments must be
1944 ;;; optional with null default and no SUPPLIED-P. There must be a
1945 ;;; &REST arg with no references.
1946 (declaim (ftype (sfunction (functional) boolean) looks-like-an-mv-bind))
1947 (defun looks-like-an-mv-bind (functional)
1948   (and (optional-dispatch-p functional)
1949        (do ((arg (optional-dispatch-arglist functional) (cdr arg)))
1950            ((null arg) nil)
1951          (let ((info (lambda-var-arg-info (car arg))))
1952            (unless info (return nil))
1953            (case (arg-info-kind info)
1954              (:optional
1955               (when (or (arg-info-supplied-p info) (arg-info-default info))
1956                 (return nil)))
1957              (:rest
1958               (return (and (null (cdr arg)) (null (leaf-refs (car arg))))))
1959              (t
1960               (return nil)))))))
1961
1962 ;;; Return true if function is an external entry point. This is true
1963 ;;; of normal XEPs (:EXTERNAL kind) and also of top level lambdas
1964 ;;; (:TOPLEVEL kind.)
1965 (defun xep-p (fun)
1966   (declare (type functional fun))
1967   (not (null (member (functional-kind fun) '(:external :toplevel)))))
1968
1969 ;;; If LVAR's only use is a non-notinline global function reference,
1970 ;;; then return the referenced symbol, otherwise NIL. If NOTINLINE-OK
1971 ;;; is true, then we don't care if the leaf is NOTINLINE.
1972 (defun lvar-fun-name (lvar &optional notinline-ok)
1973   (declare (type lvar lvar))
1974   (let ((use (lvar-uses lvar)))
1975     (if (ref-p use)
1976         (let ((leaf (ref-leaf use)))
1977           (if (and (global-var-p leaf)
1978                    (eq (global-var-kind leaf) :global-function)
1979                    (or (not (defined-fun-p leaf))
1980                        (not (eq (defined-fun-inlinep leaf) :notinline))
1981                        notinline-ok))
1982               (leaf-source-name leaf)
1983               nil))
1984         nil)))
1985
1986 (defun lvar-fun-debug-name (lvar)
1987   (declare (type lvar lvar))
1988   (let ((uses (lvar-uses lvar)))
1989     (flet ((name1 (use)
1990              (leaf-debug-name (ref-leaf use))))
1991       (if (ref-p uses)
1992         (name1 uses)
1993         (mapcar #'name1 uses)))))
1994
1995 ;;; Return the source name of a combination -- or signals an error
1996 ;;; if the function leaf is anonymous.
1997 (defun combination-fun-source-name (combination &optional (errorp t))
1998   (let ((leaf (ref-leaf (lvar-uses (combination-fun combination)))))
1999     (if (or errorp (leaf-has-source-name-p leaf))
2000         (values (leaf-source-name leaf) t)
2001         (values nil nil))))
2002
2003 ;;; Return the COMBINATION node that is the call to the LET FUN.
2004 (defun let-combination (fun)
2005   (declare (type clambda fun))
2006   (aver (functional-letlike-p fun))
2007   (lvar-dest (node-lvar (first (leaf-refs fun)))))
2008
2009 ;;; Return the initial value lvar for a LET variable, or NIL if there
2010 ;;; is none.
2011 (defun let-var-initial-value (var)
2012   (declare (type lambda-var var))
2013   (let ((fun (lambda-var-home var)))
2014     (elt (combination-args (let-combination fun))
2015          (position-or-lose var (lambda-vars fun)))))
2016
2017 ;;; Return the LAMBDA that is called by the local CALL.
2018 (defun combination-lambda (call)
2019   (declare (type basic-combination call))
2020   (aver (eq (basic-combination-kind call) :local))
2021   (ref-leaf (lvar-uses (basic-combination-fun call))))
2022
2023 (defvar *inline-expansion-limit* 200
2024   #!+sb-doc
2025   "an upper limit on the number of inline function calls that will be expanded
2026    in any given code object (single function or block compilation)")
2027
2028 ;;; Check whether NODE's component has exceeded its inline expansion
2029 ;;; limit, and warn if so, returning NIL.
2030 (defun inline-expansion-ok (node)
2031   (let ((expanded (incf (component-inline-expansions
2032                          (block-component
2033                           (node-block node))))))
2034     (cond ((> expanded *inline-expansion-limit*) nil)
2035           ((= expanded *inline-expansion-limit*)
2036            ;; FIXME: If the objective is to stop the recursive
2037            ;; expansion of inline functions, wouldn't it be more
2038            ;; correct to look back through surrounding expansions
2039            ;; (which are, I think, stored in the *CURRENT-PATH*, and
2040            ;; possibly stored elsewhere too) and suppress expansion
2041            ;; and print this warning when the function being proposed
2042            ;; for inline expansion is found there? (I don't like the
2043            ;; arbitrary numerical limit in principle, and I think
2044            ;; it'll be a nuisance in practice if we ever want the
2045            ;; compiler to be able to use WITH-COMPILATION-UNIT on
2046            ;; arbitrarily huge blocks of code. -- WHN)
2047            (let ((*compiler-error-context* node))
2048              (compiler-notify "*INLINE-EXPANSION-LIMIT* (~W) was exceeded, ~
2049                                probably trying to~%  ~
2050                                inline a recursive function."
2051                               *inline-expansion-limit*))
2052            nil)
2053           (t t))))
2054
2055 ;;; Make sure that FUNCTIONAL is not let-converted or deleted.
2056 (defun assure-functional-live-p (functional)
2057   (declare (type functional functional))
2058   (when (and (or
2059               ;; looks LET-converted
2060               (functional-somewhat-letlike-p functional)
2061               ;; It's possible for a LET-converted function to end up
2062               ;; deleted later. In that case, for the purposes of this
2063               ;; analysis, it is LET-converted: LET-converted functionals
2064               ;; are too badly trashed to expand them inline, and deleted
2065               ;; LET-converted functionals are even worse.
2066               (memq (functional-kind functional) '(:deleted :zombie))))
2067     (throw 'locall-already-let-converted functional)))
2068
2069 (defun assure-leaf-live-p (leaf)
2070   (typecase leaf
2071     (lambda-var
2072      (when (lambda-var-deleted leaf)
2073        (throw 'locall-already-let-converted leaf)))
2074     (functional
2075      (assure-functional-live-p leaf))))
2076
2077
2078 (defun call-full-like-p (call)
2079   (declare (type combination call))
2080   (let ((kind (basic-combination-kind call)))
2081     (or (eq kind :full)
2082         (and (eq kind :known)
2083              (let ((info (basic-combination-fun-info call)))
2084                (and
2085                 (not (fun-info-ir2-convert info))
2086                 (dolist (template (fun-info-templates info) t)
2087                   (when (eq (template-ltn-policy template) :fast-safe)
2088                     (multiple-value-bind (val win)
2089                        (valid-fun-use call (template-type template))
2090                       (when (or val (not win)) (return nil)))))))))))
2091 \f
2092 ;;;; careful call
2093
2094 ;;; Apply a function to some arguments, returning a list of the values
2095 ;;; resulting of the evaluation. If an error is signalled during the
2096 ;;; application, then we produce a warning message using WARN-FUN and
2097 ;;; return NIL as our second value to indicate this. NODE is used as
2098 ;;; the error context for any error message, and CONTEXT is a string
2099 ;;; that is spliced into the warning.
2100 (declaim (ftype (sfunction ((or symbol function) list node function string)
2101                           (values list boolean))
2102                 careful-call))
2103 (defun careful-call (function args node warn-fun context)
2104   (values
2105    (multiple-value-list
2106     (handler-case (apply function args)
2107       (error (condition)
2108         (let ((*compiler-error-context* node))
2109           (funcall warn-fun "Lisp error during ~A:~%~A" context condition)
2110           (return-from careful-call (values nil nil))))))
2111    t))
2112
2113 ;;; Variations of SPECIFIER-TYPE for parsing possibly wrong
2114 ;;; specifiers.
2115 (macrolet
2116     ((deffrob (basic careful compiler transform)
2117        `(progn
2118           (defun ,careful (specifier)
2119             (handler-case (,basic specifier)
2120               (sb!kernel::arg-count-error (condition)
2121                 (values nil (list (format nil "~A" condition))))
2122               (simple-error (condition)
2123                 (values nil (list* (simple-condition-format-control condition)
2124                                    (simple-condition-format-arguments condition))))))
2125           (defun ,compiler (specifier)
2126             (multiple-value-bind (type error-args) (,careful specifier)
2127               (or type
2128                   (apply #'compiler-error error-args))))
2129           (defun ,transform (specifier)
2130             (multiple-value-bind (type error-args) (,careful specifier)
2131               (or type
2132                   (apply #'give-up-ir1-transform
2133                          error-args)))))))
2134   (deffrob specifier-type careful-specifier-type compiler-specifier-type ir1-transform-specifier-type)
2135   (deffrob values-specifier-type careful-values-specifier-type compiler-values-specifier-type ir1-transform-values-specifier-type))
2136
2137 \f
2138 ;;;; utilities used at run-time for parsing &KEY args in IR1
2139
2140 ;;; This function is used by the result of PARSE-DEFTRANSFORM to find
2141 ;;; the lvar for the value of the &KEY argument KEY in the list of
2142 ;;; lvars ARGS. It returns the lvar if the keyword is present, or NIL
2143 ;;; otherwise. The legality and constantness of the keywords should
2144 ;;; already have been checked.
2145 (declaim (ftype (sfunction (list keyword) (or lvar null))
2146                 find-keyword-lvar))
2147 (defun find-keyword-lvar (args key)
2148   (do ((arg args (cddr arg)))
2149       ((null arg) nil)
2150     (when (eq (lvar-value (first arg)) key)
2151       (return (second arg)))))
2152
2153 ;;; This function is used by the result of PARSE-DEFTRANSFORM to
2154 ;;; verify that alternating lvars in ARGS are constant and that there
2155 ;;; is an even number of args.
2156 (declaim (ftype (sfunction (list) boolean) check-key-args-constant))
2157 (defun check-key-args-constant (args)
2158   (do ((arg args (cddr arg)))
2159       ((null arg) t)
2160     (unless (and (rest arg)
2161                  (constant-lvar-p (first arg)))
2162       (return nil))))
2163
2164 ;;; This function is used by the result of PARSE-DEFTRANSFORM to
2165 ;;; verify that the list of lvars ARGS is a well-formed &KEY arglist
2166 ;;; and that only keywords present in the list KEYS are supplied.
2167 (declaim (ftype (sfunction (list list) boolean) check-transform-keys))
2168 (defun check-transform-keys (args keys)
2169   (and (check-key-args-constant args)
2170        (do ((arg args (cddr arg)))
2171            ((null arg) t)
2172          (unless (member (lvar-value (first arg)) keys)
2173            (return nil)))))
2174 \f
2175 ;;;; miscellaneous
2176
2177 ;;; Called by the expansion of the EVENT macro.
2178 (declaim (ftype (sfunction (event-info (or node null)) *) %event))
2179 (defun %event (info node)
2180   (incf (event-info-count info))
2181   (when (and (>= (event-info-level info) *event-note-threshold*)
2182              (policy (or node *lexenv*)
2183                      (= inhibit-warnings 0)))
2184     (let ((*compiler-error-context* node))
2185       (compiler-notify (event-info-description info))))
2186
2187   (let ((action (event-info-action info)))
2188     (when action (funcall action node))))
2189
2190 ;;;
2191 (defun make-cast (value type policy)
2192   (declare (type lvar value)
2193            (type ctype type)
2194            (type policy policy))
2195   (%make-cast :asserted-type type
2196               :type-to-check (maybe-weaken-check type policy)
2197               :value value
2198               :derived-type (coerce-to-values type)))
2199
2200 (defun cast-type-check (cast)
2201   (declare (type cast cast))
2202   (when (cast-reoptimize cast)
2203     (ir1-optimize-cast cast t))
2204   (cast-%type-check cast))
2205
2206 (defun note-single-valuified-lvar (lvar)
2207   (declare (type (or lvar null) lvar))
2208   (when lvar
2209     (let ((use (lvar-uses lvar)))
2210       (cond ((ref-p use)
2211              (let ((leaf (ref-leaf use)))
2212                (when (and (lambda-var-p leaf)
2213                           (null (rest (leaf-refs leaf))))
2214                  (reoptimize-lambda-var leaf))))
2215             ((or (listp use) (combination-p use))
2216              (do-uses (node lvar)
2217                (setf (node-reoptimize node) t)
2218                (setf (block-reoptimize (node-block node)) t)
2219                (reoptimize-component (node-component node) :maybe)))))))
2220
2221 ;;; Return true if LVAR's only use is a reference to a global function
2222 ;;; designator with one of the specified NAMES, that hasn't been
2223 ;;; declared NOTINLINE.
2224 (defun lvar-fun-is (lvar names)
2225   (declare (type lvar lvar) (list names))
2226   (let ((use (lvar-uses lvar)))
2227     (and (ref-p use)
2228          (let* ((*lexenv* (node-lexenv use))
2229                 (leaf (ref-leaf use))
2230                 (name
2231                  (cond ((global-var-p leaf)
2232                         ;; Case 1: #'NAME
2233                         (and (eq (global-var-kind leaf) :global-function)
2234                              (car (member (leaf-source-name leaf) names
2235                                           :test #'equal))))
2236                        ((constant-p leaf)
2237                         (let ((value (constant-value leaf)))
2238                           (car (if (functionp value)
2239                                    ;; Case 2: #.#'NAME
2240                                    (member value names
2241                                            :key (lambda (name)
2242                                                   (and (fboundp name)
2243                                                        (fdefinition name)))
2244                                            :test #'eq)
2245                                    ;; Case 3: 'NAME
2246                                    (member value names
2247                                            :test #'equal))))))))
2248            (and name
2249                 (not (fun-lexically-notinline-p name)))))))
2250
2251 ;;; Return true if LVAR's only use is a call to one of the named functions
2252 ;;; (or any function if none are specified) with the specified number of
2253 ;;; of arguments (or any number if number is not specified)
2254 (defun lvar-matches (lvar &key fun-names arg-count)
2255   (let ((use (lvar-uses lvar)))
2256     (and (combination-p use)
2257          (or (not fun-names)
2258              (multiple-value-bind (name ok)
2259                  (combination-fun-source-name use nil)
2260                (and ok (member name fun-names :test #'eq))))
2261          (or (not arg-count)
2262              (= arg-count (length (combination-args use)))))))