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