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