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