fd32077d92b1b21eb020b1d71d3f0667d3b3fb8e
[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     (let* ((start (make-continuation))
41            (block (continuation-starts-block start))
42            (cont (make-continuation))
43            (*lexenv* (if cleanup
44                          (make-lexenv :cleanup cleanup)
45                          *lexenv*)))
46       (change-block-successor block1 block2 block)
47       (link-blocks block block2)
48       (ir1-convert start cont form)
49       (setf (block-last block) (continuation-use cont))
50       block)))
51 \f
52 ;;;; continuation use hacking
53
54 ;;; Return a list of all the nodes which use Cont.
55 (declaim (ftype (function (continuation) list) find-uses))
56 (defun find-uses (cont)
57   (ecase (continuation-kind cont)
58     ((:block-start :deleted-block-start)
59      (block-start-uses (continuation-block cont)))
60     (:inside-block (list (continuation-use cont)))
61     (:unused nil)
62     (:deleted nil)))
63
64 ;;; Update continuation use information so that NODE is no longer a
65 ;;; use of its CONT. If the old continuation doesn't start its block,
66 ;;; then we don't update the BLOCK-START-USES, since it will be
67 ;;; deleted when we are done.
68 ;;;
69 ;;; Note: if you call this function, you may have to do a
70 ;;; REOPTIMIZE-CONTINUATION to inform IR1 optimization that something
71 ;;; has changed.
72 (declaim (ftype (function (node) (values)) delete-continuation-use))
73 (defun delete-continuation-use (node)
74   (let* ((cont (node-cont node))
75          (block (continuation-block cont)))
76     (ecase (continuation-kind cont)
77       (:deleted)
78       ((:block-start :deleted-block-start)
79        (let ((uses (delete node (block-start-uses block))))
80          (setf (block-start-uses block) uses)
81          (setf (continuation-use cont)
82                (if (cdr uses) nil (car uses)))))
83       (:inside-block
84        (setf (continuation-kind cont) :unused)
85        (setf (continuation-block cont) nil)
86        (setf (continuation-use cont) nil)
87        (setf (continuation-next cont) nil)))
88     (setf (node-cont node) nil))
89   (values))
90
91 ;;; Update continuation use information so that NODE uses CONT. If
92 ;;; CONT is :UNUSED, then we set its block to NODE's NODE-BLOCK (which
93 ;;; must be set.)
94 ;;;
95 ;;; Note: if you call this function, you may have to do a
96 ;;; REOPTIMIZE-CONTINUATION to inform IR1 optimization that something
97 ;;; has changed.
98 (declaim (ftype (function (node continuation) (values)) add-continuation-use))
99 (defun add-continuation-use (node cont)
100   (aver (not (node-cont node)))
101   (let ((block (continuation-block cont)))
102     (ecase (continuation-kind cont)
103       (:deleted)
104       (:unused
105        (aver (not block))
106        (let ((block (node-block node)))
107          (aver block)
108          (setf (continuation-block cont) block))
109        (setf (continuation-kind cont) :inside-block)
110        (setf (continuation-use cont) node))
111       ((:block-start :deleted-block-start)
112        (let ((uses (cons node (block-start-uses block))))
113          (setf (block-start-uses block) uses)
114          (setf (continuation-use cont)
115                (if (cdr uses) nil (car uses)))))))
116   (setf (node-cont node) cont)
117   (values))
118
119 ;;; Return true if CONT is the NODE-CONT for NODE and CONT is
120 ;;; transferred to immediately after the evaluation of NODE.
121 (defun immediately-used-p (cont node)
122   (declare (type continuation cont) (type node node))
123   (and (eq (node-cont node) cont)
124        (not (eq (continuation-kind cont) :deleted))
125        (let ((cblock (continuation-block cont))
126              (nblock (node-block node)))
127          (or (eq cblock nblock)
128              (let ((succ (block-succ nblock)))
129                (and (= (length succ) 1)
130                     (eq (first succ) cblock)))))))
131 \f
132 ;;;; continuation substitution
133
134 ;;; In OLD's DEST, replace OLD with NEW. NEW's DEST must initially be
135 ;;; NIL. When we are done, we call FLUSH-DEST on OLD to clear its DEST
136 ;;; and to note potential optimization opportunities.
137 (defun substitute-continuation (new old)
138   (declare (type continuation old new))
139   (aver (not (continuation-dest new)))
140   (let ((dest (continuation-dest old)))
141     (etypecase dest
142       ((or ref bind))
143       (cif (setf (if-test dest) new))
144       (cset (setf (set-value dest) new))
145       (creturn (setf (return-result dest) new))
146       (exit (setf (exit-value dest) new))
147       (basic-combination
148        (if (eq old (basic-combination-fun dest))
149            (setf (basic-combination-fun dest) new)
150            (setf (basic-combination-args dest)
151                  (nsubst new old (basic-combination-args dest))))))
152
153     (flush-dest old)
154     (setf (continuation-dest new) dest))
155   (values))
156
157 ;;; Replace all uses of OLD with uses of NEW, where NEW has an
158 ;;; arbitary number of uses. If NEW will end up with more than one
159 ;;; use, then we must arrange for it to start a block if it doesn't
160 ;;; already.
161 (defun substitute-continuation-uses (new old)
162   (declare (type continuation old new))
163   (unless (and (eq (continuation-kind new) :unused)
164                (eq (continuation-kind old) :inside-block))
165     (ensure-block-start new))
166
167   (do-uses (node old)
168     (delete-continuation-use node)
169     (add-continuation-use node new))
170   (dolist (lexenv-use (continuation-lexenv-uses old))
171     (setf (cadr lexenv-use) new))
172
173   (reoptimize-continuation new)
174   (values))
175 \f
176 ;;;; block starting/creation
177
178 ;;; Return the block that CONT is the start of, making a block if
179 ;;; necessary. This function is called by IR1 translators which may
180 ;;; cause a continuation to be used more than once. Every continuation
181 ;;; which may be used more than once must start a block by the time
182 ;;; that anyone does a USE-CONTINUATION on it.
183 ;;;
184 ;;; We also throw the block into the next/prev list for the
185 ;;; *CURRENT-COMPONENT* so that we keep track of which blocks we have
186 ;;; made.
187 (defun continuation-starts-block (cont)
188   (declare (type continuation cont))
189   (ecase (continuation-kind cont)
190     (:unused
191      (aver (not (continuation-block cont)))
192      (let* ((head (component-head *current-component*))
193             (next (block-next head))
194             (new-block (make-block cont)))
195        (setf (block-next new-block) next)
196        (setf (block-prev new-block) head)
197        (setf (block-prev next) new-block)
198        (setf (block-next head) new-block)
199        (setf (continuation-block cont) new-block)
200        (setf (continuation-use cont) nil)
201        (setf (continuation-kind cont) :block-start)
202        new-block))
203     (:block-start
204      (continuation-block cont))))
205
206 ;;; Ensure that CONT is the start of a block (or deleted) so that
207 ;;; the use set can be freely manipulated.
208 ;;; -- If the continuation is :UNUSED or is :INSIDE-BLOCK and the
209 ;;;    CONT of LAST in its block, then we make it the start of a new
210 ;;;    deleted block.
211 ;;; -- If the continuation is :INSIDE-BLOCK inside a block, then we
212 ;;;    split the block using Node-Ends-Block, which makes the
213 ;;;    continuation be a :BLOCK-START.
214 (defun ensure-block-start (cont)
215   (declare (type continuation cont))
216   (let ((kind (continuation-kind cont)))
217     (ecase kind
218       ((:deleted :block-start :deleted-block-start))
219       ((:unused :inside-block)
220        (let ((block (continuation-block cont)))
221          (cond ((or (eq kind :unused)
222                     (eq (node-cont (block-last block)) cont))
223                 (setf (continuation-block cont)
224                       (make-block-key :start cont
225                                       :component nil
226                                       :start-uses (find-uses cont)))
227                 (setf (continuation-kind cont) :deleted-block-start))
228                (t
229                 (node-ends-block (continuation-use cont))))))))
230   (values))
231 \f
232 ;;;; miscellaneous shorthand functions
233
234 ;;; Return the home (i.e. enclosing non-LET) CLAMBDA for NODE. Since
235 ;;; the LEXENV-LAMBDA may be deleted, we must chain up the
236 ;;; LAMBDA-CALL-LEXENV thread until we find a CLAMBDA that isn't
237 ;;; deleted, and then return its home.
238 (defun node-home-lambda (node)
239   (declare (type node node))
240   (do ((fun (lexenv-lambda (node-lexenv node))
241             (lexenv-lambda (lambda-call-lexenv fun))))
242       ((not (eq (functional-kind fun) :deleted))
243        (lambda-home fun))
244     (when (eq (lambda-home fun) fun)
245       (return fun))))
246
247 (defun node-block (node)
248   (declare (type node node))
249   (the cblock (continuation-block (node-prev node))))
250 (defun node-component (node)
251   (declare (type node node))
252   (block-component (node-block node)))
253 (defun node-physenv (node)
254   (declare (type node node))
255   (the physenv (lambda-physenv (node-home-lambda node))))
256
257 (defun lambda-block (clambda)
258   (declare (type clambda clambda))
259   (node-block (lambda-bind clambda)))
260 (defun lambda-component (clambda)
261   (block-component (lambda-block clambda)))
262
263 ;;; Return the enclosing cleanup for environment of the first or last
264 ;;; node in BLOCK.
265 (defun block-start-cleanup (block)
266   (declare (type cblock block))
267   (node-enclosing-cleanup (continuation-next (block-start block))))
268 (defun block-end-cleanup (block)
269   (declare (type cblock block))
270   (node-enclosing-cleanup (block-last block)))
271
272 ;;; Return the non-LET LAMBDA that holds BLOCK's code, or NIL
273 ;;; if there is none.
274 ;;;
275 ;;; There can legitimately be no home lambda in dead code early in the
276 ;;; IR1 conversion process, e.g. when IR1-converting the SETQ form in
277 ;;;   (BLOCK B (RETURN-FROM B) (SETQ X 3))
278 ;;; where the block is just a placeholder during parsing and doesn't
279 ;;; actually correspond to code which will be written anywhere.
280 (defun block-home-lambda-or-null (block)
281   (declare (type cblock block))
282   (if (node-p (block-last block))
283       ;; This is the old CMU CL way of doing it.
284       (node-home-lambda (block-last block))
285       ;; Now that SBCL uses this operation more aggressively than CMU
286       ;; CL did, the old CMU CL way of doing it can fail in two ways.
287       ;;   1. It can fail in a few cases even when a meaningful home
288       ;;      lambda exists, e.g. in IR1-CONVERT of one of the legs of
289       ;;      an IF.
290       ;;   2. It can fail when converting a form which is born orphaned 
291       ;;      so that it never had a meaningful home lambda, e.g. a form
292       ;;      which follows a RETURN-FROM or GO form.
293       (let ((pred-list (block-pred block)))
294         ;; To deal with case 1, we reason that
295         ;; previous-in-target-execution-order blocks should be in the
296         ;; same lambda, and that they seem in practice to be
297         ;; previous-in-compilation-order blocks too, so we look back
298         ;; to find one which is sufficiently initialized to tell us
299         ;; what the home lambda is.
300         (if pred-list
301             ;; We could get fancy about this, flooding through the
302             ;; graph of all the previous blocks, but in practice it
303             ;; seems to work just to grab the first previous block and
304             ;; use it.
305             (node-home-lambda (block-last (first pred-list)))
306             ;; In case 2, we end up with an empty PRED-LIST and
307             ;; have to punt: There's no home lambda.
308             nil))))
309
310 ;;; Return the non-LET LAMBDA that holds BLOCK's code.
311 (defun block-home-lambda (block)
312   (the clambda
313     (block-home-lambda-or-null block)))
314
315 ;;; Return the IR1 physical environment for BLOCK.
316 (defun block-physenv (block)
317   (declare (type cblock block))
318   (lambda-physenv (block-home-lambda block)))
319
320 ;;; Return the Top Level Form number of PATH, i.e. the ordinal number
321 ;;; of its original source's top level form in its compilation unit.
322 (defun source-path-tlf-number (path)
323   (declare (list path))
324   (car (last path)))
325
326 ;;; Return the (reversed) list for the PATH in the original source
327 ;;; (with the Top Level Form number last).
328 (defun source-path-original-source (path)
329   (declare (list path) (inline member))
330   (cddr (member 'original-source-start path :test #'eq)))
331
332 ;;; Return the Form Number of PATH's original source inside the Top
333 ;;; Level Form that contains it. This is determined by the order that
334 ;;; we walk the subforms of the top level source form.
335 (defun source-path-form-number (path)
336   (declare (list path) (inline member))
337   (cadr (member 'original-source-start path :test #'eq)))
338
339 ;;; Return a list of all the enclosing forms not in the original
340 ;;; source that converted to get to this form, with the immediate
341 ;;; source for node at the start of the list.
342 (defun source-path-forms (path)
343   (subseq path 0 (position 'original-source-start path)))
344
345 ;;; Return the innermost source form for NODE.
346 (defun node-source-form (node)
347   (declare (type node node))
348   (let* ((path (node-source-path node))
349          (forms (source-path-forms path)))
350     (if forms
351         (first forms)
352         (values (find-original-source path)))))
353
354 ;;; Return NODE-SOURCE-FORM, T if continuation has a single use,
355 ;;; otherwise NIL, NIL.
356 (defun continuation-source (cont)
357   (let ((use (continuation-use cont)))
358     (if use
359         (values (node-source-form use) t)
360         (values nil nil))))
361
362 ;;; Return the LAMBDA that is CONT's home, or NIL if there is none.
363 (defun continuation-home-lambda-or-null (cont)
364   ;; KLUDGE: This function is a post-CMU-CL hack by WHN, and this
365   ;; implementation might not be quite right, or might be uglier than
366   ;; necessary. It appears that the original Python never found a need
367   ;; to do this operation. The obvious things based on
368   ;; NODE-HOME-LAMBDA of CONTINUATION-USE usually work; then if that
369   ;; fails, BLOCK-HOME-LAMBDA of CONTINUATION-BLOCK works, given that
370   ;; we generalize it enough to grovel harder when the simple CMU CL
371   ;; approach fails, and furthermore realize that in some exceptional
372   ;; cases it might return NIL. -- WHN 2001-12-04
373   (cond ((continuation-use cont)
374          (node-home-lambda (continuation-use cont)))
375         ((continuation-block cont)
376          (block-home-lambda-or-null (continuation-block cont)))
377         (t
378          (bug "confused about home lambda for ~S"))))
379
380 ;;; Return the LAMBDA that is CONT's home.
381 (defun continuation-home-lambda (cont)
382   (the clambda
383     (continuation-home-lambda-or-null cont)))
384 \f
385 ;;; Return a new LEXENV just like DEFAULT except for the specified
386 ;;; slot values. Values for the alist slots are NCONCed to the
387 ;;; beginning of the current value, rather than replacing it entirely.
388 (defun make-lexenv (&key (default *lexenv*)
389                          funs vars blocks tags type-restrictions options
390                          (lambda (lexenv-lambda default))
391                          (cleanup (lexenv-cleanup default))
392                          (policy (lexenv-policy default)))
393   (macrolet ((frob (var slot)
394                `(let ((old (,slot default)))
395                   (if ,var
396                       (nconc ,var old)
397                       old))))
398     (internal-make-lexenv
399      (frob funs lexenv-funs)
400      (frob vars lexenv-vars)
401      (frob blocks lexenv-blocks)
402      (frob tags lexenv-tags)
403      (frob type-restrictions lexenv-type-restrictions)
404      lambda cleanup policy 
405      (frob options lexenv-options))))
406 \f
407 ;;;; flow/DFO/component hackery
408
409 ;;; Join BLOCK1 and BLOCK2.
410 (defun link-blocks (block1 block2)
411   (declare (type cblock block1 block2))
412   (setf (block-succ block1)
413         (if (block-succ block1)
414             (%link-blocks block1 block2)
415             (list block2)))
416   (push block1 (block-pred block2))
417   (values))
418 (defun %link-blocks (block1 block2)
419   (declare (type cblock block1 block2) (inline member))
420   (let ((succ1 (block-succ block1)))
421     (aver (not (member block2 succ1 :test #'eq)))
422     (cons block2 succ1)))
423
424 ;;; This is like LINK-BLOCKS, but we separate BLOCK1 and BLOCK2. If
425 ;;; this leaves a successor with a single predecessor that ends in an
426 ;;; IF, then set BLOCK-TEST-MODIFIED so that any test constraint will
427 ;;; now be able to be propagated to the successor.
428 (defun unlink-blocks (block1 block2)
429   (declare (type cblock block1 block2))
430   (let ((succ1 (block-succ block1)))
431     (if (eq block2 (car succ1))
432         (setf (block-succ block1) (cdr succ1))
433         (do ((succ (cdr succ1) (cdr succ))
434              (prev succ1 succ))
435             ((eq (car succ) block2)
436              (setf (cdr prev) (cdr succ)))
437           (aver succ))))
438
439   (let ((new-pred (delq block1 (block-pred block2))))
440     (setf (block-pred block2) new-pred)
441     (when (and new-pred (null (rest new-pred)))
442       (let ((pred-block (first new-pred)))
443         (when (if-p (block-last pred-block))
444           (setf (block-test-modified pred-block) t)))))
445   (values))
446
447 ;;; Swing the succ/pred link between BLOCK and OLD to be between BLOCK
448 ;;; and NEW. If BLOCK ends in an IF, then we have to fix up the
449 ;;; consequent/alternative blocks to point to NEW. We also set
450 ;;; BLOCK-TEST-MODIFIED so that any test constraint will be applied to
451 ;;; the new successor.
452 (defun change-block-successor (block old new)
453   (declare (type cblock new old block) (inline member))
454   (unlink-blocks block old)
455   (let ((last (block-last block))
456         (comp (block-component block)))
457     (setf (component-reanalyze comp) t)
458     (typecase last
459       (cif
460        (setf (block-test-modified block) t)
461        (let* ((succ-left (block-succ block))
462               (new (if (and (eq new (component-tail comp))
463                             succ-left)
464                        (first succ-left)
465                        new)))
466          (unless (member new succ-left :test #'eq)
467            (link-blocks block new))
468          (macrolet ((frob (slot)
469                       `(when (eq (,slot last) old)
470                          (setf (,slot last) new))))
471            (frob if-consequent)
472            (frob if-alternative))))
473       (t
474        (unless (member new (block-succ block) :test #'eq)
475          (link-blocks block new)))))
476
477   (values))
478
479 ;;; Unlink a block from the next/prev chain. We also null out the
480 ;;; COMPONENT.
481 (declaim (ftype (function (cblock) (values)) remove-from-dfo))
482 (defun remove-from-dfo (block)
483   (let ((next (block-next block))
484         (prev (block-prev block)))
485     (setf (block-component block) nil)
486     (setf (block-next prev) next)
487     (setf (block-prev next) prev))
488   (values))
489
490 ;;; Add BLOCK to the next/prev chain following AFTER. We also set the
491 ;;; Component to be the same as for AFTER.
492 (defun add-to-dfo (block after)
493   (declare (type cblock block after))
494   (let ((next (block-next after))
495         (comp (block-component after)))
496     (aver (not (eq (component-kind comp) :deleted)))
497     (setf (block-component block) comp)
498     (setf (block-next after) block)
499     (setf (block-prev block) after)
500     (setf (block-next block) next)
501     (setf (block-prev next) block))
502   (values))
503
504 ;;; Set the FLAG for all the blocks in COMPONENT to NIL, except for
505 ;;; the head and tail which are set to T.
506 (declaim (ftype (function (component) (values)) clear-flags))
507 (defun clear-flags (component)
508   (let ((head (component-head component))
509         (tail (component-tail component)))
510     (setf (block-flag head) t)
511     (setf (block-flag tail) t)
512     (do-blocks (block component)
513       (setf (block-flag block) nil)))
514   (values))
515
516 ;;; Make a component with no blocks in it. The BLOCK-FLAG is initially
517 ;;; true in the head and tail blocks.
518 (declaim (ftype (function nil component) make-empty-component))
519 (defun make-empty-component ()
520   (let* ((head (make-block-key :start nil :component nil))
521          (tail (make-block-key :start nil :component nil))
522          (res (make-component :head head :tail tail)))
523     (setf (block-flag head) t)
524     (setf (block-flag tail) t)
525     (setf (block-component head) res)
526     (setf (block-component tail) res)
527     (setf (block-next head) tail)
528     (setf (block-prev tail) head)
529     res))
530
531 ;;; Make NODE the LAST node in its block, splitting the block if necessary.
532 ;;; The new block is added to the DFO immediately following NODE's block.
533 (defun node-ends-block (node)
534   (declare (type node node))
535   (let* ((block (node-block node))
536          (start (node-cont node))
537          (last (block-last block))
538          (last-cont (node-cont last)))
539     (unless (eq last node)
540       (aver (and (eq (continuation-kind start) :inside-block)
541                    (not (block-delete-p block))))
542       (let* ((succ (block-succ block))
543              (new-block
544               (make-block-key :start start
545                               :component (block-component block)
546                               :start-uses (list (continuation-use start))
547                               :succ succ :last last)))
548         (setf (continuation-kind start) :block-start)
549         (dolist (b succ)
550           (setf (block-pred b)
551                 (cons new-block (remove block (block-pred b)))))
552         (setf (block-succ block) ())
553         (setf (block-last block) node)
554         (link-blocks block new-block)
555         (add-to-dfo new-block block)
556         (setf (component-reanalyze (block-component block)) t)
557         
558         (do ((cont start (node-cont (continuation-next cont))))
559             ((eq cont last-cont)
560              (when (eq (continuation-kind last-cont) :inside-block)
561                (setf (continuation-block last-cont) new-block)))
562           (setf (continuation-block cont) new-block))
563
564         (setf (block-type-asserted block) t)
565         (setf (block-test-modified block) t))))
566
567   (values))
568 \f
569 ;;;; deleting stuff
570
571 ;;; Deal with deleting the last (read) reference to a LAMBDA-VAR. We
572 ;;; iterate over all local calls flushing the corresponding argument,
573 ;;; allowing the computation of the argument to be deleted. We also
574 ;;; mark the let for reoptimization, since it may be that we have
575 ;;; deleted the last variable.
576 ;;;
577 ;;; The LAMBDA-VAR may still have some SETs, but this doesn't cause
578 ;;; too much difficulty, since we can efficiently implement write-only
579 ;;; variables. We iterate over the sets, marking their blocks for dead
580 ;;; code flushing, since we can delete sets whose value is unused.
581 (defun delete-lambda-var (leaf)
582   (declare (type lambda-var leaf))
583   (let* ((fun (lambda-var-home leaf))
584          (n (position leaf (lambda-vars fun))))
585     (dolist (ref (leaf-refs fun))
586       (let* ((cont (node-cont ref))
587              (dest (continuation-dest cont)))
588         (when (and (combination-p dest)
589                    (eq (basic-combination-fun dest) cont)
590                    (eq (basic-combination-kind dest) :local))
591           (let* ((args (basic-combination-args dest))
592                  (arg (elt args n)))
593             (reoptimize-continuation arg)
594             (flush-dest arg)
595             (setf (elt args n) nil))))))
596
597   (dolist (set (lambda-var-sets leaf))
598     (setf (block-flush-p (node-block set)) t))
599
600   (values))
601
602 ;;; Note that something interesting has happened to VAR. We only deal
603 ;;; with LET variables, marking the corresponding initial value arg as
604 ;;; needing to be reoptimized.
605 (defun reoptimize-lambda-var (var)
606   (declare (type lambda-var var))
607   (let ((fun (lambda-var-home var)))
608     (when (and (eq (functional-kind fun) :let)
609                (leaf-refs var))
610       (do ((args (basic-combination-args
611                   (continuation-dest
612                    (node-cont
613                     (first (leaf-refs fun)))))
614                  (cdr args))
615            (vars (lambda-vars fun) (cdr vars)))
616           ((eq (car vars) var)
617            (reoptimize-continuation (car args))))))
618   (values))
619
620 ;;; Delete a function that has no references. This need only be called
621 ;;; on functions that never had any references, since otherwise
622 ;;; DELETE-REF will handle the deletion.
623 (defun delete-functional (fun)
624   (aver (and (null (leaf-refs fun))
625              (not (functional-entry-fun fun))))
626   (etypecase fun
627     (optional-dispatch (delete-optional-dispatch fun))
628     (clambda (delete-lambda fun)))
629   (values))
630
631 ;;; Deal with deleting the last reference to a LAMBDA. Since there is
632 ;;; only one way into a LAMBDA, deleting the last reference to a
633 ;;; LAMBDA ensures that there is no way to reach any of the code in
634 ;;; it. So we just set the FUNCTIONAL-KIND for FUN and its LETs to
635 ;;; :DELETED, causing IR1 optimization to delete blocks in that
636 ;;; lambda.
637 ;;;
638 ;;; If the function isn't a LET, we unlink the function head and tail
639 ;;; from the component head and tail to indicate that the code is
640 ;;; unreachable. We also delete the function from COMPONENT-LAMBDAS
641 ;;; (it won't be there before local call analysis, but no matter.) If
642 ;;; the lambda was never referenced, we give a note.
643 ;;;
644 ;;; If the lambda is an XEP, then we null out the ENTRY-FUN in its
645 ;;; ENTRY-FUN so that people will know that it is not an entry point
646 ;;; anymore.
647 (defun delete-lambda (leaf)
648   (declare (type clambda leaf))
649   (let ((kind (functional-kind leaf))
650         (bind (lambda-bind leaf)))
651     (aver (not (member kind '(:deleted :optional :toplevel))))
652     (aver (not (functional-has-external-references-p leaf)))
653     (setf (functional-kind leaf) :deleted)
654     (setf (lambda-bind leaf) nil)
655     (dolist (let (lambda-lets leaf))
656       (setf (lambda-bind let) nil)
657       (setf (functional-kind let) :deleted))
658
659     (if (member kind '(:let :mv-let :assignment))
660         (let ((home (lambda-home leaf)))
661           (setf (lambda-lets home) (delete leaf (lambda-lets home))))
662         (let* ((bind-block (node-block bind))
663                (component (block-component bind-block))
664                (return (lambda-return leaf)))
665           (aver (null (leaf-refs leaf)))
666           (unless (leaf-ever-used leaf)
667             (let ((*compiler-error-context* bind))
668               (compiler-note "deleting unused function~:[.~;~:*~%  ~S~]"
669                              (leaf-debug-name leaf))))
670           (unlink-blocks (component-head component) bind-block)
671           (when return
672             (unlink-blocks (node-block return) (component-tail component)))
673           (setf (component-reanalyze component) t)
674           (let ((tails (lambda-tail-set leaf)))
675             (setf (tail-set-funs tails)
676                   (delete leaf (tail-set-funs tails)))
677             (setf (lambda-tail-set leaf) nil))
678           (setf (component-lambdas component)
679                 (delete leaf (component-lambdas component)))))
680
681     (when (eq kind :external)
682       (let ((fun (functional-entry-fun leaf)))
683         (setf (functional-entry-fun fun) nil)
684         (when (optional-dispatch-p fun)
685           (delete-optional-dispatch fun)))))
686
687   (values))
688
689 ;;; Deal with deleting the last reference to an OPTIONAL-DISPATCH. We
690 ;;; have to be a bit more careful than with lambdas, since DELETE-REF
691 ;;; is used both before and after local call analysis. Afterward, all
692 ;;; references to still-existing OPTIONAL-DISPATCHes have been moved
693 ;;; to the XEP, leaving it with no references at all. So we look at
694 ;;; the XEP to see whether an optional-dispatch is still really being
695 ;;; used. But before local call analysis, there are no XEPs, and all
696 ;;; references are direct.
697 ;;;
698 ;;; When we do delete the OPTIONAL-DISPATCH, we grovel all of its
699 ;;; entry-points, making them be normal lambdas, and then deleting the
700 ;;; ones with no references. This deletes any e-p lambdas that were
701 ;;; either never referenced, or couldn't be deleted when the last
702 ;;; deference was deleted (due to their :OPTIONAL kind.)
703 ;;;
704 ;;; Note that the last optional ep may alias the main entry, so when
705 ;;; we process the main entry, its kind may have been changed to NIL
706 ;;; or even converted to a let.
707 (defun delete-optional-dispatch (leaf)
708   (declare (type optional-dispatch leaf))
709   (let ((entry (functional-entry-fun leaf)))
710     (unless (and entry (leaf-refs entry))
711       (aver (or (not entry) (eq (functional-kind entry) :deleted)))
712       (setf (functional-kind leaf) :deleted)
713
714       (flet ((frob (fun)
715                (unless (eq (functional-kind fun) :deleted)
716                  (aver (eq (functional-kind fun) :optional))
717                  (setf (functional-kind fun) nil)
718                  (let ((refs (leaf-refs fun)))
719                    (cond ((null refs)
720                           (delete-lambda fun))
721                          ((null (rest refs))
722                           (or (maybe-let-convert fun)
723                               (maybe-convert-to-assignment fun)))
724                          (t
725                           (maybe-convert-to-assignment fun)))))))
726         
727         (dolist (ep (optional-dispatch-entry-points leaf))
728           (frob ep))
729         (when (optional-dispatch-more-entry leaf)
730           (frob (optional-dispatch-more-entry leaf)))
731         (let ((main (optional-dispatch-main-entry leaf)))
732           (when (eq (functional-kind main) :optional)
733             (frob main))))))
734
735   (values))
736
737 ;;; Do stuff to delete the semantic attachments of a REF node. When
738 ;;; this leaves zero or one reference, we do a type dispatch off of
739 ;;; the leaf to determine if a special action is appropriate.
740 (defun delete-ref (ref)
741   (declare (type ref ref))
742   (let* ((leaf (ref-leaf ref))
743          (refs (delete ref (leaf-refs leaf))))
744     (setf (leaf-refs leaf) refs)
745
746     (cond ((null refs)
747            (typecase leaf
748              (lambda-var
749               (delete-lambda-var leaf))
750              (clambda
751               (ecase (functional-kind leaf)
752                 ((nil :let :mv-let :assignment :escape :cleanup)
753                  (aver (not (functional-entry-fun leaf)))
754                  (delete-lambda leaf))
755                 (:external
756                  (delete-lambda leaf))
757                 ((:deleted :optional))))
758              (optional-dispatch
759               (unless (eq (functional-kind leaf) :deleted)
760                 (delete-optional-dispatch leaf)))))
761           ((null (rest refs))
762            (typecase leaf
763              (clambda (or (maybe-let-convert leaf)
764                           (maybe-convert-to-assignment leaf)))
765              (lambda-var (reoptimize-lambda-var leaf))))
766           (t
767            (typecase leaf
768              (clambda (maybe-convert-to-assignment leaf))))))
769
770   (values))
771
772 ;;; This function is called by people who delete nodes; it provides a
773 ;;; way to indicate that the value of a continuation is no longer
774 ;;; used. We null out the CONTINUATION-DEST, set FLUSH-P in the blocks
775 ;;; containing uses of CONT and set COMPONENT-REOPTIMIZE. If the PREV
776 ;;; of the use is deleted, then we blow off reoptimization.
777 ;;;
778 ;;; If the continuation is :Deleted, then we don't do anything, since
779 ;;; all semantics have already been flushed. :DELETED-BLOCK-START
780 ;;; start continuations are treated just like :BLOCK-START; it is
781 ;;; possible that the continuation may be given a new dest (e.g. by
782 ;;; SUBSTITUTE-CONTINUATION), so we don't want to delete it.
783 (defun flush-dest (cont)
784   (declare (type continuation cont))
785
786   (unless (eq (continuation-kind cont) :deleted)
787     (aver (continuation-dest cont))
788     (setf (continuation-dest cont) nil)
789     (do-uses (use cont)
790       (let ((prev (node-prev use)))
791         (unless (eq (continuation-kind prev) :deleted)
792           (let ((block (continuation-block prev)))
793             (setf (component-reoptimize (block-component block)) t)
794             (setf (block-attributep (block-flags block) flush-p type-asserted)
795                   t))))))
796
797   (setf (continuation-%type-check cont) nil)
798
799   (values))
800
801 ;;; Do a graph walk backward from BLOCK, marking all predecessor
802 ;;; blocks with the DELETE-P flag.
803 (defun mark-for-deletion (block)
804   (declare (type cblock block))
805   (unless (block-delete-p block)
806     (setf (block-delete-p block) t)
807     (setf (component-reanalyze (block-component block)) t)
808     (dolist (pred (block-pred block))
809       (mark-for-deletion pred)))
810   (values))
811
812 ;;; Delete CONT, eliminating both control and value semantics. We set
813 ;;; FLUSH-P and COMPONENT-REOPTIMIZE similarly to in FLUSH-DEST. Here
814 ;;; we must get the component from the use block, since the
815 ;;; continuation may be a :DELETED-BLOCK-START.
816 ;;;
817 ;;; If CONT has DEST, then it must be the case that the DEST is
818 ;;; unreachable, since we can't compute the value desired. In this
819 ;;; case, we call MARK-FOR-DELETION to cause the DEST block and its
820 ;;; predecessors to tell people to ignore them, and to cause them to
821 ;;; be deleted eventually.
822 (defun delete-continuation (cont)
823   (declare (type continuation cont))
824   (aver (not (eq (continuation-kind cont) :deleted)))
825
826   (do-uses (use cont)
827     (let ((prev (node-prev use)))
828       (unless (eq (continuation-kind prev) :deleted)
829         (let ((block (continuation-block prev)))
830           (setf (block-attributep (block-flags block) flush-p type-asserted) t)
831           (setf (component-reoptimize (block-component block)) t)))))
832
833   (let ((dest (continuation-dest cont)))
834     (when dest
835       (let ((prev (node-prev dest)))
836         (when (and prev
837                    (not (eq (continuation-kind prev) :deleted)))
838           (let ((block (continuation-block prev)))
839             (unless (block-delete-p block)
840               (mark-for-deletion block)))))))
841
842   (setf (continuation-kind cont) :deleted)
843   (setf (continuation-dest cont) nil)
844   (setf (continuation-next cont) nil)
845   (setf (continuation-asserted-type cont) *empty-type*)
846   (setf (continuation-%derived-type cont) *empty-type*)
847   (setf (continuation-use cont) nil)
848   (setf (continuation-block cont) nil)
849   (setf (continuation-reoptimize cont) nil)
850   (setf (continuation-%type-check cont) nil)
851   (setf (continuation-info cont) nil)
852
853   (values))
854
855 ;;; This function does what is necessary to eliminate the code in it
856 ;;; from the IR1 representation. This involves unlinking it from its
857 ;;; predecessors and successors and deleting various node-specific
858 ;;; semantic information.
859 ;;;
860 ;;; We mark the START as has having no next and remove the last node
861 ;;; from its CONT's uses. We also flush the DEST for all continuations
862 ;;; whose values are received by nodes in the block.
863 (defun delete-block (block)
864   (declare (type cblock block))
865   (aver (block-component block)) ; else block is already deleted!
866   (note-block-deletion block)
867   (setf (block-delete-p block) t)
868
869   (let* ((last (block-last block))
870          (cont (node-cont last)))
871     (delete-continuation-use last)
872     (if (eq (continuation-kind cont) :unused)
873         (delete-continuation cont)
874         (reoptimize-continuation cont)))
875
876   (dolist (b (block-pred block))
877     (unlink-blocks b block))
878   (dolist (b (block-succ block))
879     (unlink-blocks block b))
880
881   (do-nodes (node cont block)
882     (typecase node
883       (ref (delete-ref node))
884       (cif
885        (flush-dest (if-test node)))
886       ;; The next two cases serve to maintain the invariant that a LET
887       ;; always has a well-formed COMBINATION, REF and BIND. We delete
888       ;; the lambda whenever we delete any of these, but we must be
889       ;; careful that this LET has not already been partially deleted.
890       (basic-combination
891        (when (and (eq (basic-combination-kind node) :local)
892                   ;; Guards COMBINATION-LAMBDA agains the REF being deleted.
893                   (continuation-use (basic-combination-fun node)))
894          (let ((fun (combination-lambda node)))
895            ;; If our REF was the 2'nd to last ref, and has been deleted, then
896            ;; Fun may be a LET for some other combination.
897            (when (and (member (functional-kind fun) '(:let :mv-let))
898                       (eq (let-combination fun) node))
899              (delete-lambda fun))))
900        (flush-dest (basic-combination-fun node))
901        (dolist (arg (basic-combination-args node))
902          (when arg (flush-dest arg))))
903       (bind
904        (let ((lambda (bind-lambda node)))
905          (unless (eq (functional-kind lambda) :deleted)
906            (aver (member (functional-kind lambda) '(:let :mv-let :assignment)))
907            (delete-lambda lambda))))
908       (exit
909        (let ((value (exit-value node))
910              (entry (exit-entry node)))
911          (when value
912            (flush-dest value))
913          (when entry
914            (setf (entry-exits entry)
915                  (delete node (entry-exits entry))))))
916       (creturn
917        (flush-dest (return-result node))
918        (delete-return node))
919       (cset
920        (flush-dest (set-value node))
921        (let ((var (set-var node)))
922          (setf (basic-var-sets var)
923                (delete node (basic-var-sets var))))))
924
925     (delete-continuation (node-prev node)))
926
927   (remove-from-dfo block)
928   (values))
929
930 ;;; Do stuff to indicate that the return node Node is being deleted.
931 ;;; We set the RETURN to NIL.
932 (defun delete-return (node)
933   (declare (type creturn node))
934   (let ((fun (return-lambda node)))
935     (aver (lambda-return fun))
936     (setf (lambda-return fun) nil))
937   (values))
938
939 ;;; If any of the VARS in FUN was never referenced and was not
940 ;;; declared IGNORE, then complain.
941 (defun note-unreferenced-vars (fun)
942   (declare (type clambda fun))
943   (dolist (var (lambda-vars fun))
944     (unless (or (leaf-ever-used var)
945                 (lambda-var-ignorep var))
946       (let ((*compiler-error-context* (lambda-bind fun)))
947         (unless (policy *compiler-error-context* (= inhibit-warnings 3))
948           ;; ANSI section "3.2.5 Exceptional Situations in the Compiler"
949           ;; requires this to be no more than a STYLE-WARNING.
950           (compiler-style-warn "The variable ~S is defined but never used."
951                                (leaf-debug-name var)))
952         (setf (leaf-ever-used var) t)))) ; to avoid repeated warnings? -- WHN
953   (values))
954
955 (defvar *deletion-ignored-objects* '(t nil))
956
957 ;;; Return true if we can find OBJ in FORM, NIL otherwise. We bound
958 ;;; our recursion so that we don't get lost in circular structures. We
959 ;;; ignore the car of forms if they are a symbol (to prevent confusing
960 ;;; function referencess with variables), and we also ignore anything
961 ;;; inside ' or #'.
962 (defun present-in-form (obj form depth)
963   (declare (type (integer 0 20) depth))
964   (cond ((= depth 20) nil)
965         ((eq obj form) t)
966         ((atom form) nil)
967         (t
968          (let ((first (car form))
969                (depth (1+ depth)))
970            (if (member first '(quote function))
971                nil
972                (or (and (not (symbolp first))
973                         (present-in-form obj first depth))
974                    (do ((l (cdr form) (cdr l))
975                         (n 0 (1+ n)))
976                        ((or (atom l) (> n 100))
977                         nil)
978                      (declare (fixnum n))
979                      (when (present-in-form obj (car l) depth)
980                        (return t)))))))))
981
982 ;;; This function is called on a block immediately before we delete
983 ;;; it. We check to see whether any of the code about to die appeared
984 ;;; in the original source, and emit a note if so.
985 ;;;
986 ;;; If the block was in a lambda is now deleted, then we ignore the
987 ;;; whole block, since this case is picked off in DELETE-LAMBDA. We
988 ;;; also ignore the deletion of CRETURN nodes, since it is somewhat
989 ;;; reasonable for a function to not return, and there is a different
990 ;;; note for that case anyway.
991 ;;;
992 ;;; If the actual source is an atom, then we use a bunch of heuristics
993 ;;; to guess whether this reference really appeared in the original
994 ;;; source:
995 ;;; -- If a symbol, it must be interned and not a keyword.
996 ;;; -- It must not be an easily introduced constant (T or NIL, a fixnum
997 ;;;    or a character.)
998 ;;; -- The atom must be "present" in the original source form, and
999 ;;;    present in all intervening actual source forms.
1000 (defun note-block-deletion (block)
1001   (let ((home (block-home-lambda block)))
1002     (unless (eq (functional-kind home) :deleted)
1003       (do-nodes (node cont block)
1004         (let* ((path (node-source-path node))
1005                (first (first path)))
1006           (when (or (eq first 'original-source-start)
1007                     (and (atom first)
1008                          (or (not (symbolp first))
1009                              (let ((pkg (symbol-package first)))
1010                                (and pkg
1011                                     (not (eq pkg (symbol-package :end))))))
1012                          (not (member first *deletion-ignored-objects*))
1013                          (not (typep first '(or fixnum character)))
1014                          (every (lambda (x)
1015                                   (present-in-form first x 0))
1016                                 (source-path-forms path))
1017                          (present-in-form first (find-original-source path)
1018                                           0)))
1019             (unless (return-p node)
1020               (let ((*compiler-error-context* node))
1021                 (compiler-note "deleting unreachable code")))
1022             (return))))))
1023   (values))
1024
1025 ;;; Delete a node from a block, deleting the block if there are no
1026 ;;; nodes left. We remove the node from the uses of its CONT, but we
1027 ;;; don't deal with cleaning up any type-specific semantic
1028 ;;; attachments. If the CONT is :UNUSED after deleting this use, then
1029 ;;; we delete CONT. (Note :UNUSED is not the same as no uses. A
1030 ;;; continuation will only become :UNUSED if it was :INSIDE-BLOCK
1031 ;;; before.)
1032 ;;;
1033 ;;; If the node is the last node, there must be exactly one successor.
1034 ;;; We link all of our precedessors to the successor and unlink the
1035 ;;; block. In this case, we return T, otherwise NIL. If no nodes are
1036 ;;; left, and the block is a successor of itself, then we replace the
1037 ;;; only node with a degenerate exit node. This provides a way to
1038 ;;; represent the bodyless infinite loop, given the prohibition on
1039 ;;; empty blocks in IR1.
1040 (defun unlink-node (node)
1041   (declare (type node node))
1042   (let* ((cont (node-cont node))
1043          (next (continuation-next cont))
1044          (prev (node-prev node))
1045          (block (continuation-block prev))
1046          (prev-kind (continuation-kind prev))
1047          (last (block-last block)))
1048
1049     (unless (eq (continuation-kind cont) :deleted)
1050       (delete-continuation-use node)
1051       (when (eq (continuation-kind cont) :unused)
1052         (aver (not (continuation-dest cont)))
1053         (delete-continuation cont)))
1054
1055     (setf (block-type-asserted block) t)
1056     (setf (block-test-modified block) t)
1057
1058     (cond ((or (eq prev-kind :inside-block)
1059                (and (eq prev-kind :block-start)
1060                     (not (eq node last))))
1061            (cond ((eq node last)
1062                   (setf (block-last block) (continuation-use prev))
1063                   (setf (continuation-next prev) nil))
1064                  (t
1065                   (setf (continuation-next prev) next)
1066                   (setf (node-prev next) prev)))
1067            (setf (node-prev node) nil)
1068            nil)
1069           (t
1070            (aver (eq prev-kind :block-start))
1071            (aver (eq node last))
1072            (let* ((succ (block-succ block))
1073                   (next (first succ)))
1074              (aver (and succ (null (cdr succ))))
1075              (cond
1076               ((member block succ)
1077                (with-ir1-environment-from-node node
1078                  (let ((exit (make-exit))
1079                        (dummy (make-continuation)))
1080                    (setf (continuation-next prev) nil)
1081                    (link-node-to-previous-continuation exit prev)
1082                    (add-continuation-use exit dummy)
1083                    (setf (block-last block) exit)))
1084                (setf (node-prev node) nil)
1085                nil)
1086               (t
1087                (aver (eq (block-start-cleanup block)
1088                          (block-end-cleanup block)))
1089                (unlink-blocks block next)
1090                (dolist (pred (block-pred block))
1091                  (change-block-successor pred block next))
1092                (remove-from-dfo block)
1093                (cond ((continuation-dest prev)
1094                       (setf (continuation-next prev) nil)
1095                       (setf (continuation-kind prev) :deleted-block-start))
1096                      (t
1097                       (delete-continuation prev)))
1098                (setf (node-prev node) nil)
1099                t)))))))
1100
1101 ;;; Return true if NODE has been deleted, false if it is still a valid
1102 ;;; part of IR1.
1103 (defun node-deleted (node)
1104   (declare (type node node))
1105   (let ((prev (node-prev node)))
1106     (not (and prev
1107               (not (eq (continuation-kind prev) :deleted))
1108               (let ((block (continuation-block prev)))
1109                 (and (block-component block)
1110                      (not (block-delete-p block))))))))
1111
1112 ;;; Delete all the blocks and functions in COMPONENT. We scan first
1113 ;;; marking the blocks as DELETE-P to prevent weird stuff from being
1114 ;;; triggered by deletion.
1115 (defun delete-component (component)
1116   (declare (type component component))
1117   (aver (null (component-new-funs component)))
1118   (setf (component-kind component) :deleted)
1119   (do-blocks (block component)
1120     (setf (block-delete-p block) t))
1121   (dolist (fun (component-lambdas component))
1122     (setf (functional-kind fun) nil)
1123     (setf (functional-entry-fun fun) nil)
1124     (setf (leaf-refs fun) nil)
1125     (delete-functional fun))
1126   (do-blocks (block component)
1127     (delete-block block))
1128   (values))
1129
1130 ;;; Convert code of the form
1131 ;;;   (FOO ... (FUN ...) ...)
1132 ;;; to
1133 ;;;   (FOO ...    ...    ...).
1134 ;;; In other words, replace the function combination FUN by its
1135 ;;; arguments. If there are any problems with doing this, use GIVE-UP
1136 ;;; to blow out of whatever transform called this. Note, as the number
1137 ;;; of arguments changes, the transform must be prepared to return a
1138 ;;; lambda with a new lambda-list with the correct number of
1139 ;;; arguments.
1140 (defun extract-fun-args (cont fun num-args)
1141   #!+sb-doc
1142   "If CONT is a call to FUN with NUM-ARGS args, change those arguments
1143    to feed directly to the continuation-dest of CONT, which must be
1144    a combination."
1145   (declare (type continuation cont)
1146            (type symbol fun)
1147            (type index num-args))
1148   (let ((outside (continuation-dest cont))
1149         (inside (continuation-use cont)))
1150     (aver (combination-p outside))
1151     (unless (combination-p inside)
1152       (give-up-ir1-transform))
1153     (let ((inside-fun (combination-fun inside)))
1154       (unless (eq (continuation-fun-name inside-fun) fun)
1155         (give-up-ir1-transform))
1156       (let ((inside-args (combination-args inside)))
1157         (unless (= (length inside-args) num-args)
1158           (give-up-ir1-transform))
1159         (let* ((outside-args (combination-args outside))
1160                (arg-position (position cont outside-args))
1161                (before-args (subseq outside-args 0 arg-position))
1162                (after-args (subseq outside-args (1+ arg-position))))
1163           (dolist (arg inside-args)
1164             (setf (continuation-dest arg) outside))
1165           (setf (combination-args inside) nil)
1166           (setf (combination-args outside)
1167                 (append before-args inside-args after-args))
1168           (change-ref-leaf (continuation-use inside-fun)
1169                            (find-free-fun 'list "???"))
1170           (setf (combination-kind inside) :full)
1171           (setf (node-derived-type inside) *wild-type*)
1172           (flush-dest cont)
1173           (setf (continuation-asserted-type cont) *wild-type*)
1174           (values))))))
1175 \f
1176 ;;;; leaf hackery
1177
1178 ;;; Change the LEAF that a REF refers to.
1179 (defun change-ref-leaf (ref leaf)
1180   (declare (type ref ref) (type leaf leaf))
1181   (unless (eq (ref-leaf ref) leaf)
1182     (push ref (leaf-refs leaf))
1183     (delete-ref ref)
1184     (setf (ref-leaf ref) leaf)
1185     (let ((ltype (leaf-type leaf)))
1186       (if (fun-type-p ltype)
1187           (setf (node-derived-type ref) ltype)
1188           (derive-node-type ref ltype)))
1189     (reoptimize-continuation (node-cont ref)))
1190   (values))
1191
1192 ;;; Change all REFS for OLD-LEAF to NEW-LEAF.
1193 (defun substitute-leaf (new-leaf old-leaf)
1194   (declare (type leaf new-leaf old-leaf))
1195   (dolist (ref (leaf-refs old-leaf))
1196     (change-ref-leaf ref new-leaf))
1197   (values))
1198
1199 ;;; like SUBSITUTE-LEAF, only there is a predicate on the REF to tell
1200 ;;; whether to substitute
1201 (defun substitute-leaf-if (test new-leaf old-leaf)
1202   (declare (type leaf new-leaf old-leaf) (type function test))
1203   (dolist (ref (leaf-refs old-leaf))
1204     (when (funcall test ref)
1205       (change-ref-leaf ref new-leaf)))
1206   (values))
1207
1208 ;;; Return a LEAF which represents the specified constant object. If
1209 ;;; the object is not in *CONSTANTS*, then we create a new constant
1210 ;;; LEAF and enter it.
1211 (defun find-constant (object)
1212   (if (typep object
1213              ;; FIXME: What is the significance of this test? ("things
1214              ;; that are worth uniquifying"?)
1215              '(or symbol number character instance))
1216       (or (gethash object *constants*)
1217           (setf (gethash object *constants*)
1218                 (make-constant :value object
1219                                :%source-name '.anonymous.
1220                                :type (ctype-of object)
1221                                :where-from :defined)))
1222       (make-constant :value object
1223                      :%source-name '.anonymous.
1224                      :type (ctype-of object)
1225                      :where-from :defined)))
1226 \f
1227 ;;; If there is a non-local exit noted in ENTRY's environment that
1228 ;;; exits to CONT in that entry, then return it, otherwise return NIL.
1229 (defun find-nlx-info (entry cont)
1230   (declare (type entry entry) (type continuation cont))
1231   (let ((entry-cleanup (entry-cleanup entry)))
1232     (dolist (nlx (physenv-nlx-info (node-physenv entry)) nil)
1233       (when (and (eq (nlx-info-continuation nlx) cont)
1234                  (eq (nlx-info-cleanup nlx) entry-cleanup))
1235         (return nlx)))))
1236 \f
1237 ;;;; functional hackery
1238
1239 (declaim (ftype (function (functional) clambda) main-entry))
1240 (defun main-entry (functional)
1241   (etypecase functional
1242     (clambda functional)
1243     (optional-dispatch
1244      (optional-dispatch-main-entry functional))))
1245
1246 ;;; RETURN true if FUNCTIONAL is a thing that can be treated like
1247 ;;; MV-BIND when it appears in an MV-CALL. All fixed arguments must be
1248 ;;; optional with null default and no SUPPLIED-P. There must be a
1249 ;;; &REST arg with no references.
1250 (declaim (ftype (function (functional) boolean) looks-like-an-mv-bind))
1251 (defun looks-like-an-mv-bind (functional)
1252   (and (optional-dispatch-p functional)
1253        (do ((arg (optional-dispatch-arglist functional) (cdr arg)))
1254            ((null arg) nil)
1255          (let ((info (lambda-var-arg-info (car arg))))
1256            (unless info (return nil))
1257            (case (arg-info-kind info)
1258              (:optional
1259               (when (or (arg-info-supplied-p info) (arg-info-default info))
1260                 (return nil)))
1261              (:rest
1262               (return (and (null (cdr arg)) (null (leaf-refs (car arg))))))
1263              (t
1264               (return nil)))))))
1265
1266 ;;; Return true if function is an external entry point. This is true
1267 ;;; of normal XEPs (:EXTERNAL kind) and also of top level lambdas
1268 ;;; (:TOPLEVEL kind.)
1269 (defun xep-p (fun)
1270   (declare (type functional fun))
1271   (not (null (member (functional-kind fun) '(:external :toplevel)))))
1272
1273 ;;; If CONT's only use is a non-notinline global function reference,
1274 ;;; then return the referenced symbol, otherwise NIL. If NOTINLINE-OK
1275 ;;; is true, then we don't care if the leaf is NOTINLINE.
1276 (defun continuation-fun-name (cont &optional notinline-ok)
1277   (declare (type continuation cont))
1278   (let ((use (continuation-use cont)))
1279     (if (ref-p use)
1280         (let ((leaf (ref-leaf use)))
1281           (if (and (global-var-p leaf)
1282                    (eq (global-var-kind leaf) :global-function)
1283                    (or (not (defined-fun-p leaf))
1284                        (not (eq (defined-fun-inlinep leaf) :notinline))
1285                        notinline-ok))
1286               (leaf-source-name leaf)
1287               nil))
1288         nil)))
1289
1290 ;;; Return the COMBINATION node that is the call to the LET FUN.
1291 (defun let-combination (fun)
1292   (declare (type clambda fun))
1293   (aver (member (functional-kind fun) '(:let :mv-let)))
1294   (continuation-dest (node-cont (first (leaf-refs fun)))))
1295
1296 ;;; Return the initial value continuation for a LET variable, or NIL
1297 ;;; if there is none.
1298 (defun let-var-initial-value (var)
1299   (declare (type lambda-var var))
1300   (let ((fun (lambda-var-home var)))
1301     (elt (combination-args (let-combination fun))
1302          (position-or-lose var (lambda-vars fun)))))
1303
1304 ;;; Return the LAMBDA that is called by the local CALL.
1305 (defun combination-lambda (call)
1306   (declare (type basic-combination call))
1307   (aver (eq (basic-combination-kind call) :local))
1308   (ref-leaf (continuation-use (basic-combination-fun call))))
1309
1310 (defvar *inline-expansion-limit* 200
1311   #!+sb-doc
1312   "an upper limit on the number of inline function calls that will be expanded
1313    in any given code object (single function or block compilation)")
1314
1315 ;;; Check whether NODE's component has exceeded its inline expansion
1316 ;;; limit, and warn if so, returning NIL.
1317 (defun inline-expansion-ok (node)
1318   (let ((expanded (incf (component-inline-expansions
1319                          (block-component
1320                           (node-block node))))))
1321     (cond ((> expanded *inline-expansion-limit*) nil)
1322           ((= expanded *inline-expansion-limit*)
1323            ;; FIXME: If the objective is to stop the recursive
1324            ;; expansion of inline functions, wouldn't it be more
1325            ;; correct to look back through surrounding expansions
1326            ;; (which are, I think, stored in the *CURRENT-PATH*, and
1327            ;; possibly stored elsewhere too) and suppress expansion
1328            ;; and print this warning when the function being proposed
1329            ;; for inline expansion is found there? (I don't like the
1330            ;; arbitrary numerical limit in principle, and I think
1331            ;; it'll be a nuisance in practice if we ever want the
1332            ;; compiler to be able to use WITH-COMPILATION-UNIT on
1333            ;; arbitrarily huge blocks of code. -- WHN)
1334            (let ((*compiler-error-context* node))
1335              (compiler-note "*INLINE-EXPANSION-LIMIT* (~W) was exceeded, ~
1336                              probably trying to~%  ~
1337                              inline a recursive function."
1338                             *inline-expansion-limit*))
1339            nil)
1340           (t t))))
1341 \f
1342 ;;;; careful call
1343
1344 ;;; Apply a function to some arguments, returning a list of the values
1345 ;;; resulting of the evaluation. If an error is signalled during the
1346 ;;; application, then we print a warning message and return NIL as our
1347 ;;; second value to indicate this. Node is used as the error context
1348 ;;; for any error message, and Context is a string that is spliced
1349 ;;; into the warning.
1350 (declaim (ftype (function ((or symbol function) list node string)
1351                           (values list boolean))
1352                 careful-call))
1353 (defun careful-call (function args node context)
1354   (values
1355    (multiple-value-list
1356     (handler-case (apply function args)
1357       (error (condition)
1358         (let ((*compiler-error-context* node))
1359           (compiler-warn "Lisp error during ~A:~%~A" context condition)
1360           (return-from careful-call (values nil nil))))))
1361    t))
1362 \f
1363 ;;;; utilities used at run-time for parsing &KEY args in IR1
1364
1365 ;;; This function is used by the result of PARSE-DEFTRANSFORM to find
1366 ;;; the continuation for the value of the &KEY argument KEY in the
1367 ;;; list of continuations ARGS. It returns the continuation if the
1368 ;;; keyword is present, or NIL otherwise. The legality and
1369 ;;; constantness of the keywords should already have been checked.
1370 (declaim (ftype (function (list keyword) (or continuation null))
1371                 find-keyword-continuation))
1372 (defun find-keyword-continuation (args key)
1373   (do ((arg args (cddr arg)))
1374       ((null arg) nil)
1375     (when (eq (continuation-value (first arg)) key)
1376       (return (second arg)))))
1377
1378 ;;; This function is used by the result of PARSE-DEFTRANSFORM to
1379 ;;; verify that alternating continuations in ARGS are constant and
1380 ;;; that there is an even number of args.
1381 (declaim (ftype (function (list) boolean) check-key-args-constant))
1382 (defun check-key-args-constant (args)
1383   (do ((arg args (cddr arg)))
1384       ((null arg) t)
1385     (unless (and (rest arg)
1386                  (constant-continuation-p (first arg)))
1387       (return nil))))
1388
1389 ;;; This function is used by the result of PARSE-DEFTRANSFORM to
1390 ;;; verify that the list of continuations ARGS is a well-formed &KEY
1391 ;;; arglist and that only keywords present in the list KEYS are
1392 ;;; supplied.
1393 (declaim (ftype (function (list list) boolean) check-transform-keys))
1394 (defun check-transform-keys (args keys)
1395   (and (check-key-args-constant args)
1396        (do ((arg args (cddr arg)))
1397            ((null arg) t)
1398          (unless (member (continuation-value (first arg)) keys)
1399            (return nil)))))
1400 \f
1401 ;;;; miscellaneous
1402
1403 ;;; Called by the expansion of the EVENT macro.
1404 (declaim (ftype (function (event-info (or node null)) *) %event))
1405 (defun %event (info node)
1406   (incf (event-info-count info))
1407   (when (and (>= (event-info-level info) *event-note-threshold*)
1408              (policy (or node *lexenv*)
1409                      (= inhibit-warnings 0)))
1410     (let ((*compiler-error-context* node))
1411       (compiler-note (event-info-description info))))
1412
1413   (let ((action (event-info-action info)))
1414     (when action (funcall action node))))