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