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