da56197f27cc6e1d8cf828b01a1eb39dcd4847d3
[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 none in
18 ;;; its function. If Node has no cleanup, but is in a let, then we must still
19 ;;; check the environment that the call is in.
20 (defun node-enclosing-cleanup (node)
21   (declare (type node node))
22   (do ((lexenv (node-lexenv node)
23                (lambda-call-lexenv (lexenv-lambda lexenv))))
24       ((null lexenv) nil)
25     (let ((cup (lexenv-cleanup lexenv)))
26       (when cup (return cup)))))
27
28 ;;; Convert the FORM in a block inserted between BLOCK1 and BLOCK2 as
29 ;;; an implicit MV-PROG1. The inserted block is returned. NODE is used
30 ;;; for IR1 context when converting the form. Note that the block is
31 ;;; not assigned a number, and is linked into the DFO at the
32 ;;; beginning. We indicate that we have trashed the DFO by setting
33 ;;; COMPONENT-REANALYZE. If CLEANUP is supplied, then convert with
34 ;;; that cleanup.
35 (defun insert-cleanup-code (block1 block2 node form &optional cleanup)
36   (declare (type cblock block1 block2) (type node node)
37            (type (or cleanup null) cleanup))
38   (setf (component-reanalyze (block-component block1)) t)
39   (with-ir1-environment node
40     (let* ((start (make-continuation))
41            (block (continuation-starts-block start))
42            (cont (make-continuation))
43            (*lexenv* (if cleanup
44                          (make-lexenv :cleanup cleanup)
45                          *lexenv*)))
46       (change-block-successor block1 block2 block)
47       (link-blocks block block2)
48       (ir1-convert start cont form)
49       (setf (block-last block) (continuation-use cont))
50       block)))
51 \f
52 ;;;; continuation use hacking
53
54 ;;; Return a list of all the nodes which use Cont.
55 (declaim (ftype (function (continuation) list) find-uses))
56 (defun find-uses (cont)
57   (ecase (continuation-kind cont)
58     ((:block-start :deleted-block-start)
59      (block-start-uses (continuation-block cont)))
60     (:inside-block (list (continuation-use cont)))
61     (:unused nil)
62     (:deleted nil)))
63
64 ;;; Update continuation use information so that NODE is no longer a
65 ;;; use of its CONT. If the old continuation doesn't start its block,
66 ;;; then we don't update the BLOCK-START-USES, since it will be
67 ;;; deleted when we are done.
68 ;;;
69 ;;; Note: if you call this function, you may have to do a
70 ;;; REOPTIMIZE-CONTINUATION to inform IR1 optimization that something
71 ;;; has changed.
72 (declaim (ftype (function (node) (values)) delete-continuation-use))
73 (defun delete-continuation-use (node)
74   (let* ((cont (node-cont node))
75          (block (continuation-block cont)))
76     (ecase (continuation-kind cont)
77       (:deleted)
78       ((:block-start :deleted-block-start)
79        (let ((uses (delete node (block-start-uses block))))
80          (setf (block-start-uses block) uses)
81          (setf (continuation-use cont)
82                (if (cdr uses) nil (car uses)))))
83       (:inside-block
84        (setf (continuation-kind cont) :unused)
85        (setf (continuation-block cont) nil)
86        (setf (continuation-use cont) nil)
87        (setf (continuation-next cont) nil)))
88     (setf (node-cont node) nil))
89   (values))
90
91 ;;; Update continuation use information so that NODE uses CONT. If
92 ;;; CONT is :UNUSED, then we set its block to NODE's NODE-BLOCK (which
93 ;;; must be set.)
94 ;;;
95 ;;; Note: if you call this function, you may have to do a
96 ;;; REOPTIMIZE-CONTINUATION to inform IR1 optimization that something
97 ;;; has changed.
98 (declaim (ftype (function (node continuation) (values)) add-continuation-use))
99 (defun add-continuation-use (node cont)
100   (aver (not (node-cont node)))
101   (let ((block (continuation-block cont)))
102     (ecase (continuation-kind cont)
103       (:deleted)
104       (:unused
105        (aver (not block))
106        (let ((block (node-block node)))
107          (aver block)
108          (setf (continuation-block cont) block))
109        (setf (continuation-kind cont) :inside-block)
110        (setf (continuation-use cont) node))
111       ((:block-start :deleted-block-start)
112        (let ((uses (cons node (block-start-uses block))))
113          (setf (block-start-uses block) uses)
114          (setf (continuation-use cont)
115                (if (cdr uses) nil (car uses)))))))
116   (setf (node-cont node) cont)
117   (values))
118
119 ;;; Return true if CONT is the NODE-CONT for NODE and CONT is
120 ;;; transferred to immediately after the evaluation of NODE.
121 (defun immediately-used-p (cont node)
122   (declare (type continuation cont) (type node node))
123   (and (eq (node-cont node) cont)
124        (not (eq (continuation-kind cont) :deleted))
125        (let ((cblock (continuation-block cont))
126              (nblock (node-block node)))
127          (or (eq cblock nblock)
128              (let ((succ (block-succ nblock)))
129                (and (= (length succ) 1)
130                     (eq (first succ) cblock)))))))
131 \f
132 ;;;; continuation substitution
133
134 ;;; In OLD's DEST, replace OLD with NEW. NEW's DEST must initially be
135 ;;; NIL. When we are done, we call FLUSH-DEST on OLD to clear its DEST
136 ;;; and to note potential optimization opportunities.
137 (defun substitute-continuation (new old)
138   (declare (type continuation old new))
139   (aver (not (continuation-dest new)))
140   (let ((dest (continuation-dest old)))
141     (etypecase dest
142       ((or ref bind))
143       (cif (setf (if-test dest) new))
144       (cset (setf (set-value dest) new))
145       (creturn (setf (return-result dest) new))
146       (exit (setf (exit-value dest) new))
147       (basic-combination
148        (if (eq old (basic-combination-fun dest))
149            (setf (basic-combination-fun dest) new)
150            (setf (basic-combination-args dest)
151                  (nsubst new old (basic-combination-args dest))))))
152
153     (flush-dest old)
154     (setf (continuation-dest new) dest))
155   (values))
156
157 ;;; Replace all uses of OLD with uses of NEW, where NEW has an
158 ;;; arbitary number of uses. If NEW will end up with more than one
159 ;;; use, then we must arrange for it to start a block if it doesn't
160 ;;; already.
161 (defun substitute-continuation-uses (new old)
162   (declare (type continuation old new))
163   (unless (and (eq (continuation-kind new) :unused)
164                (eq (continuation-kind old) :inside-block))
165     (ensure-block-start new))
166
167   (do-uses (node old)
168     (delete-continuation-use node)
169     (add-continuation-use node new))
170   (dolist (lexenv-use (continuation-lexenv-uses old))
171     (setf (cadr lexenv-use) new))
172
173   (reoptimize-continuation new)
174   (values))
175 \f
176 ;;;; block starting/creation
177
178 ;;; Return the block that CONT is the start of, making a block if
179 ;;; necessary. This function is called by IR1 translators which may
180 ;;; cause a continuation to be used more than once. Every continuation
181 ;;; which may be used more than once must start a block by the time
182 ;;; that anyone does a USE-CONTINUATION on it.
183 ;;;
184 ;;; We also throw the block into the next/prev list for the
185 ;;; *CURRENT-COMPONENT* so that we keep track of which blocks we have
186 ;;; made.
187 (defun continuation-starts-block (cont)
188   (declare (type continuation cont))
189   (ecase (continuation-kind cont)
190     (:unused
191      (aver (not (continuation-block cont)))
192      (let* ((head (component-head *current-component*))
193             (next (block-next head))
194             (new-block (make-block cont)))
195        (setf (block-next new-block) next)
196        (setf (block-prev new-block) head)
197        (setf (block-prev next) new-block)
198        (setf (block-next head) new-block)
199        (setf (continuation-block cont) new-block)
200        (setf (continuation-use cont) nil)
201        (setf (continuation-kind cont) :block-start)
202        new-block))
203     (:block-start
204      (continuation-block cont))))
205
206 ;;; Ensure that Cont is the start of a block (or deleted) so that the use
207 ;;; set can be freely manipulated.
208 ;;; -- If the continuation is :Unused or is :Inside-Block and the Cont of Last
209 ;;;    in its block, then we make it the start of a new deleted block.
210 ;;; -- If the continuation is :Inside-Block inside a block, then we split the
211 ;;;    block using Node-Ends-Block, which makes the continuation be a
212 ;;;    :Block-Start.
213 (defun ensure-block-start (cont)
214   (declare (type continuation cont))
215   (let ((kind (continuation-kind cont)))
216     (ecase kind
217       ((:deleted :block-start :deleted-block-start))
218       ((:unused :inside-block)
219        (let ((block (continuation-block cont)))
220          (cond ((or (eq kind :unused)
221                     (eq (node-cont (block-last block)) cont))
222                 (setf (continuation-block cont)
223                       (make-block-key :start cont
224                                       :component nil
225                                       :start-uses (find-uses cont)))
226                 (setf (continuation-kind cont) :deleted-block-start))
227                (t
228                 (node-ends-block (continuation-use cont))))))))
229   (values))
230 \f
231 ;;;; miscellaneous shorthand functions
232
233 ;;; Return the home (i.e. enclosing non-let) lambda for Node. Since the
234 ;;; LEXENV-LAMBDA may be deleted, we must chain up the LAMBDA-CALL-LEXENV
235 ;;; thread until we find a lambda that isn't deleted, and then return its home.
236 (declaim (maybe-inline node-home-lambda))
237 (defun node-home-lambda (node)
238   (declare (type node node))
239   (do ((fun (lexenv-lambda (node-lexenv node))
240             (lexenv-lambda (lambda-call-lexenv fun))))
241       ((not (eq (functional-kind fun) :deleted))
242        (lambda-home fun))
243     (when (eq (lambda-home fun) fun)
244       (return fun))))
245
246 #!-sb-fluid (declaim (inline node-block node-tlf-number))
247 (declaim (maybe-inline node-environment))
248 (defun node-block (node)
249   (declare (type node node))
250   (the cblock (continuation-block (node-prev node))))
251 (defun node-environment (node)
252   (declare (type node node))
253   #!-sb-fluid (declare (inline node-home-lambda))
254   (the environment (lambda-environment (node-home-lambda node))))
255
256 ;;; Return the enclosing cleanup for environment of the first or last node
257 ;;; in Block.
258 (defun block-start-cleanup (block)
259   (declare (type cblock block))
260   (node-enclosing-cleanup (continuation-next (block-start block))))
261 (defun block-end-cleanup (block)
262   (declare (type cblock block))
263   (node-enclosing-cleanup (block-last block)))
264
265 ;;; Return the non-let lambda that holds Block's code.
266 (defun block-home-lambda (block)
267   (declare (type cblock block))
268   #!-sb-fluid (declare (inline node-home-lambda))
269   (node-home-lambda (block-last block)))
270
271 ;;; Return the IR1 environment for Block.
272 (defun block-environment (block)
273   (declare (type cblock block))
274   #!-sb-fluid (declare (inline node-home-lambda))
275   (lambda-environment (node-home-lambda (block-last block))))
276
277 ;;; Return the Top Level Form number of path, i.e. the ordinal number
278 ;;; of its original source's top-level form in its compilation unit.
279 (defun source-path-tlf-number (path)
280   (declare (list path))
281   (car (last path)))
282
283 ;;; Return the (reversed) list for the path in the original source
284 ;;; (with the Top Level Form number last).
285 (defun source-path-original-source (path)
286   (declare (list path) (inline member))
287   (cddr (member 'original-source-start path :test #'eq)))
288
289 ;;; Return the Form Number of Path's original source inside the Top
290 ;;; Level Form that contains it. This is determined by the order that
291 ;;; we walk the subforms of the top level source form.
292 (defun source-path-form-number (path)
293   (declare (list path) (inline member))
294   (cadr (member 'original-source-start path :test #'eq)))
295
296 ;;; Return a list of all the enclosing forms not in the original
297 ;;; source that converted to get to this form, with the immediate
298 ;;; source for node at the start of the list.
299 (defun source-path-forms (path)
300   (subseq path 0 (position 'original-source-start path)))
301
302 ;;; Return the innermost source form for Node.
303 (defun node-source-form (node)
304   (declare (type node node))
305   (let* ((path (node-source-path node))
306          (forms (source-path-forms path)))
307     (if forms
308         (first forms)
309         (values (find-original-source path)))))
310
311 ;;; Return NODE-SOURCE-FORM, T if continuation has a single use,
312 ;;; otherwise NIL, NIL.
313 (defun continuation-source (cont)
314   (let ((use (continuation-use cont)))
315     (if use
316         (values (node-source-form use) t)
317         (values nil nil))))
318 \f
319 ;;; Return a new LEXENV just like DEFAULT except for the specified
320 ;;; slot values. Values for the alist slots are NCONCed to the
321 ;;; beginning of the current value, rather than replacing it entirely.
322 (defun make-lexenv (&key (default *lexenv*)
323                          functions variables blocks tags type-restrictions
324                          options
325                          (lambda (lexenv-lambda default))
326                          (cleanup (lexenv-cleanup default))
327                          (policy (lexenv-policy default)))
328   (macrolet ((frob (var slot)
329                `(let ((old (,slot default)))
330                   (if ,var
331                       (nconc ,var old)
332                       old))))
333     (internal-make-lexenv
334      (frob functions lexenv-functions)
335      (frob variables lexenv-variables)
336      (frob blocks lexenv-blocks)
337      (frob tags lexenv-tags)
338      (frob type-restrictions lexenv-type-restrictions)
339      lambda cleanup policy 
340      (frob options lexenv-options))))
341 \f
342 ;;;; flow/DFO/component hackery
343
344 ;;; Join BLOCK1 and BLOCK2.
345 #!-sb-fluid (declaim (inline link-blocks))
346 (defun link-blocks (block1 block2)
347   (declare (type cblock block1 block2))
348   (setf (block-succ block1)
349         (if (block-succ block1)
350             (%link-blocks block1 block2)
351             (list block2)))
352   (push block1 (block-pred block2))
353   (values))
354 (defun %link-blocks (block1 block2)
355   (declare (type cblock block1 block2) (inline member))
356   (let ((succ1 (block-succ block1)))
357     (aver (not (member block2 succ1 :test #'eq)))
358     (cons block2 succ1)))
359
360 ;;; Like LINK-BLOCKS, but we separate BLOCK1 and BLOCK2. If this leaves a
361 ;;; successor with a single predecessor that ends in an IF, then set
362 ;;; BLOCK-TEST-MODIFIED so that any test constraint will now be able to be
363 ;;; propagated to the successor.
364 (defun unlink-blocks (block1 block2)
365   (declare (type cblock block1 block2))
366   (let ((succ1 (block-succ block1)))
367     (if (eq block2 (car succ1))
368         (setf (block-succ block1) (cdr succ1))
369         (do ((succ (cdr succ1) (cdr succ))
370              (prev succ1 succ))
371             ((eq (car succ) block2)
372              (setf (cdr prev) (cdr succ)))
373           (aver succ))))
374
375   (let ((new-pred (delq block1 (block-pred block2))))
376     (setf (block-pred block2) new-pred)
377     (when (and new-pred (null (rest new-pred)))
378       (let ((pred-block (first new-pred)))
379         (when (if-p (block-last pred-block))
380           (setf (block-test-modified pred-block) t)))))
381   (values))
382
383 ;;; Swing the succ/pred link between Block and Old to be between Block and
384 ;;; New. If Block ends in an IF, then we have to fix up the
385 ;;; consequent/alternative blocks to point to New. We also set
386 ;;; BLOCK-TEST-MODIFIED so that any test constraint will be applied to the new
387 ;;; successor.
388 (defun change-block-successor (block old new)
389   (declare (type cblock new old block) (inline member))
390   (unlink-blocks block old)
391   (let ((last (block-last block))
392         (comp (block-component block)))
393     (setf (component-reanalyze comp) t)
394     (typecase last
395       (cif
396        (setf (block-test-modified block) t)
397        (let* ((succ-left (block-succ block))
398               (new (if (and (eq new (component-tail comp))
399                             succ-left)
400                        (first succ-left)
401                        new)))
402          (unless (member new succ-left :test #'eq)
403            (link-blocks block new))
404          (macrolet ((frob (slot)
405                       `(when (eq (,slot last) old)
406                          (setf (,slot last) new))))
407            (frob if-consequent)
408            (frob if-alternative))))
409       (t
410        (unless (member new (block-succ block) :test #'eq)
411          (link-blocks block new)))))
412
413   (values))
414
415 ;;; Unlink a block from the next/prev chain. We also null out the
416 ;;; Component.
417 (declaim (ftype (function (cblock) (values)) remove-from-dfo))
418 #!-sb-fluid (declaim (inline remove-from-dfo))
419 (defun remove-from-dfo (block)
420   (let ((next (block-next block))
421         (prev (block-prev block)))
422     (setf (block-component block) nil)
423     (setf (block-next prev) next)
424     (setf (block-prev next) prev))
425   (values))
426
427 ;;; Add Block to the next/prev chain following After. We also set the
428 ;;; Component to be the same as for After.
429 #!-sb-fluid (declaim (inline add-to-dfo))
430 (defun add-to-dfo (block after)
431   (declare (type cblock block after))
432   (let ((next (block-next after))
433         (comp (block-component after)))
434     (aver (not (eq (component-kind comp) :deleted)))
435     (setf (block-component block) comp)
436     (setf (block-next after) block)
437     (setf (block-prev block) after)
438     (setf (block-next block) next)
439     (setf (block-prev next) block))
440   (values))
441
442 ;;; Set the Flag for all the blocks in Component to NIL, except for the head
443 ;;; and tail which are set to T.
444 (declaim (ftype (function (component) (values)) clear-flags))
445 (defun clear-flags (component)
446   (let ((head (component-head component))
447         (tail (component-tail component)))
448     (setf (block-flag head) t)
449     (setf (block-flag tail) t)
450     (do-blocks (block component)
451       (setf (block-flag block) nil)))
452   (values))
453
454 ;;; Make a component with no blocks in it. The Block-Flag is initially
455 ;;; true in the head and tail blocks.
456 (declaim (ftype (function nil component) make-empty-component))
457 (defun make-empty-component ()
458   (let* ((head (make-block-key :start nil :component nil))
459          (tail (make-block-key :start nil :component nil))
460          (res (make-component :head head :tail tail)))
461     (setf (block-flag head) t)
462     (setf (block-flag tail) t)
463     (setf (block-component head) res)
464     (setf (block-component tail) res)
465     (setf (block-next head) tail)
466     (setf (block-prev tail) head)
467     res))
468
469 ;;; Makes Node the Last node in its block, splitting the block if necessary.
470 ;;; The new block is added to the DFO immediately following Node's block.
471 (defun node-ends-block (node)
472   (declare (type node node))
473   (let* ((block (node-block node))
474          (start (node-cont node))
475          (last (block-last block))
476          (last-cont (node-cont last)))
477     (unless (eq last node)
478       (aver (and (eq (continuation-kind start) :inside-block)
479                    (not (block-delete-p block))))
480       (let* ((succ (block-succ block))
481              (new-block
482               (make-block-key :start start
483                               :component (block-component block)
484                               :start-uses (list (continuation-use start))
485                               :succ succ :last last)))
486         (setf (continuation-kind start) :block-start)
487         (dolist (b succ)
488           (setf (block-pred b)
489                 (cons new-block (remove block (block-pred b)))))
490         (setf (block-succ block) ())
491         (setf (block-last block) node)
492         (link-blocks block new-block)
493         (add-to-dfo new-block block)
494         (setf (component-reanalyze (block-component block)) t)
495         
496         (do ((cont start (node-cont (continuation-next cont))))
497             ((eq cont last-cont)
498              (when (eq (continuation-kind last-cont) :inside-block)
499                (setf (continuation-block last-cont) new-block)))
500           (setf (continuation-block cont) new-block))
501
502         (setf (block-type-asserted block) t)
503         (setf (block-test-modified block) t))))
504
505   (values))
506 \f
507 ;;;; deleting stuff
508
509 ;;; Deal with deleting the last (read) reference to a lambda-var. We
510 ;;; iterate over all local calls flushing the corresponding argument, allowing
511 ;;; the computation of the argument to be deleted. We also mark the let for
512 ;;; reoptimization, since it may be that we have deleted the last variable.
513 ;;;
514 ;;; The lambda-var may still have some sets, but this doesn't cause too much
515 ;;; difficulty, since we can efficiently implement write-only variables. We
516 ;;; iterate over the sets, marking their blocks for dead code flushing, since
517 ;;; we can delete sets whose value is unused.
518 (defun delete-lambda-var (leaf)
519   (declare (type lambda-var leaf))
520   (let* ((fun (lambda-var-home leaf))
521          (n (position leaf (lambda-vars fun))))
522     (dolist (ref (leaf-refs fun))
523       (let* ((cont (node-cont ref))
524              (dest (continuation-dest cont)))
525         (when (and (combination-p dest)
526                    (eq (basic-combination-fun dest) cont)
527                    (eq (basic-combination-kind dest) :local))
528           (let* ((args (basic-combination-args dest))
529                  (arg (elt args n)))
530             (reoptimize-continuation arg)
531             (flush-dest arg)
532             (setf (elt args n) nil))))))
533
534   (dolist (set (lambda-var-sets leaf))
535     (setf (block-flush-p (node-block set)) t))
536
537   (values))
538
539 ;;; Note that something interesting has happened to Var. We only deal with
540 ;;; LET variables, marking the corresponding initial value arg as needing to be
541 ;;; reoptimized.
542 (defun reoptimize-lambda-var (var)
543   (declare (type lambda-var var))
544   (let ((fun (lambda-var-home var)))
545     (when (and (eq (functional-kind fun) :let)
546                (leaf-refs var))
547       (do ((args (basic-combination-args
548                   (continuation-dest
549                    (node-cont
550                     (first (leaf-refs fun)))))
551                  (cdr args))
552            (vars (lambda-vars fun) (cdr vars)))
553           ((eq (car vars) var)
554            (reoptimize-continuation (car args))))))
555   (values))
556
557 ;;; This function deletes functions that have no references. This need only
558 ;;; be called on functions that never had any references, since otherwise
559 ;;; DELETE-REF will handle the deletion.
560 (defun delete-functional (fun)
561   (aver (and (null (leaf-refs fun))
562              (not (functional-entry-function fun))))
563   (etypecase fun
564     (optional-dispatch (delete-optional-dispatch fun))
565     (clambda (delete-lambda fun)))
566   (values))
567
568 ;;; Deal with deleting the last reference to a lambda. Since there is only
569 ;;; one way into a lambda, deleting the last reference to a lambda ensures that
570 ;;; there is no way to reach any of the code in it. So we just set the
571 ;;; Functional-Kind for Fun and its Lets to :Deleted, causing IR1 optimization
572 ;;; to delete blocks in that lambda.
573 ;;;
574 ;;; If the function isn't a Let, we unlink the function head and tail from
575 ;;; the component head and tail to indicate that the code is unreachable. We
576 ;;; also delete the function from Component-Lambdas (it won't be there before
577 ;;; local call analysis, but no matter.)  If the lambda was never referenced,
578 ;;; we give a note.
579 ;;;
580 ;;; If the lambda is an XEP, then we null out the Entry-Function in its
581 ;;; Entry-Function so that people will know that it is not an entry point
582 ;;; anymore.
583 (defun delete-lambda (leaf)
584   (declare (type clambda leaf))
585   (let ((kind (functional-kind leaf))
586         (bind (lambda-bind leaf)))
587     (aver (not (member kind '(:deleted :optional :top-level))))
588     (setf (functional-kind leaf) :deleted)
589     (setf (lambda-bind leaf) nil)
590     (dolist (let (lambda-lets leaf))
591       (setf (lambda-bind let) nil)
592       (setf (functional-kind let) :deleted))
593
594     (if (member kind '(:let :mv-let :assignment))
595         (let ((home (lambda-home leaf)))
596           (setf (lambda-lets home) (delete leaf (lambda-lets home))))
597         (let* ((bind-block (node-block bind))
598                (component (block-component bind-block))
599                (return (lambda-return leaf)))
600           (aver (null (leaf-refs leaf)))
601           (unless (leaf-ever-used leaf)
602             (let ((*compiler-error-context* bind))
603               (compiler-note "deleting unused function~:[.~;~:*~%  ~S~]"
604                              (leaf-name leaf))))
605           (unlink-blocks (component-head component) bind-block)
606           (when return
607             (unlink-blocks (node-block return) (component-tail component)))
608           (setf (component-reanalyze component) t)
609           (let ((tails (lambda-tail-set leaf)))
610             (setf (tail-set-functions tails)
611                   (delete leaf (tail-set-functions tails)))
612             (setf (lambda-tail-set leaf) nil))
613           (setf (component-lambdas component)
614                 (delete leaf (component-lambdas component)))))
615
616     (when (eq kind :external)
617       (let ((fun (functional-entry-function leaf)))
618         (setf (functional-entry-function fun) nil)
619         (when (optional-dispatch-p fun)
620           (delete-optional-dispatch fun)))))
621
622   (values))
623
624 ;;; Deal with deleting the last reference to an Optional-Dispatch. We have
625 ;;; to be a bit more careful than with lambdas, since Delete-Ref is used both
626 ;;; before and after local call analysis. Afterward, all references to
627 ;;; still-existing optional-dispatches have been moved to the XEP, leaving it
628 ;;; with no references at all. So we look at the XEP to see whether an
629 ;;; optional-dispatch is still really being used. But before local call
630 ;;; analysis, there are no XEPs, and all references are direct.
631 ;;;
632 ;;; When we do delete the optional-dispatch, we grovel all of its
633 ;;; entry-points, making them be normal lambdas, and then deleting the ones
634 ;;; with no references. This deletes any e-p lambdas that were either never
635 ;;; referenced, or couldn't be deleted when the last deference was deleted (due
636 ;;; to their :OPTIONAL kind.)
637 ;;;
638 ;;; Note that the last optional ep may alias the main entry, so when we process
639 ;;; the main entry, its kind may have been changed to NIL or even converted to
640 ;;; a let.
641 (defun delete-optional-dispatch (leaf)
642   (declare (type optional-dispatch leaf))
643   (let ((entry (functional-entry-function leaf)))
644     (unless (and entry (leaf-refs entry))
645       (aver (or (not entry) (eq (functional-kind entry) :deleted)))
646       (setf (functional-kind leaf) :deleted)
647
648       (flet ((frob (fun)
649                (unless (eq (functional-kind fun) :deleted)
650                  (aver (eq (functional-kind fun) :optional))
651                  (setf (functional-kind fun) nil)
652                  (let ((refs (leaf-refs fun)))
653                    (cond ((null refs)
654                           (delete-lambda fun))
655                          ((null (rest refs))
656                           (or (maybe-let-convert fun)
657                               (maybe-convert-to-assignment fun)))
658                          (t
659                           (maybe-convert-to-assignment fun)))))))
660         
661         (dolist (ep (optional-dispatch-entry-points leaf))
662           (frob ep))
663         (when (optional-dispatch-more-entry leaf)
664           (frob (optional-dispatch-more-entry leaf)))
665         (let ((main (optional-dispatch-main-entry leaf)))
666           (when (eq (functional-kind main) :optional)
667             (frob main))))))
668
669   (values))
670
671 ;;; Do stuff to delete the semantic attachments of a Ref node. When this
672 ;;; leaves zero or one reference, we do a type dispatch off of the leaf to
673 ;;; determine if a special action is appropriate.
674 (defun delete-ref (ref)
675   (declare (type ref ref))
676   (let* ((leaf (ref-leaf ref))
677          (refs (delete ref (leaf-refs leaf))))
678     (setf (leaf-refs leaf) refs)
679
680     (cond ((null refs)
681            (typecase leaf
682              (lambda-var (delete-lambda-var leaf))
683              (clambda
684               (ecase (functional-kind leaf)
685                 ((nil :let :mv-let :assignment :escape :cleanup)
686                  (aver (not (functional-entry-function leaf)))
687                  (delete-lambda leaf))
688                 (:external
689                  (delete-lambda leaf))
690                 ((:deleted :optional))))
691              (optional-dispatch
692               (unless (eq (functional-kind leaf) :deleted)
693                 (delete-optional-dispatch leaf)))))
694           ((null (rest refs))
695            (typecase leaf
696              (clambda (or (maybe-let-convert leaf)
697                           (maybe-convert-to-assignment leaf)))
698              (lambda-var (reoptimize-lambda-var leaf))))
699           (t
700            (typecase leaf
701              (clambda (maybe-convert-to-assignment leaf))))))
702
703   (values))
704
705 ;;; This function is called by people who delete nodes; it provides a way to
706 ;;; indicate that the value of a continuation is no longer used. We null out
707 ;;; the Continuation-Dest, set Flush-P in the blocks containing uses of Cont
708 ;;; and set Component-Reoptimize. If the Prev of the use is deleted, then we
709 ;;; blow off reoptimization.
710 ;;;
711 ;;; If the continuation is :Deleted, then we don't do anything, since all
712 ;;; semantics have already been flushed. :Deleted-Block-Start start
713 ;;; continuations are treated just like :Block-Start; it is possible that the
714 ;;; continuation may be given a new dest (e.g. by SUBSTITUTE-CONTINUATION), so
715 ;;; we don't want to delete it.
716 (defun flush-dest (cont)
717   (declare (type continuation cont))
718
719   (unless (eq (continuation-kind cont) :deleted)
720     (aver (continuation-dest cont))
721     (setf (continuation-dest cont) nil)
722     (do-uses (use cont)
723       (let ((prev (node-prev use)))
724         (unless (eq (continuation-kind prev) :deleted)
725           (let ((block (continuation-block prev)))
726             (setf (component-reoptimize (block-component block)) t)
727             (setf (block-attributep (block-flags block) flush-p type-asserted)
728                   t))))))
729
730   (setf (continuation-%type-check cont) nil)
731
732   (values))
733
734 ;;; Do a graph walk backward from Block, marking all predecessor blocks with
735 ;;; the DELETE-P flag.
736 (defun mark-for-deletion (block)
737   (declare (type cblock block))
738   (unless (block-delete-p block)
739     (setf (block-delete-p block) t)
740     (setf (component-reanalyze (block-component block)) t)
741     (dolist (pred (block-pred block))
742       (mark-for-deletion pred)))
743   (values))
744
745 ;;;    Delete Cont, eliminating both control and value semantics. We set
746 ;;; FLUSH-P and COMPONENT-REOPTIMIZE similarly to in FLUSH-DEST. Here we must
747 ;;; get the component from the use block, since the continuation may be a
748 ;;; :DELETED-BLOCK-START.
749 ;;;
750 ;;;    If Cont has DEST, then it must be the case that the DEST is unreachable,
751 ;;; since we can't compute the value desired. In this case, we call
752 ;;; MARK-FOR-DELETION to cause the DEST block and its predecessors to tell
753 ;;; people to ignore them, and to cause them to be deleted eventually.
754 (defun delete-continuation (cont)
755   (declare (type continuation cont))
756   (aver (not (eq (continuation-kind cont) :deleted)))
757
758   (do-uses (use cont)
759     (let ((prev (node-prev use)))
760       (unless (eq (continuation-kind prev) :deleted)
761         (let ((block (continuation-block prev)))
762           (setf (block-attributep (block-flags block) flush-p type-asserted) t)
763           (setf (component-reoptimize (block-component block)) t)))))
764
765   (let ((dest (continuation-dest cont)))
766     (when dest
767       (let ((prev (node-prev dest)))
768         (when (and prev
769                    (not (eq (continuation-kind prev) :deleted)))
770           (let ((block (continuation-block prev)))
771             (unless (block-delete-p block)
772               (mark-for-deletion block)))))))
773
774   (setf (continuation-kind cont) :deleted)
775   (setf (continuation-dest cont) nil)
776   (setf (continuation-next cont) nil)
777   (setf (continuation-asserted-type cont) *empty-type*)
778   (setf (continuation-%derived-type cont) *empty-type*)
779   (setf (continuation-use cont) nil)
780   (setf (continuation-block cont) nil)
781   (setf (continuation-reoptimize cont) nil)
782   (setf (continuation-%type-check cont) nil)
783   (setf (continuation-info cont) nil)
784
785   (values))
786
787 ;;; This function does what is necessary to eliminate the code in it
788 ;;; from the IR1 representation. This involves unlinking it from its
789 ;;; predecessors and successors and deleting various node-specific
790 ;;; semantic information.
791 ;;;
792 ;;; We mark the START as has having no next and remove the last node
793 ;;; from its CONT's uses. We also flush the DEST for all continuations
794 ;;; whose values are received by nodes in the block.
795 (defun delete-block (block)
796   (declare (type cblock block))
797   (aver (block-component block)) ; else block is already deleted!
798   (note-block-deletion block)
799   (setf (block-delete-p block) t)
800
801   (let* ((last (block-last block))
802          (cont (node-cont last)))
803     (delete-continuation-use last)
804     (if (eq (continuation-kind cont) :unused)
805         (delete-continuation cont)
806         (reoptimize-continuation cont)))
807
808   (dolist (b (block-pred block))
809     (unlink-blocks b block))
810   (dolist (b (block-succ block))
811     (unlink-blocks block b))
812
813   (do-nodes (node cont block)
814     (typecase node
815       (ref (delete-ref node))
816       (cif
817        (flush-dest (if-test node)))
818       ;; The next two cases serve to maintain the invariant that a LET always
819       ;; has a well-formed COMBINATION, REF and BIND. We delete the lambda
820       ;; whenever we delete any of these, but we must be careful that this LET
821       ;; has not already been partially deleted.
822       (basic-combination
823        (when (and (eq (basic-combination-kind node) :local)
824                   ;; Guards COMBINATION-LAMBDA agains the REF being deleted.
825                   (continuation-use (basic-combination-fun node)))
826          (let ((fun (combination-lambda node)))
827            ;; If our REF was the 2'nd to last ref, and has been deleted, then
828            ;; Fun may be a LET for some other combination.
829            (when (and (member (functional-kind fun) '(:let :mv-let))
830                       (eq (let-combination fun) node))
831              (delete-lambda fun))))
832        (flush-dest (basic-combination-fun node))
833        (dolist (arg (basic-combination-args node))
834          (when arg (flush-dest arg))))
835       (bind
836        (let ((lambda (bind-lambda node)))
837          (unless (eq (functional-kind lambda) :deleted)
838            (aver (member (functional-kind lambda) '(:let :mv-let :assignment)))
839            (delete-lambda lambda))))
840       (exit
841        (let ((value (exit-value node))
842              (entry (exit-entry node)))
843          (when value
844            (flush-dest value))
845          (when entry
846            (setf (entry-exits entry)
847                  (delete node (entry-exits entry))))))
848       (creturn
849        (flush-dest (return-result node))
850        (delete-return node))
851       (cset
852        (flush-dest (set-value node))
853        (let ((var (set-var node)))
854          (setf (basic-var-sets var)
855                (delete node (basic-var-sets var))))))
856
857     (delete-continuation (node-prev node)))
858
859   (remove-from-dfo block)
860   (values))
861
862 ;;; Do stuff to indicate that the return node Node is being deleted. We set
863 ;;; the RETURN to NIL.
864 (defun delete-return (node)
865   (declare (type creturn node))
866   (let ((fun (return-lambda node)))
867     (aver (lambda-return fun))
868     (setf (lambda-return fun) nil))
869   (values))
870
871 ;;; If any of the Vars in fun were never referenced and was not declared
872 ;;; IGNORE, then complain.
873 (defun note-unreferenced-vars (fun)
874   (declare (type clambda fun))
875   (dolist (var (lambda-vars fun))
876     (unless (or (leaf-ever-used var)
877                 (lambda-var-ignorep var))
878       (let ((*compiler-error-context* (lambda-bind fun)))
879         (unless (policy *compiler-error-context* (= inhibit-warnings 3))
880           ;; ANSI section "3.2.5 Exceptional Situations in the Compiler"
881           ;; requires this to be a STYLE-WARNING.
882           (compiler-style-warning "The variable ~S is defined but never used."
883                                   (leaf-name var)))
884         (setf (leaf-ever-used var) t))))
885   (values))
886
887 (defvar *deletion-ignored-objects* '(t nil))
888
889 ;;; Return true if we can find Obj in Form, NIL otherwise. We bound our
890 ;;; recursion so that we don't get lost in circular structures. We ignore the
891 ;;; car of forms if they are a symbol (to prevent confusing function
892 ;;; referencess with variables), and we also ignore anything inside ' or #'.
893 (defun present-in-form (obj form depth)
894   (declare (type (integer 0 20) depth))
895   (cond ((= depth 20) nil)
896         ((eq obj form) t)
897         ((atom form) nil)
898         (t
899          (let ((first (car form))
900                (depth (1+ depth)))
901            (if (member first '(quote function))
902                nil
903                (or (and (not (symbolp first))
904                         (present-in-form obj first depth))
905                    (do ((l (cdr form) (cdr l))
906                         (n 0 (1+ n)))
907                        ((or (atom l) (> n 100))
908                         nil)
909                      (declare (fixnum n))
910                      (when (present-in-form obj (car l) depth)
911                        (return t)))))))))
912
913 ;;; This function is called on a block immediately before we delete it. We
914 ;;; check to see whether any of the code about to die appeared in the original
915 ;;; source, and emit a note if so.
916 ;;;
917 ;;; If the block was in a lambda is now deleted, then we ignore the whole
918 ;;; block, since this case is picked off in DELETE-LAMBDA. We also ignore
919 ;;; the deletion of CRETURN nodes, since it is somewhat reasonable for a
920 ;;; function to not return, and there is a different note for that case anyway.
921 ;;;
922 ;;; If the actual source is an atom, then we use a bunch of heuristics to
923 ;;; guess whether this reference really appeared in the original source:
924 ;;; -- If a symbol, it must be interned and not a keyword.
925 ;;; -- It must not be an easily introduced constant (T or NIL, a fixnum or a
926 ;;;    character.)
927 ;;; -- The atom must be "present" in the original source form, and present in
928 ;;;    all intervening actual source forms.
929 (defun note-block-deletion (block)
930   (let ((home (block-home-lambda block)))
931     (unless (eq (functional-kind home) :deleted)
932       (do-nodes (node cont block)
933         (let* ((path (node-source-path node))
934                (first (first path)))
935           (when (or (eq first 'original-source-start)
936                     (and (atom first)
937                          (or (not (symbolp first))
938                              (let ((pkg (symbol-package first)))
939                                (and pkg
940                                     (not (eq pkg (symbol-package :end))))))
941                          (not (member first *deletion-ignored-objects*))
942                          (not (typep first '(or fixnum character)))
943                          (every #'(lambda (x)
944                                     (present-in-form first x 0))
945                                 (source-path-forms path))
946                          (present-in-form first (find-original-source path)
947                                           0)))
948             (unless (return-p node)
949               (let ((*compiler-error-context* node))
950                 (compiler-note "deleting unreachable code")))
951             (return))))))
952   (values))
953
954 ;;; Delete a node from a block, deleting the block if there are no nodes
955 ;;; left. We remove the node from the uses of its CONT, but we don't deal with
956 ;;; cleaning up any type-specific semantic attachments. If the CONT is :UNUSED
957 ;;; after deleting this use, then we delete CONT. (Note :UNUSED is not the
958 ;;; same as no uses. A continuation will only become :UNUSED if it was
959 ;;; :INSIDE-BLOCK before.)
960 ;;;
961 ;;; If the node is the last node, there must be exactly one successor. We
962 ;;; link all of our precedessors to the successor and unlink the block. In
963 ;;; this case, we return T, otherwise NIL. If no nodes are left, and the block
964 ;;; is a successor of itself, then we replace the only node with a degenerate
965 ;;; exit node. This provides a way to represent the bodyless infinite loop,
966 ;;; given the prohibition on empty blocks in IR1.
967 (defun unlink-node (node)
968   (declare (type node node))
969   (let* ((cont (node-cont node))
970          (next (continuation-next cont))
971          (prev (node-prev node))
972          (block (continuation-block prev))
973          (prev-kind (continuation-kind prev))
974          (last (block-last block)))
975
976     (unless (eq (continuation-kind cont) :deleted)
977       (delete-continuation-use node)
978       (when (eq (continuation-kind cont) :unused)
979         (aver (not (continuation-dest cont)))
980         (delete-continuation cont)))
981
982     (setf (block-type-asserted block) t)
983     (setf (block-test-modified block) t)
984
985     (cond ((or (eq prev-kind :inside-block)
986                (and (eq prev-kind :block-start)
987                     (not (eq node last))))
988            (cond ((eq node last)
989                   (setf (block-last block) (continuation-use prev))
990                   (setf (continuation-next prev) nil))
991                  (t
992                   (setf (continuation-next prev) next)
993                   (setf (node-prev next) prev)))
994            (setf (node-prev node) nil)
995            nil)
996           (t
997            (aver (eq prev-kind :block-start))
998            (aver (eq node last))
999            (let* ((succ (block-succ block))
1000                   (next (first succ)))
1001              (aver (and succ (null (cdr succ))))
1002              (cond
1003               ((member block succ)
1004                (with-ir1-environment node
1005                  (let ((exit (make-exit))
1006                        (dummy (make-continuation)))
1007                    (setf (continuation-next prev) nil)
1008                    (prev-link exit prev)
1009                    (add-continuation-use exit dummy)
1010                    (setf (block-last block) exit)))
1011                (setf (node-prev node) nil)
1012                nil)
1013               (t
1014                (aver (eq (block-start-cleanup block)
1015                          (block-end-cleanup block)))
1016                (unlink-blocks block next)
1017                (dolist (pred (block-pred block))
1018                  (change-block-successor pred block next))
1019                (remove-from-dfo block)
1020                (cond ((continuation-dest prev)
1021                       (setf (continuation-next prev) nil)
1022                       (setf (continuation-kind prev) :deleted-block-start))
1023                      (t
1024                       (delete-continuation prev)))
1025                (setf (node-prev node) nil)
1026                t)))))))
1027
1028 ;;; Return true if NODE has been deleted, false if it is still a valid part
1029 ;;; of IR1.
1030 (defun node-deleted (node)
1031   (declare (type node node))
1032   (let ((prev (node-prev node)))
1033     (not (and prev
1034               (not (eq (continuation-kind prev) :deleted))
1035               (let ((block (continuation-block prev)))
1036                 (and (block-component block)
1037                      (not (block-delete-p block))))))))
1038
1039 ;;; Delete all the blocks and functions in Component. We scan first marking
1040 ;;; the blocks as delete-p to prevent weird stuff from being triggered by
1041 ;;; deletion.
1042 (defun delete-component (component)
1043   (declare (type component component))
1044   (aver (null (component-new-functions component)))
1045   (setf (component-kind component) :deleted)
1046   (do-blocks (block component)
1047     (setf (block-delete-p block) t))
1048   (dolist (fun (component-lambdas component))
1049     (setf (functional-kind fun) nil)
1050     (setf (functional-entry-function fun) nil)
1051     (setf (leaf-refs fun) nil)
1052     (delete-functional fun))
1053   (do-blocks (block component)
1054     (delete-block block))
1055   (values))
1056
1057 ;;; Convert code of the form
1058 ;;;   (FOO ... (FUN ...) ...)
1059 ;;; to
1060 ;;;   (FOO ...    ...    ...).
1061 ;;; In other words, replace the function combination FUN by its
1062 ;;; arguments. If there are any problems with doing this, use GIVE-UP
1063 ;;; to blow out of whatever transform called this. Note, as the number
1064 ;;; of arguments changes, the transform must be prepared to return a
1065 ;;; lambda with a new lambda-list with the correct number of
1066 ;;; arguments.
1067 (defun extract-function-args (cont fun num-args)
1068   #!+sb-doc
1069   "If CONT is a call to FUN with NUM-ARGS args, change those arguments
1070    to feed directly to the continuation-dest of CONT, which must be
1071    a combination."
1072   (declare (type continuation cont)
1073            (type symbol fun)
1074            (type index num-args))
1075   (let ((outside (continuation-dest cont))
1076         (inside (continuation-use cont)))
1077     (aver (combination-p outside))
1078     (unless (combination-p inside)
1079       (give-up-ir1-transform))
1080     (let ((inside-fun (combination-fun inside)))
1081       (unless (eq (continuation-function-name inside-fun) fun)
1082         (give-up-ir1-transform))
1083       (let ((inside-args (combination-args inside)))
1084         (unless (= (length inside-args) num-args)
1085           (give-up-ir1-transform))
1086         (let* ((outside-args (combination-args outside))
1087                (arg-position (position cont outside-args))
1088                (before-args (subseq outside-args 0 arg-position))
1089                (after-args (subseq outside-args (1+ arg-position))))
1090           (dolist (arg inside-args)
1091             (setf (continuation-dest arg) outside))
1092           (setf (combination-args inside) nil)
1093           (setf (combination-args outside)
1094                 (append before-args inside-args after-args))
1095           (change-ref-leaf (continuation-use inside-fun)
1096                            (find-free-function 'list "???"))
1097           (setf (combination-kind inside) :full)
1098           (setf (node-derived-type inside) *wild-type*)
1099           (flush-dest cont)
1100           (setf (continuation-asserted-type cont) *wild-type*)
1101           (values))))))
1102 \f
1103 ;;;; leaf hackery
1104
1105 ;;; Change the Leaf that a Ref refers to.
1106 (defun change-ref-leaf (ref leaf)
1107   (declare (type ref ref) (type leaf leaf))
1108   (unless (eq (ref-leaf ref) leaf)
1109     (push ref (leaf-refs leaf))
1110     (delete-ref ref)
1111     (setf (ref-leaf ref) leaf)
1112     (let ((ltype (leaf-type leaf)))
1113       (if (function-type-p ltype)
1114           (setf (node-derived-type ref) ltype)
1115           (derive-node-type ref ltype)))
1116     (reoptimize-continuation (node-cont ref)))
1117   (values))
1118
1119 ;;; Change all Refs for Old-Leaf to New-Leaf.
1120 (defun substitute-leaf (new-leaf old-leaf)
1121   (declare (type leaf new-leaf old-leaf))
1122   (dolist (ref (leaf-refs old-leaf))
1123     (change-ref-leaf ref new-leaf))
1124   (values))
1125
1126 ;;; Like SUBSITIUTE-LEAF, only there is a predicate on the Ref to tell
1127 ;;; whether to substitute.
1128 (defun substitute-leaf-if (test new-leaf old-leaf)
1129   (declare (type leaf new-leaf old-leaf) (type function test))
1130   (dolist (ref (leaf-refs old-leaf))
1131     (when (funcall test ref)
1132       (change-ref-leaf ref new-leaf)))
1133   (values))
1134
1135 ;;; Return a LEAF which represents the specified constant object. If the
1136 ;;; object is not in *CONSTANTS*, then we create a new constant LEAF and
1137 ;;; enter it.
1138 #!-sb-fluid (declaim (maybe-inline find-constant))
1139 (defun find-constant (object)
1140   (if (typep object '(or symbol number character instance))
1141     (or (gethash object *constants*)
1142         (setf (gethash object *constants*)
1143               (make-constant :value object
1144                              :name nil
1145                              :type (ctype-of object)
1146                              :where-from :defined)))
1147     (make-constant :value object
1148                    :name nil
1149                    :type (ctype-of object)
1150                    :where-from :defined)))
1151 \f
1152 ;;; If there is a non-local exit noted in Entry's environment that exits to
1153 ;;; Cont in that entry, then return it, otherwise return NIL.
1154 (defun find-nlx-info (entry cont)
1155   (declare (type entry entry) (type continuation cont))
1156   (let ((entry-cleanup (entry-cleanup entry)))
1157     (dolist (nlx (environment-nlx-info (node-environment entry)) nil)
1158       (when (and (eq (nlx-info-continuation nlx) cont)
1159                  (eq (nlx-info-cleanup nlx) entry-cleanup))
1160         (return nlx)))))
1161 \f
1162 ;;;; functional hackery
1163
1164 ;;; If Functional is a Lambda, just return it; if it is an
1165 ;;; optional-dispatch, return the main-entry.
1166 (declaim (ftype (function (functional) clambda) main-entry))
1167 (defun main-entry (functional)
1168   (etypecase functional
1169     (clambda functional)
1170     (optional-dispatch
1171      (optional-dispatch-main-entry functional))))
1172
1173 ;;; Returns true if Functional is a thing that can be treated like
1174 ;;; MV-Bind when it appears in an MV-Call. All fixed arguments must be
1175 ;;; optional with null default and no supplied-p. There must be a rest
1176 ;;; arg with no references.
1177 (declaim (ftype (function (functional) boolean) looks-like-an-mv-bind))
1178 (defun looks-like-an-mv-bind (functional)
1179   (and (optional-dispatch-p functional)
1180        (do ((arg (optional-dispatch-arglist functional) (cdr arg)))
1181            ((null arg) nil)
1182          (let ((info (lambda-var-arg-info (car arg))))
1183            (unless info (return nil))
1184            (case (arg-info-kind info)
1185              (:optional
1186               (when (or (arg-info-supplied-p info) (arg-info-default info))
1187                 (return nil)))
1188              (:rest
1189               (return (and (null (cdr arg)) (null (leaf-refs (car arg))))))
1190              (t
1191               (return nil)))))))
1192
1193 ;;; Return true if function is an XEP. This is true of normal XEPs
1194 ;;; (:External kind) and top-level lambdas (:Top-Level kind.)
1195 #!-sb-fluid (declaim (inline external-entry-point-p))
1196 (defun external-entry-point-p (fun)
1197   (declare (type functional fun))
1198   (not (null (member (functional-kind fun) '(:external :top-level)))))
1199
1200 ;;; If Cont's only use is a non-notinline global function reference, then
1201 ;;; return the referenced symbol, otherwise NIL. If Notinline-OK is true, then
1202 ;;; we don't care if the leaf is notinline.
1203 (defun continuation-function-name (cont &optional notinline-ok)
1204   (declare (type continuation cont))
1205   (let ((use (continuation-use cont)))
1206     (if (ref-p use)
1207         (let ((leaf (ref-leaf use)))
1208           (if (and (global-var-p leaf)
1209                    (eq (global-var-kind leaf) :global-function)
1210                    (or (not (defined-function-p leaf))
1211                        (not (eq (defined-function-inlinep leaf) :notinline))
1212                        notinline-ok))
1213               (leaf-name leaf)
1214               nil))
1215         nil)))
1216
1217 ;;; Return the COMBINATION node that is the call to the let Fun.
1218 (defun let-combination (fun)
1219   (declare (type clambda fun))
1220   (aver (member (functional-kind fun) '(:let :mv-let)))
1221   (continuation-dest (node-cont (first (leaf-refs fun)))))
1222
1223 ;;; Return the initial value continuation for a let variable or NIL if none.
1224 (defun let-var-initial-value (var)
1225   (declare (type lambda-var var))
1226   (let ((fun (lambda-var-home var)))
1227     (elt (combination-args (let-combination fun))
1228          (position-or-lose var (lambda-vars fun)))))
1229
1230 ;;; Return the LAMBDA that is called by the local Call.
1231 #!-sb-fluid (declaim (inline combination-lambda))
1232 (defun combination-lambda (call)
1233   (declare (type basic-combination call))
1234   (aver (eq (basic-combination-kind call) :local))
1235   (ref-leaf (continuation-use (basic-combination-fun call))))
1236
1237 (defvar *inline-expansion-limit* 200
1238   #!+sb-doc
1239   "An upper limit on the number of inline function calls that will be expanded
1240    in any given code object (single function or block compilation.)")
1241
1242 ;;; Check whether Node's component has exceeded its inline expansion
1243 ;;; limit, and warn if so, returning NIL.
1244 (defun inline-expansion-ok (node)
1245   (let ((expanded (incf (component-inline-expansions
1246                          (block-component
1247                           (node-block node))))))
1248     (cond ((> expanded *inline-expansion-limit*) nil)
1249           ((= expanded *inline-expansion-limit*)
1250            (let ((*compiler-error-context* node))
1251              (compiler-note "*INLINE-EXPANSION-LIMIT* (~D) was exceeded, ~
1252                              probably trying to~%  ~
1253                              inline a recursive function."
1254                             *inline-expansion-limit*))
1255            nil)
1256           (t t))))
1257 \f
1258 ;;;; compiler error context determination
1259
1260 (declaim (special *current-path*))
1261
1262 ;;; We bind print level and length when printing out messages so that
1263 ;;; we don't dump huge amounts of garbage.
1264 ;;;
1265 ;;; FIXME: It's not possible to get the defaults right for everyone.
1266 ;;; So: Should these variables be in the SB-EXT package? Or should we
1267 ;;; just get rid of them completely and just use the bare
1268 ;;; CL:*PRINT-FOO* variables instead?
1269 (declaim (type (or unsigned-byte null)
1270                *compiler-error-print-level*
1271                *compiler-error-print-length*
1272                *compiler-error-print-lines*))
1273 (defvar *compiler-error-print-level* 5
1274   #!+sb-doc
1275   "the value for *PRINT-LEVEL* when printing compiler error messages")
1276 (defvar *compiler-error-print-length* 10
1277   #!+sb-doc
1278   "the value for *PRINT-LENGTH* when printing compiler error messages")
1279 (defvar *compiler-error-print-lines* 12
1280   #!+sb-doc
1281   "the value for *PRINT-LINES* when printing compiler error messages")
1282
1283 (defvar *enclosing-source-cutoff* 1
1284   #!+sb-doc
1285   "The maximum number of enclosing non-original source forms (i.e. from
1286   macroexpansion) that we print in full. For additional enclosing forms, we
1287   print only the CAR.")
1288 (declaim (type unsigned-byte *enclosing-source-cutoff*))
1289
1290 ;;; We separate the determination of compiler error contexts from the
1291 ;;; actual signalling of those errors by objectifying the error
1292 ;;; context. This allows postponement of the determination of how (and
1293 ;;; if) to signal the error.
1294 ;;;
1295 ;;; We take care not to reference any of the IR1 so that pending
1296 ;;; potential error messages won't prevent the IR1 from being GC'd. To
1297 ;;; this end, we convert source forms to strings so that source forms
1298 ;;; that contain IR1 references (e.g. %DEFUN) don't hold onto the IR.
1299 (defstruct (compiler-error-context
1300             #-no-ansi-print-object
1301             (:print-object (lambda (x stream)
1302                              (print-unreadable-object (x stream :type t))))
1303             (:copier nil))
1304   ;; A list of the stringified CARs of the enclosing non-original source forms
1305   ;; exceeding the *enclosing-source-cutoff*.
1306   (enclosing-source nil :type list)
1307   ;; A list of stringified enclosing non-original source forms.
1308   (source nil :type list)
1309   ;; The stringified form in the original source that expanded into Source.
1310   (original-source (required-argument) :type simple-string)
1311   ;; A list of prefixes of "interesting" forms that enclose original-source.
1312   (context nil :type list)
1313   ;; The FILE-INFO-NAME for the relevant FILE-INFO.
1314   (file-name (required-argument)
1315              :type (or pathname (member :lisp :stream)))
1316   ;; The file position at which the top-level form starts, if applicable.
1317   (file-position nil :type (or index null))
1318   ;; The original source part of the source path.
1319   (original-source-path nil :type list))
1320
1321 ;;; If true, this is the node which is used as context in compiler warning
1322 ;;; messages.
1323 (declaim (type (or null compiler-error-context node) *compiler-error-context*))
1324 (defvar *compiler-error-context* nil)
1325
1326 ;;; a hashtable mapping macro names to source context parsers. Each parser
1327 ;;; function returns the source-context list for that form.
1328 (defvar *source-context-methods* (make-hash-table))
1329
1330 ;;; documentation originally from cmu-user.tex:
1331 ;;;   This macro defines how to extract an abbreviated source context from
1332 ;;;   the \var{name}d form when it appears in the compiler input.
1333 ;;;   \var{lambda-list} is a \code{defmacro} style lambda-list used to
1334 ;;;   parse the arguments. The \var{body} should return a list of
1335 ;;;   subforms that can be printed on about one line. There are
1336 ;;;   predefined methods for \code{defstruct}, \code{defmethod}, etc. If
1337 ;;;   no method is defined, then the first two subforms are returned.
1338 ;;;   Note that this facility implicitly determines the string name
1339 ;;;   associated with anonymous functions.
1340 ;;; So even though SBCL itself only uses this macro within this file,
1341 ;;; it's a reasonable thing to put in SB-EXT in case some dedicated
1342 ;;; user wants to do some heavy tweaking to make SBCL give more
1343 ;;; informative output about his code.
1344 (defmacro def-source-context (name lambda-list &body body)
1345   #!+sb-doc
1346   "DEF-SOURCE-CONTEXT Name Lambda-List Form*
1347    This macro defines how to extract an abbreviated source context from the
1348    Named form when it appears in the compiler input. Lambda-List is a DEFMACRO
1349    style lambda-list used to parse the arguments. The Body should return a
1350    list of subforms suitable for a \"~{~S ~}\" format string."
1351   (let ((n-whole (gensym)))
1352     `(setf (gethash ',name *source-context-methods*)
1353            #'(lambda (,n-whole)
1354                (destructuring-bind ,lambda-list ,n-whole ,@body)))))
1355
1356 (def-source-context defstruct (name-or-options &rest slots)
1357   (declare (ignore slots))
1358   `(defstruct ,(if (consp name-or-options)
1359                    (car name-or-options)
1360                    name-or-options)))
1361
1362 (def-source-context function (thing)
1363   (if (and (consp thing) (eq (first thing) 'lambda) (consp (rest thing)))
1364       `(lambda ,(second thing))
1365       `(function ,thing)))
1366
1367 ;;; Return the first two elements of FORM if FORM is a list. Take the
1368 ;;; CAR of the second form if appropriate.
1369 (defun source-form-context (form)
1370   (cond ((atom form) nil)
1371         ((>= (length form) 2)
1372          (funcall (gethash (first form) *source-context-methods*
1373                            #'(lambda (x)
1374                                (declare (ignore x))
1375                                (list (first form) (second form))))
1376                   (rest form)))
1377         (t
1378          form)))
1379
1380 ;;; Given a source path, return the original source form and a
1381 ;;; description of the interesting aspects of the context in which it
1382 ;;; appeared. The context is a list of lists, one sublist per context
1383 ;;; form. The sublist is a list of some of the initial subforms of the
1384 ;;; context form.
1385 ;;;
1386 ;;; For now, we use the first two subforms of each interesting form. A
1387 ;;; form is interesting if the first element is a symbol beginning
1388 ;;; with "DEF" and it is not the source form. If there is no
1389 ;;; DEF-mumble, then we use the outermost containing form. If the
1390 ;;; second subform is a list, then in some cases we return the CAR of
1391 ;;; that form rather than the whole form (i.e. don't show DEFSTRUCT
1392 ;;; options, etc.)
1393 (defun find-original-source (path)
1394   (declare (list path))
1395   (let* ((rpath (reverse (source-path-original-source path)))
1396          (tlf (first rpath))
1397          (root (find-source-root tlf *source-info*)))
1398     (collect ((context))
1399       (let ((form root)
1400             (current (rest rpath)))
1401         (loop
1402           (when (atom form)
1403             (aver (null current))
1404             (return))
1405           (let ((head (first form)))
1406             (when (symbolp head)
1407               (let ((name (symbol-name head)))
1408                 (when (and (>= (length name) 3) (string= name "DEF" :end1 3))
1409                   (context (source-form-context form))))))
1410           (when (null current) (return))
1411           (setq form (nth (pop current) form)))
1412         
1413         (cond ((context)
1414                (values form (context)))
1415               ((and path root)
1416                (let ((c (source-form-context root)))
1417                  (values form (if c (list c) nil))))
1418               (t
1419                (values '(unable to locate source)
1420                        '((some strange place)))))))))
1421
1422 ;;; Convert a source form to a string, suitably formatted for use in
1423 ;;; compiler warnings.
1424 (defun stringify-form (form &optional (pretty t))
1425   (let ((*print-level* *compiler-error-print-level*)
1426         (*print-length* *compiler-error-print-length*)
1427         (*print-lines* *compiler-error-print-lines*)
1428         (*print-pretty* pretty))
1429     (if pretty
1430         (format nil "~<~@;  ~S~:>" (list form))
1431         (prin1-to-string form))))
1432
1433 ;;; Return a COMPILER-ERROR-CONTEXT structure describing the current
1434 ;;; error context, or NIL if we can't figure anything out. ARGS is a
1435 ;;; list of things that are going to be printed out in the error
1436 ;;; message, and can thus be blown off when they appear in the source
1437 ;;; context.
1438 (defun find-error-context (args)
1439   (let ((context *compiler-error-context*))
1440     (if (compiler-error-context-p context)
1441         context
1442         (let ((path (or *current-path*
1443                         (if context
1444                             (node-source-path context)
1445                             nil))))
1446           (when (and *source-info* path)
1447             (multiple-value-bind (form src-context) (find-original-source path)
1448               (collect ((full nil cons)
1449                         (short nil cons))
1450                 (let ((forms (source-path-forms path))
1451                       (n 0))
1452                   (dolist (src (if (member (first forms) args)
1453                                    (rest forms)
1454                                    forms))
1455                     (if (>= n *enclosing-source-cutoff*)
1456                         (short (stringify-form (if (consp src)
1457                                                    (car src)
1458                                                    src)
1459                                                nil))
1460                         (full (stringify-form src)))
1461                     (incf n)))
1462
1463                 (let* ((tlf (source-path-tlf-number path))
1464                        (file-info (source-info-file-info *source-info*)))
1465                   (make-compiler-error-context
1466                    :enclosing-source (short)
1467                    :source (full)
1468                    :original-source (stringify-form form)
1469                    :context src-context
1470                    :file-name (file-info-name file-info)
1471                    :file-position
1472                    (multiple-value-bind (ignore pos)
1473                        (find-source-root tlf *source-info*)
1474                      (declare (ignore ignore))
1475                      pos)
1476                    :original-source-path
1477                    (source-path-original-source path))))))))))
1478 \f
1479 ;;;; printing error messages
1480
1481 ;;; We save the context information that we printed out most recently
1482 ;;; so that we don't print it out redundantly.
1483
1484 ;;; The last COMPILER-ERROR-CONTEXT that we printed.
1485 (defvar *last-error-context* nil)
1486 (declaim (type (or compiler-error-context null) *last-error-context*))
1487
1488 ;;; The format string and args for the last error we printed.
1489 (defvar *last-format-string* nil)
1490 (defvar *last-format-args* nil)
1491 (declaim (type (or string null) *last-format-string*))
1492 (declaim (type list *last-format-args*))
1493
1494 ;;; The number of times that the last error message has been emitted,
1495 ;;; so that we can compress duplicate error messages.
1496 (defvar *last-message-count* 0)
1497 (declaim (type index *last-message-count*))
1498
1499 ;;; If the last message was given more than once, then print out an
1500 ;;; indication of how many times it was repeated. We reset the message count
1501 ;;; when we are done.
1502 (defun note-message-repeats (&optional (terpri t))
1503   (cond ((= *last-message-count* 1)
1504          (when terpri (terpri *error-output*)))
1505         ((> *last-message-count* 1)
1506           (format *error-output* "~&; [Last message occurs ~D times.]~2%"
1507                  *last-message-count*)))
1508   (setq *last-message-count* 0))
1509
1510 ;;; Print out the message, with appropriate context if we can find it.
1511 ;;; If the context is different from the context of the last message
1512 ;;; we printed, then we print the context. If the original source is
1513 ;;; different from the source we are working on, then we print the
1514 ;;; current source in addition to the original source.
1515 ;;;
1516 ;;; We suppress printing of messages identical to the previous, but
1517 ;;; record the number of times that the message is repeated.
1518 (defun print-compiler-message (format-string format-args)
1519
1520   (declare (type simple-string format-string))
1521   (declare (type list format-args))
1522   
1523   (let ((stream *error-output*)
1524         (context (find-error-context format-args)))
1525     (cond
1526      (context
1527       (let ((file (compiler-error-context-file-name context))
1528             (in (compiler-error-context-context context))
1529             (form (compiler-error-context-original-source context))
1530             (enclosing (compiler-error-context-enclosing-source context))
1531             (source (compiler-error-context-source context))
1532             (last *last-error-context*))
1533
1534         (unless (and last
1535                      (equal file (compiler-error-context-file-name last)))
1536           (when (pathnamep file)
1537             (note-message-repeats)
1538             (setq last nil)
1539             (format stream "~2&; file: ~A~%" (namestring file))))
1540
1541         (unless (and last
1542                      (equal in (compiler-error-context-context last)))
1543           (note-message-repeats)
1544           (setq last nil)
1545           (format stream "~&")
1546           (pprint-logical-block (stream nil :per-line-prefix "; ")
1547             (format stream "in:~{~<~%    ~4:;~{ ~S~}~>~^ =>~}" in))
1548           (format stream "~%"))
1549
1550
1551         (unless (and last
1552                      (string= form
1553                               (compiler-error-context-original-source last)))
1554           (note-message-repeats)
1555           (setq last nil)
1556           (format stream "~&")
1557           (pprint-logical-block (stream nil :per-line-prefix "; ")
1558             (format stream "  ~A" form))
1559           (format stream "~&"))
1560
1561         (unless (and last
1562                      (equal enclosing
1563                             (compiler-error-context-enclosing-source last)))
1564           (when enclosing
1565             (note-message-repeats)
1566             (setq last nil)
1567             (format stream "~&; --> ~{~<~%; --> ~1:;~A~> ~}~%" enclosing)))
1568
1569         (unless (and last
1570                      (equal source (compiler-error-context-source last)))
1571           (setq *last-format-string* nil)
1572           (when source
1573             (note-message-repeats)
1574             (dolist (src source)
1575               (format stream "~&")
1576               (write-string "; ==>" stream)
1577               (format stream "~&")
1578               (pprint-logical-block (stream nil :per-line-prefix "; ")
1579                 (write-string src stream)))))))
1580      (t
1581        (format stream "~&")
1582       (note-message-repeats)
1583       (setq *last-format-string* nil)
1584        (format stream "~&")))
1585
1586     (setq *last-error-context* context)
1587
1588     (unless (and (equal format-string *last-format-string*)
1589                  (tree-equal format-args *last-format-args*))
1590       (note-message-repeats nil)
1591       (setq *last-format-string* format-string)
1592       (setq *last-format-args* format-args)
1593       (let ((*print-level*  *compiler-error-print-level*)
1594             (*print-length* *compiler-error-print-length*)
1595             (*print-lines*  *compiler-error-print-lines*))
1596         (format stream "~&")
1597         (pprint-logical-block (stream nil :per-line-prefix "; ")
1598           (format stream "~&~?" format-string format-args))
1599         (format stream "~&"))))
1600
1601   (incf *last-message-count*)
1602   (values))
1603
1604 (defun print-compiler-condition (condition)
1605   (declare (type condition condition))
1606   (let (;; These different classes of conditions have different
1607         ;; effects on the return codes of COMPILE-FILE, so it's nice
1608         ;; for users to be able to pick them out by lexical search
1609         ;; through the output.
1610         (what (etypecase condition
1611                 (style-warning 'style-warning)
1612                 (warning 'warning)
1613                 (error 'error))))
1614     (multiple-value-bind (format-string format-args)
1615         (if (typep condition 'simple-condition)
1616             (values (simple-condition-format-control condition)
1617                     (simple-condition-format-arguments condition))
1618             (values "~A"
1619                     (list (with-output-to-string (s)
1620                             (princ condition s)))))
1621       (print-compiler-message (format nil
1622                                       "caught ~S:~%  ~A"
1623                                       what
1624                                       format-string)
1625                               format-args)))
1626   (values))
1627
1628 ;;; COMPILER-NOTE is vaguely like COMPILER-ERROR and the other
1629 ;;; condition-signalling functions, but it just writes some output
1630 ;;; instead of signalling. (In CMU CL, it did signal a condition, but
1631 ;;; this didn't seem to work all that well; it was weird to have
1632 ;;; COMPILE-FILE return with WARNINGS-P set when the only problem was
1633 ;;; that the compiler couldn't figure out how to compile something as
1634 ;;; efficiently as it liked.)
1635 (defun compiler-note (format-string &rest format-args)
1636   (unless (if *compiler-error-context*
1637               (policy *compiler-error-context* (= inhibit-warnings 3))
1638               (policy *lexenv* (= inhibit-warnings 3)))
1639     (incf *compiler-note-count*)
1640     (print-compiler-message (format nil "note: ~A" format-string)
1641                             format-args))
1642   (values))
1643
1644 ;;; Issue a note when we might or might not be in the compiler.
1645 (defun maybe-compiler-note (&rest rest)
1646   (if (boundp '*lexenv*) ; if we're in the compiler
1647       (apply #'compiler-note rest)
1648       (let ((stream *error-output*))
1649         (pprint-logical-block (stream nil :per-line-prefix ";")
1650           
1651           (format stream " note: ~3I~_")
1652           (pprint-logical-block (stream nil)
1653             (apply #'format stream rest)))
1654         (fresh-line stream)))) ; (outside logical block, no per-line-prefix)
1655
1656 ;;; The politically correct way to print out progress messages and
1657 ;;; such like. We clear the current error context so that we know that
1658 ;;; it needs to be reprinted, and we also Force-Output so that the
1659 ;;; message gets seen right away.
1660 (declaim (ftype (function (string &rest t) (values)) compiler-mumble))
1661 (defun compiler-mumble (format-string &rest format-args)
1662   (note-message-repeats)
1663   (setq *last-error-context* nil)
1664   (apply #'format *error-output* format-string format-args)
1665   (force-output *error-output*)
1666   (values))
1667
1668 ;;; Return a string that somehow names the code in COMPONENT. We use
1669 ;;; the source path for the bind node for an arbitrary entry point to
1670 ;;; find the source context, then return that as a string.
1671 (declaim (ftype (function (component) simple-string) find-component-name))
1672 (defun find-component-name (component)
1673   (let ((ep (first (block-succ (component-head component)))))
1674     (aver ep) ; else no entry points??
1675     (multiple-value-bind (form context)
1676         (find-original-source
1677          (node-source-path (continuation-next (block-start ep))))
1678       (declare (ignore form))
1679       (let ((*print-level* 2)
1680             (*print-pretty* nil))
1681         (format nil "~{~{~S~^ ~}~^ => ~}" context)))))
1682 \f
1683 ;;;; condition system interface
1684
1685 ;;; Keep track of how many times each kind of condition happens.
1686 (defvar *compiler-error-count*)
1687 (defvar *compiler-warning-count*)
1688 (defvar *compiler-style-warning-count*)
1689 (defvar *compiler-note-count*)
1690
1691 ;;; Keep track of whether any surrounding COMPILE or COMPILE-FILE call
1692 ;;; should return WARNINGS-P or FAILURE-P.
1693 (defvar *failure-p*)
1694 (defvar *warnings-p*)
1695
1696 ;;; condition handlers established by the compiler. We re-signal the
1697 ;;; condition, then if it isn't handled, we increment our warning
1698 ;;; counter and print the error message.
1699 (defun compiler-error-handler (condition)
1700   (signal condition)
1701   (incf *compiler-error-count*)
1702   (setf *warnings-p* t
1703         *failure-p* t)
1704   (print-compiler-condition condition)
1705   (continue condition))
1706 (defun compiler-warning-handler (condition)
1707   (signal condition)
1708   (incf *compiler-warning-count*)
1709   (setf *warnings-p* t
1710         *failure-p* t)
1711   (print-compiler-condition condition)
1712   (muffle-warning condition))
1713 (defun compiler-style-warning-handler (condition)
1714   (signal condition)
1715   (incf *compiler-style-warning-count*)
1716   (setf *warnings-p* t)
1717   (print-compiler-condition condition)
1718   (muffle-warning condition))
1719 \f
1720 ;;;; undefined warnings
1721
1722 (defvar *undefined-warning-limit* 3
1723   #!+sb-doc
1724   "If non-null, then an upper limit on the number of unknown function or type
1725   warnings that the compiler will print for any given name in a single
1726   compilation. This prevents excessive amounts of output when the real
1727   problem is a missing definition (as opposed to a typo in the use.)")
1728
1729 ;;; Make an entry in the *UNDEFINED-WARNINGS* describing a reference
1730 ;;; to NAME of the specified KIND. If we have exceeded the warning
1731 ;;; limit, then just increment the count, otherwise note the current
1732 ;;; error context.
1733 ;;;
1734 ;;; Undefined types are noted by a condition handler in
1735 ;;; WITH-COMPILATION-UNIT, which can potentially be invoked outside
1736 ;;; the compiler, hence the BOUNDP check.
1737 (defun note-undefined-reference (name kind)
1738   (unless (and
1739            ;; Check for boundness so we don't blow up if we're called
1740            ;; when IR1 conversion isn't going on.
1741            (boundp '*lexenv*)
1742            ;; FIXME: I'm pretty sure the INHIBIT-WARNINGS test below
1743            ;; isn't a good idea; we should have INHIBIT-WARNINGS
1744            ;; affect compiler notes, not STYLE-WARNINGs. And I'm not
1745            ;; sure what the BOUNDP '*LEXENV* test above is for; it's
1746            ;; likely a good idea, but it probably deserves an
1747            ;; explanatory comment.
1748            (policy *lexenv* (= inhibit-warnings 3)))
1749     (let* ((found (dolist (warning *undefined-warnings* nil)
1750                     (when (and (equal (undefined-warning-name warning) name)
1751                                (eq (undefined-warning-kind warning) kind))
1752                       (return warning))))
1753            (res (or found
1754                     (make-undefined-warning :name name :kind kind))))
1755       (unless found (push res *undefined-warnings*))
1756       (when (or (not *undefined-warning-limit*)
1757                 (< (undefined-warning-count res) *undefined-warning-limit*))
1758         (push (find-error-context (list name))
1759               (undefined-warning-warnings res)))
1760       (incf (undefined-warning-count res))))
1761   (values))
1762 \f
1763 ;;;; careful call
1764
1765 ;;; Apply a function to some arguments, returning a list of the values
1766 ;;; resulting of the evaluation. If an error is signalled during the
1767 ;;; application, then we print a warning message and return NIL as our
1768 ;;; second value to indicate this. Node is used as the error context
1769 ;;; for any error message, and Context is a string that is spliced
1770 ;;; into the warning.
1771 (declaim (ftype (function ((or symbol function) list node string)
1772                           (values list boolean))
1773                 careful-call))
1774 (defun careful-call (function args node context)
1775   (values
1776    (multiple-value-list
1777     (handler-case (apply function args)
1778       (error (condition)
1779         (let ((*compiler-error-context* node))
1780           (compiler-warning "Lisp error during ~A:~%~A" context condition)
1781           (return-from careful-call (values nil nil))))))
1782    t))
1783 \f
1784 ;;;; utilities used at run-time for parsing &KEY args in IR1
1785
1786 ;;; This function is used by the result of PARSE-DEFTRANSFORM to find
1787 ;;; the continuation for the value of the &KEY argument KEY in the
1788 ;;; list of continuations ARGS. It returns the continuation if the
1789 ;;; keyword is present, or NIL otherwise. The legality and
1790 ;;; constantness of the keywords should already have been checked.
1791 (declaim (ftype (function (list keyword) (or continuation null))
1792                 find-keyword-continuation))
1793 (defun find-keyword-continuation (args key)
1794   (do ((arg args (cddr arg)))
1795       ((null arg) nil)
1796     (when (eq (continuation-value (first arg)) key)
1797       (return (second arg)))))
1798
1799 ;;; This function is used by the result of PARSE-DEFTRANSFORM to
1800 ;;; verify that alternating continuations in ARGS are constant and
1801 ;;; that there is an even number of args.
1802 (declaim (ftype (function (list) boolean) check-key-args-constant))
1803 (defun check-key-args-constant (args)
1804   (do ((arg args (cddr arg)))
1805       ((null arg) t)
1806     (unless (and (rest arg)
1807                  (constant-continuation-p (first arg)))
1808       (return nil))))
1809
1810 ;;; This function is used by the result of PARSE-DEFTRANSFORM to
1811 ;;; verify that the list of continuations ARGS is a well-formed &KEY
1812 ;;; arglist and that only keywords present in the list KEYS are
1813 ;;; supplied.
1814 (declaim (ftype (function (list list) boolean) check-transform-keys))
1815 (defun check-transform-keys (args keys)
1816   (and (check-key-args-constant args)
1817        (do ((arg args (cddr arg)))
1818            ((null arg) t)
1819          (unless (member (continuation-value (first arg)) keys)
1820            (return nil)))))
1821 \f
1822 ;;;; miscellaneous
1823
1824 ;;; Called by the expansion of the EVENT macro.
1825 (declaim (ftype (function (event-info (or node null)) *) %event))
1826 (defun %event (info node)
1827   (incf (event-info-count info))
1828   (when (and (>= (event-info-level info) *event-note-threshold*)
1829              (policy (or node *lexenv*)
1830                      (= inhibit-warnings 0)))
1831     (let ((*compiler-error-context* node))
1832       (compiler-note (event-info-description info))))
1833
1834   (let ((action (event-info-action info)))
1835     (when action (funcall action node))))