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