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