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