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