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