7f44b64f3178c987f5d212e03804aa33cf2a6417
[sbcl.git] / src / compiler / ir1opt.lisp
1 ;;;; This file implements the IR1 optimization phase of the compiler.
2 ;;;; IR1 optimization is a grab-bag of optimizations that don't make
3 ;;;; major changes to the block-level control flow and don't use flow
4 ;;;; analysis. These optimizations can mostly be classified as
5 ;;;; "meta-evaluation", but there is a sizable top-down component as
6 ;;;; well.
7
8 ;;;; This software is part of the SBCL system. See the README file for
9 ;;;; more information.
10 ;;;;
11 ;;;; This software is derived from the CMU CL system, which was
12 ;;;; written at Carnegie Mellon University and released into the
13 ;;;; public domain. The software is in the public domain and is
14 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
15 ;;;; files for more information.
16
17 (in-package "SB!C")
18 \f
19 ;;;; interface for obtaining results of constant folding
20
21 ;;; Return true for an LVAR whose sole use is a reference to a
22 ;;; constant leaf.
23 (defun constant-lvar-p (thing)
24   (declare (type (or lvar null) thing))
25   (and (lvar-p thing)
26        (or (let ((use (principal-lvar-use thing)))
27              (and (ref-p use) (constant-p (ref-leaf use))))
28            ;; check for EQL types (but not singleton numeric types)
29            (let ((type (lvar-type thing)))
30              (values (type-singleton-p type))))))
31
32 ;;; Return the constant value for an LVAR whose only use is a constant
33 ;;; node.
34 (declaim (ftype (function (lvar) t) lvar-value))
35 (defun lvar-value (lvar)
36   (let ((use  (principal-lvar-use lvar))
37         (type (lvar-type lvar))
38         leaf)
39     (if (and (ref-p use)
40              (constant-p (setf leaf (ref-leaf use))))
41         (constant-value leaf)
42         (multiple-value-bind (constantp value) (type-singleton-p type)
43           (unless constantp
44             (error "~S used on non-constant LVAR ~S" 'lvar-value lvar))
45           value))))
46 \f
47 ;;;; interface for obtaining results of type inference
48
49 ;;; Our best guess for the type of this lvar's value. Note that this
50 ;;; may be VALUES or FUNCTION type, which cannot be passed as an
51 ;;; argument to the normal type operations. See LVAR-TYPE.
52 ;;;
53 ;;; The result value is cached in the LVAR-%DERIVED-TYPE slot. If the
54 ;;; slot is true, just return that value, otherwise recompute and
55 ;;; stash the value there.
56 (eval-when (:compile-toplevel :execute)
57   (#+sb-xc-host cl:defmacro
58    #-sb-xc-host sb!xc:defmacro
59         lvar-type-using (lvar accessor)
60      `(let ((uses (lvar-uses ,lvar)))
61         (cond ((null uses) *empty-type*)
62               ((listp uses)
63                (do ((res (,accessor (first uses))
64                          (values-type-union (,accessor (first current))
65                                             res))
66                     (current (rest uses) (rest current)))
67                    ((or (null current) (eq res *wild-type*))
68                     res)))
69               (t
70                (,accessor uses))))))
71
72 #!-sb-fluid (declaim (inline lvar-derived-type))
73 (defun lvar-derived-type (lvar)
74   (declare (type lvar lvar))
75   (or (lvar-%derived-type lvar)
76       (setf (lvar-%derived-type lvar)
77             (%lvar-derived-type lvar))))
78 (defun %lvar-derived-type (lvar)
79   (lvar-type-using lvar node-derived-type))
80
81 ;;; Return the derived type for LVAR's first value. This is guaranteed
82 ;;; not to be a VALUES or FUNCTION type.
83 (declaim (ftype (sfunction (lvar) ctype) lvar-type))
84 (defun lvar-type (lvar)
85   (single-value-type (lvar-derived-type lvar)))
86
87 ;;; LVAR-CONSERVATIVE-TYPE
88 ;;;
89 ;;; Certain types refer to the contents of an object, which can
90 ;;; change without type derivation noticing: CONS types and ARRAY
91 ;;; types suffer from this:
92 ;;;
93 ;;;  (let ((x (the (cons fixnum fixnum) (cons a b))))
94 ;;;     (setf (car x) c)
95 ;;;     (+ (car x) (cdr x)))
96 ;;;
97 ;;; Python doesn't realize that the SETF CAR can change the type of X -- so we
98 ;;; cannot use LVAR-TYPE which gets the derived results. Worse, still, instead
99 ;;; of (SETF CAR) we might have a call to a user-defined function FOO which
100 ;;; does the same -- so there is no way to use the derived information in
101 ;;; general.
102 ;;;
103 ;;; So, the conservative option is to use the derived type if the leaf has
104 ;;; only a single ref -- in which case there cannot be a prior call that
105 ;;; mutates it. Otherwise we use the declared type or punt to the most general
106 ;;; type we know to be correct for sure.
107 (defun lvar-conservative-type (lvar)
108   (let ((derived-type (lvar-type lvar))
109         (t-type *universal-type*))
110     ;; Recompute using NODE-CONSERVATIVE-TYPE instead of derived type if
111     ;; necessary -- picking off some easy cases up front.
112     (cond ((or (eq derived-type t-type)
113                ;; Can't use CSUBTYPEP!
114                (type= derived-type (specifier-type 'list))
115                (type= derived-type (specifier-type 'null)))
116            derived-type)
117           ((and (cons-type-p derived-type)
118                 (eq t-type (cons-type-car-type derived-type))
119                 (eq t-type (cons-type-cdr-type derived-type)))
120            derived-type)
121           ((and (array-type-p derived-type)
122                 (or (not (array-type-complexp derived-type))
123                     (let ((dimensions (array-type-dimensions derived-type)))
124                       (or (eq '* dimensions)
125                           (every (lambda (dim) (eq '* dim)) dimensions)))))
126            derived-type)
127           ((type-needs-conservation-p derived-type)
128            (single-value-type (lvar-type-using lvar node-conservative-type)))
129           (t
130            derived-type))))
131
132 (defun node-conservative-type (node)
133   (let* ((derived-values-type (node-derived-type node))
134          (derived-type (single-value-type derived-values-type)))
135     (if (ref-p node)
136         (let ((leaf (ref-leaf node)))
137           (if (and (basic-var-p leaf)
138                    (cdr (leaf-refs leaf)))
139               (coerce-to-values
140                (if (eq :declared (leaf-where-from leaf))
141                    (leaf-type leaf)
142                    (conservative-type derived-type)))
143               derived-values-type))
144         derived-values-type)))
145
146 (defun conservative-type (type)
147   (cond ((or (eq type *universal-type*)
148              (eq type (specifier-type 'list))
149              (eq type (specifier-type 'null)))
150          type)
151         ((cons-type-p type)
152          (specifier-type 'cons))
153         ((array-type-p type)
154          (if (array-type-complexp type)
155              (make-array-type
156               ;; ADJUST-ARRAY may change dimensions, but rank stays same.
157               :dimensions
158               (let ((old (array-type-dimensions type)))
159                 (if (eq '* old)
160                     old
161                     (mapcar (constantly '*) old)))
162               ;; Complexity cannot change.
163               :complexp (array-type-complexp type)
164               ;; Element type cannot change.
165               :element-type (array-type-element-type type)
166               :specialized-element-type (array-type-specialized-element-type type))
167              ;; Simple arrays cannot change at all.
168              type))
169         ((union-type-p type)
170          ;; Conservative union type is an union of conservative types.
171          (let ((res *empty-type*))
172            (dolist (part (union-type-types type) res)
173              (setf res (type-union res (conservative-type part))))))
174         (t
175          ;; Catch-all.
176          ;;
177          ;; If the type contains some CONS types, the conservative type contains all
178          ;; of them.
179          (when (types-equal-or-intersect type (specifier-type 'cons))
180            (setf type (type-union type (specifier-type 'cons))))
181          ;; Similarly for non-simple arrays -- it should be possible to preserve
182          ;; more information here, but really...
183          (let ((non-simple-arrays (specifier-type '(and array (not simple-array)))))
184            (when (types-equal-or-intersect type non-simple-arrays)
185              (setf type (type-union type non-simple-arrays))))
186          type)))
187
188 (defun type-needs-conservation-p (type)
189   (cond ((eq type *universal-type*)
190          ;; Excluding T is necessary, because we do want type derivation to
191          ;; be able to narrow it down in case someone (most like a macro-expansion...)
192          ;; actually declares something as having type T.
193          nil)
194         ((or (cons-type-p type) (and (array-type-p type) (array-type-complexp type)))
195          ;; Covered by the next case as well, but this is a quick test.
196          t)
197         ((types-equal-or-intersect type (specifier-type '(or cons (and array (not simple-array)))))
198          t)))
199
200 ;;; If LVAR is an argument of a function, return a type which the
201 ;;; function checks LVAR for.
202 #!-sb-fluid (declaim (inline lvar-externally-checkable-type))
203 (defun lvar-externally-checkable-type (lvar)
204   (or (lvar-%externally-checkable-type lvar)
205       (%lvar-%externally-checkable-type lvar)))
206 (defun %lvar-%externally-checkable-type (lvar)
207   (declare (type lvar lvar))
208   (let ((dest (lvar-dest lvar)))
209     (if (not (and dest (combination-p dest)))
210         ;; TODO: MV-COMBINATION
211         (setf (lvar-%externally-checkable-type lvar) *wild-type*)
212         (let* ((fun (combination-fun dest))
213                (args (combination-args dest))
214                (fun-type (lvar-type fun)))
215           (setf (lvar-%externally-checkable-type fun) *wild-type*)
216           (if (or (not (call-full-like-p dest))
217                   (not (fun-type-p fun-type))
218                   ;; FUN-TYPE might be (AND FUNCTION (SATISFIES ...)).
219                   (fun-type-wild-args fun-type))
220               (dolist (arg args)
221                 (when arg
222                   (setf (lvar-%externally-checkable-type arg)
223                         *wild-type*)))
224               (map-combination-args-and-types
225                (lambda (arg type)
226                  (setf (lvar-%externally-checkable-type arg)
227                        (acond ((lvar-%externally-checkable-type arg)
228                                (values-type-intersection
229                                 it (coerce-to-values type)))
230                               (t (coerce-to-values type)))))
231                dest)))))
232   (or (lvar-%externally-checkable-type lvar) *wild-type*))
233 #!-sb-fluid(declaim (inline flush-lvar-externally-checkable-type))
234 (defun flush-lvar-externally-checkable-type (lvar)
235   (declare (type lvar lvar))
236   (setf (lvar-%externally-checkable-type lvar) nil))
237 \f
238 ;;;; interface routines used by optimizers
239
240 (declaim (inline reoptimize-component))
241 (defun reoptimize-component (component kind)
242   (declare (type component component)
243            (type (member nil :maybe t) kind))
244   (aver kind)
245   (unless (eq (component-reoptimize component) t)
246     (setf (component-reoptimize component) kind)))
247
248 ;;; This function is called by optimizers to indicate that something
249 ;;; interesting has happened to the value of LVAR. Optimizers must
250 ;;; make sure that they don't call for reoptimization when nothing has
251 ;;; happened, since optimization will fail to terminate.
252 ;;;
253 ;;; We clear any cached type for the lvar and set the reoptimize flags
254 ;;; on everything in sight.
255 (defun reoptimize-lvar (lvar)
256   (declare (type (or lvar null) lvar))
257   (when lvar
258     (setf (lvar-%derived-type lvar) nil)
259     (let ((dest (lvar-dest lvar)))
260       (when dest
261         (setf (lvar-reoptimize lvar) t)
262         (setf (node-reoptimize dest) t)
263         (binding* (;; Since this may be called during IR1 conversion,
264                    ;; PREV may be missing.
265                    (prev (node-prev dest) :exit-if-null)
266                    (block (ctran-block prev))
267                    (component (block-component block)))
268           (when (typep dest 'cif)
269             (setf (block-test-modified block) t))
270           (setf (block-reoptimize block) t)
271           (reoptimize-component component :maybe))))
272     (do-uses (node lvar)
273       (setf (block-type-check (node-block node)) t)))
274   (values))
275
276 (defun reoptimize-lvar-uses (lvar)
277   (declare (type lvar lvar))
278   (do-uses (use lvar)
279     (setf (node-reoptimize use) t)
280     (setf (block-reoptimize (node-block use)) t)
281     (reoptimize-component (node-component use) :maybe)))
282
283 ;;; Annotate NODE to indicate that its result has been proven to be
284 ;;; TYPEP to RTYPE. After IR1 conversion has happened, this is the
285 ;;; only correct way to supply information discovered about a node's
286 ;;; type. If you screw with the NODE-DERIVED-TYPE directly, then
287 ;;; information may be lost and reoptimization may not happen.
288 ;;;
289 ;;; What we do is intersect RTYPE with NODE's DERIVED-TYPE. If the
290 ;;; intersection is different from the old type, then we do a
291 ;;; REOPTIMIZE-LVAR on the NODE-LVAR.
292 (defun derive-node-type (node rtype &key from-scratch)
293   (declare (type valued-node node) (type ctype rtype))
294   (let* ((initial-type (node-derived-type node))
295          (node-type (if from-scratch
296                         *wild-type*
297                         initial-type)))
298     (unless (eq initial-type rtype)
299       (let ((int (values-type-intersection node-type rtype))
300             (lvar (node-lvar node)))
301         (when (type/= initial-type int)
302           (when (and *check-consistency*
303                      (eq int *empty-type*)
304                      (not (eq rtype *empty-type*)))
305             (aver (not from-scratch))
306             (let ((*compiler-error-context* node))
307               (compiler-warn
308                "New inferred type ~S conflicts with old type:~
309                 ~%  ~S~%*** possible internal error? Please report this."
310                (type-specifier rtype) (type-specifier node-type))))
311           (setf (node-derived-type node) int)
312           ;; If the new type consists of only one object, replace the
313           ;; node with a constant reference.
314           (when (and (ref-p node)
315                      (lambda-var-p (ref-leaf node)))
316             (let ((type (single-value-type int)))
317               (when (and (member-type-p type)
318                          (eql 1 (member-type-size type)))
319                 (change-ref-leaf node (find-constant
320                                        (first (member-type-members type)))))))
321           (reoptimize-lvar lvar)))))
322   (values))
323
324 ;;; This is similar to DERIVE-NODE-TYPE, but asserts that it is an
325 ;;; error for LVAR's value not to be TYPEP to TYPE. We implement it
326 ;;; splitting off DEST a new CAST node; old LVAR will deliver values
327 ;;; to CAST. If we improve the assertion, we set TYPE-CHECK and
328 ;;; TYPE-ASSERTED to guarantee that the new assertion will be checked.
329 (defun assert-lvar-type (lvar type policy)
330   (declare (type lvar lvar) (type ctype type))
331   (unless (values-subtypep (lvar-derived-type lvar) type)
332     (let ((internal-lvar (make-lvar))
333           (dest (lvar-dest lvar)))
334       (substitute-lvar internal-lvar lvar)
335       (let ((cast (insert-cast-before dest lvar type policy)))
336         (use-lvar cast internal-lvar)
337         t))))
338
339 \f
340 ;;;; IR1-OPTIMIZE
341
342 ;;; Do one forward pass over COMPONENT, deleting unreachable blocks
343 ;;; and doing IR1 optimizations. We can ignore all blocks that don't
344 ;;; have the REOPTIMIZE flag set. If COMPONENT-REOPTIMIZE is true when
345 ;;; we are done, then another iteration would be beneficial.
346 (defun ir1-optimize (component fastp)
347   (declare (type component component))
348   (setf (component-reoptimize component) nil)
349   (loop with block = (block-next (component-head component))
350         with tail = (component-tail component)
351         for last-block = block
352         until (eq block tail)
353         do (cond
354              ;; We delete blocks when there is either no predecessor or the
355              ;; block is in a lambda that has been deleted. These blocks
356              ;; would eventually be deleted by DFO recomputation, but doing
357              ;; it here immediately makes the effect available to IR1
358              ;; optimization.
359              ((or (block-delete-p block)
360                   (null (block-pred block)))
361               (delete-block-lazily block)
362               (setq block (clean-component component block)))
363              ((eq (functional-kind (block-home-lambda block)) :deleted)
364               ;; Preserve the BLOCK-SUCC invariant that almost every block has
365               ;; one successor (and a block with DELETE-P set is an acceptable
366               ;; exception).
367               (mark-for-deletion block)
368               (setq block (clean-component component block)))
369              (t
370               (loop
371                  (let ((succ (block-succ block)))
372                    (unless (singleton-p succ)
373                      (return)))
374
375                  (let ((last (block-last block)))
376                    (typecase last
377                      (cif
378                       (flush-dest (if-test last))
379                       (when (unlink-node last)
380                         (return)))
381                      (exit
382                       (when (maybe-delete-exit last)
383                         (return)))))
384
385                  (unless (join-successor-if-possible block)
386                    (return)))
387
388               (when (and (not fastp) (block-reoptimize block) (block-component block))
389                 (aver (not (block-delete-p block)))
390                 (ir1-optimize-block block))
391
392               (cond ((and (block-delete-p block) (block-component block))
393                      (setq block (clean-component component block)))
394                     ((and (block-flush-p block) (block-component block))
395                      (flush-dead-code block)))))
396         do (when (eq block last-block)
397              (setq block (block-next block))))
398
399   (values))
400
401 ;;; Loop over the nodes in BLOCK, acting on (and clearing) REOPTIMIZE
402 ;;; flags.
403 ;;;
404 ;;; Note that although they are cleared here, REOPTIMIZE flags might
405 ;;; still be set upon return from this function, meaning that further
406 ;;; optimization is wanted (as a consequence of optimizations we did).
407 (defun ir1-optimize-block (block)
408   (declare (type cblock block))
409   ;; We clear the node and block REOPTIMIZE flags before doing the
410   ;; optimization, not after. This ensures that the node or block will
411   ;; be reoptimized if necessary.
412   (setf (block-reoptimize block) nil)
413   (do-nodes (node nil block :restart-p t)
414     (when (node-reoptimize node)
415       ;; As above, we clear the node REOPTIMIZE flag before optimizing.
416       (setf (node-reoptimize node) nil)
417       (typecase node
418         (ref)
419         (combination
420          ;; With a COMBINATION, we call PROPAGATE-FUN-CHANGE whenever
421          ;; the function changes, and call IR1-OPTIMIZE-COMBINATION if
422          ;; any argument changes.
423          (ir1-optimize-combination node))
424         (cif
425          (ir1-optimize-if node))
426         (creturn
427          ;; KLUDGE: We leave the NODE-OPTIMIZE flag set going into
428          ;; IR1-OPTIMIZE-RETURN, since IR1-OPTIMIZE-RETURN wants to
429          ;; clear the flag itself. -- WHN 2002-02-02, quoting original
430          ;; CMU CL comments
431          (setf (node-reoptimize node) t)
432          (ir1-optimize-return node))
433         (mv-combination
434          (ir1-optimize-mv-combination node))
435         (exit
436          ;; With an EXIT, we derive the node's type from the VALUE's
437          ;; type.
438          (let ((value (exit-value node)))
439            (when value
440              (derive-node-type node (lvar-derived-type value)))))
441         (cset
442          ;; PROPAGATE-FROM-SETS can do a better job if NODE-REOPTIMIZE
443          ;; is accurate till the node actually has been reoptimized.
444          (setf (node-reoptimize node) t)
445          (ir1-optimize-set node))
446         (cast
447          (ir1-optimize-cast node)))))
448
449   (values))
450
451 ;;; Try to join with a successor block. If we succeed, we return true,
452 ;;; otherwise false.
453 (defun join-successor-if-possible (block)
454   (declare (type cblock block))
455   (let ((next (first (block-succ block))))
456     (when (block-start next)  ; NEXT is not an END-OF-COMPONENT marker
457       (cond ( ;; We cannot combine with a successor block if:
458              (or
459               ;; the successor has more than one predecessor;
460               (rest (block-pred next))
461               ;; the successor is the current block (infinite loop);
462               (eq next block)
463               ;; the next block has a different cleanup, and thus
464               ;; we may want to insert cleanup code between the
465               ;; two blocks at some point;
466               (not (eq (block-end-cleanup block)
467                        (block-start-cleanup next)))
468               ;; the next block has a different home lambda, and
469               ;; thus the control transfer is a non-local exit.
470               (not (eq (block-home-lambda block)
471                        (block-home-lambda next)))
472               ;; Stack analysis phase wants ENTRY to start a block...
473               (entry-p (block-start-node next))
474               (let ((last (block-last block)))
475                 (and (valued-node-p last)
476                      (awhen (node-lvar last)
477                        (or
478                         ;; ... and a DX-allocator to end a block.
479                         (lvar-dynamic-extent it)
480                         ;; FIXME: This is a partial workaround for bug 303.
481                         (consp (lvar-uses it)))))))
482              nil)
483             (t
484              (join-blocks block next)
485              t)))))
486
487 ;;; Join together two blocks. The code in BLOCK2 is moved into BLOCK1
488 ;;; and BLOCK2 is deleted from the DFO. We combine the optimize flags
489 ;;; for the two blocks so that any indicated optimization gets done.
490 (defun join-blocks (block1 block2)
491   (declare (type cblock block1 block2))
492   (let* ((last1 (block-last block1))
493          (last2 (block-last block2))
494          (succ (block-succ block2))
495          (start2 (block-start block2)))
496     (do ((ctran start2 (node-next (ctran-next ctran))))
497         ((not ctran))
498       (setf (ctran-block ctran) block1))
499
500     (unlink-blocks block1 block2)
501     (dolist (block succ)
502       (unlink-blocks block2 block)
503       (link-blocks block1 block))
504
505     (setf (ctran-kind start2) :inside-block)
506     (setf (node-next last1) start2)
507     (setf (ctran-use start2) last1)
508     (setf (block-last block1) last2))
509
510   (setf (block-flags block1)
511         (attributes-union (block-flags block1)
512                           (block-flags block2)
513                           (block-attributes type-asserted test-modified)))
514
515   (let ((next (block-next block2))
516         (prev (block-prev block2)))
517     (setf (block-next prev) next)
518     (setf (block-prev next) prev))
519
520   (values))
521
522 ;;; Delete any nodes in BLOCK whose value is unused and which have no
523 ;;; side effects. We can delete sets of lexical variables when the set
524 ;;; variable has no references.
525 (defun flush-dead-code (block)
526   (declare (type cblock block))
527   (setf (block-flush-p block) nil)
528   (do-nodes-backwards (node lvar block :restart-p t)
529     (unless lvar
530       (typecase node
531         (ref
532          (delete-ref node)
533          (unlink-node node))
534         (combination
535          (when (flushable-combination-p node)
536            (flush-combination node)))
537         (mv-combination
538          (when (eq (basic-combination-kind node) :local)
539            (let ((fun (combination-lambda node)))
540              (when (dolist (var (lambda-vars fun) t)
541                      (when (or (leaf-refs var)
542                                (lambda-var-sets var))
543                        (return nil)))
544                (flush-dest (first (basic-combination-args node)))
545                (delete-let fun)))))
546         (exit
547          (let ((value (exit-value node)))
548            (when value
549              (flush-dest value)
550              (setf (exit-value node) nil))))
551         (cset
552          (let ((var (set-var node)))
553            (when (and (lambda-var-p var)
554                       (null (leaf-refs var)))
555              (flush-dest (set-value node))
556              (setf (basic-var-sets var)
557                    (delq node (basic-var-sets var)))
558              (unlink-node node))))
559         (cast
560          (unless (cast-type-check node)
561            (flush-dest (cast-value node))
562            (unlink-node node))))))
563
564   (values))
565 \f
566 ;;;; local call return type propagation
567
568 ;;; This function is called on RETURN nodes that have their REOPTIMIZE
569 ;;; flag set. It iterates over the uses of the RESULT, looking for
570 ;;; interesting stuff to update the TAIL-SET. If a use isn't a local
571 ;;; call, then we union its type together with the types of other such
572 ;;; uses. We assign to the RETURN-RESULT-TYPE the intersection of this
573 ;;; type with the RESULT's asserted type. We can make this
574 ;;; intersection now (potentially before type checking) because this
575 ;;; assertion on the result will eventually be checked (if
576 ;;; appropriate.)
577 ;;;
578 ;;; We call MAYBE-CONVERT-TAIL-LOCAL-CALL on each local non-MV
579 ;;; combination, which may change the successor of the call to be the
580 ;;; called function, and if so, checks if the call can become an
581 ;;; assignment. If we convert to an assignment, we abort, since the
582 ;;; RETURN has been deleted.
583 (defun find-result-type (node)
584   (declare (type creturn node))
585   (let ((result (return-result node)))
586     (collect ((use-union *empty-type* values-type-union))
587       (do-uses (use result)
588         (let ((use-home (node-home-lambda use)))
589           (cond ((or (eq (functional-kind use-home) :deleted)
590                      (block-delete-p (node-block use))))
591                 ((and (basic-combination-p use)
592                       (eq (basic-combination-kind use) :local))
593                  (aver (eq (lambda-tail-set use-home)
594                            (lambda-tail-set (combination-lambda use))))
595                  (when (combination-p use)
596                    (when (nth-value 1 (maybe-convert-tail-local-call use))
597                      (return-from find-result-type t))))
598                 (t
599                  (use-union (node-derived-type use))))))
600       (let ((int
601              ;; (values-type-intersection
602              ;; (continuation-asserted-type result) ; FIXME -- APD, 2002-01-26
603              (use-union)
604               ;; )
605               ))
606         (setf (return-result-type node) int))))
607   nil)
608
609 ;;; Do stuff to realize that something has changed about the value
610 ;;; delivered to a return node. Since we consider the return values of
611 ;;; all functions in the tail set to be equivalent, this amounts to
612 ;;; bringing the entire tail set up to date. We iterate over the
613 ;;; returns for all the functions in the tail set, reanalyzing them
614 ;;; all (not treating NODE specially.)
615 ;;;
616 ;;; When we are done, we check whether the new type is different from
617 ;;; the old TAIL-SET-TYPE. If so, we set the type and also reoptimize
618 ;;; all the lvars for references to functions in the tail set. This
619 ;;; will cause IR1-OPTIMIZE-COMBINATION to derive the new type as the
620 ;;; results of the calls.
621 (defun ir1-optimize-return (node)
622   (declare (type creturn node))
623   (tagbody
624    :restart
625      (let* ((tails (lambda-tail-set (return-lambda node)))
626             (funs (tail-set-funs tails)))
627        (collect ((res *empty-type* values-type-union))
628                 (dolist (fun funs)
629                   (let ((return (lambda-return fun)))
630                     (when return
631                       (when (node-reoptimize return)
632                         (setf (node-reoptimize return) nil)
633                         (when (find-result-type return)
634                           (go :restart)))
635                       (res (return-result-type return)))))
636
637                 (when (type/= (res) (tail-set-type tails))
638                   (setf (tail-set-type tails) (res))
639                   (dolist (fun (tail-set-funs tails))
640                     (dolist (ref (leaf-refs fun))
641                       (reoptimize-lvar (node-lvar ref))))))))
642
643   (values))
644 \f
645 ;;;; IF optimization
646
647 ;;; Utility: return T if both argument cblocks are equivalent.  For now,
648 ;;; detect only blocks that read the same leaf into the same lvar, and
649 ;;; continue to the same block.
650 (defun cblocks-equivalent-p (x y)
651   (declare (type cblock x y))
652   (and (ref-p (block-start-node x))
653        (eq (block-last x) (block-start-node x))
654
655        (ref-p (block-start-node y))
656        (eq (block-last y) (block-start-node y))
657
658        (equal (block-succ x) (block-succ y))
659        (eql (ref-lvar (block-start-node x)) (ref-lvar (block-start-node y)))
660        (eql (ref-leaf (block-start-node x)) (ref-leaf (block-start-node y)))))
661
662 ;;; Check whether the predicate is known to be true or false,
663 ;;; deleting the IF node in favor of the appropriate branch when this
664 ;;; is the case.
665 ;;; Similarly, when both branches are equivalent, branch directly to either
666 ;;; of them.
667 ;;; Also, if the test has multiple uses, replicate the node when possible...
668 ;;; in fact, splice in direct jumps to the right branch if possible.
669 (defun ir1-optimize-if (node)
670   (declare (type cif node))
671   (let ((test (if-test node))
672         (block (node-block node)))
673     (let* ((type (lvar-type test))
674            (consequent  (if-consequent  node))
675            (alternative (if-alternative node))
676            (victim
677             (cond ((constant-lvar-p test)
678                    (if (lvar-value test) alternative consequent))
679                   ((not (types-equal-or-intersect type (specifier-type 'null)))
680                    alternative)
681                   ((type= type (specifier-type 'null))
682                    consequent)
683                   ((or (eq consequent alternative) ; Can this happen?
684                        (cblocks-equivalent-p alternative consequent))
685                    alternative))))
686       (when victim
687         (kill-if-branch-1 node test block victim)
688         (return-from ir1-optimize-if (values))))
689     (tension-if-if-1 node test block)
690     (duplicate-if-if-1 node test block)
691     (values)))
692
693 ;; When we know that we only have a single successor, kill the victim
694 ;; ... unless the victim and the remaining successor are the same.
695 (defun kill-if-branch-1 (node test block victim)
696   (declare (type cif node))
697   (flush-dest test)
698   (when (rest (block-succ block))
699     (unlink-blocks block victim))
700   (setf (component-reanalyze (node-component node)) t)
701   (unlink-node node))
702
703 ;; When if/if conversion would leave (if ... (if nil ...)) or
704 ;; (if ... (if not-nil ...)), splice the correct successor right
705 ;; in.
706 (defun tension-if-if-1 (node test block)
707   (when (and (eq (block-start-node block) node)
708              (listp (lvar-uses test)))
709     (do-uses (use test)
710       (when (immediately-used-p test use)
711         (let* ((type (single-value-type (node-derived-type use)))
712                (target (if (type= type (specifier-type 'null))
713                            (if-alternative node)
714                            (multiple-value-bind (typep surep)
715                                (ctypep nil type)
716                              (and (not typep) surep
717                                   (if-consequent node))))))
718           (when target
719             (let ((pred (node-block use)))
720               (cond ((listp (lvar-uses test))
721                      (change-block-successor pred block target)
722                      (delete-lvar-use use))
723                     (t
724                      ;; only one use left. Just kill the now-useless
725                      ;; branch to avoid spurious code deletion notes.
726                      (aver (rest (block-succ block)))
727                      (kill-if-branch-1
728                       node test block
729                       (if (eql target (if-alternative node))
730                           (if-consequent node)
731                           (if-alternative node)))
732                      (return-from tension-if-if-1))))))))))
733
734 ;; Finally, duplicate EQ-nil tests
735 (defun duplicate-if-if-1 (node test block)
736   (when (and (eq (block-start-node block) node)
737              (listp (lvar-uses test)))
738     (do-uses (use test)
739       (when (immediately-used-p test use)
740         (convert-if-if use node)
741         ;; leave the last use as is, instead of replacing
742         ;; the (singly-referenced) CIF node with a duplicate.
743         (when (not (listp (lvar-uses test))) (return))))))
744
745 ;;; Create a new copy of an IF node that tests the value of the node
746 ;;; USE. The test must have >1 use, and must be immediately used by
747 ;;; USE. NODE must be the only node in its block (implying that
748 ;;; block-start = if-test).
749 ;;;
750 ;;; This optimization has an effect semantically similar to the
751 ;;; source-to-source transformation:
752 ;;;    (IF (IF A B C) D E) ==>
753 ;;;    (IF A (IF B D E) (IF C D E))
754 ;;;
755 ;;; We clobber the NODE-SOURCE-PATH of both the original and the new
756 ;;; node so that dead code deletion notes will definitely not consider
757 ;;; either node to be part of the original source. One node might
758 ;;; become unreachable, resulting in a spurious note.
759 (defun convert-if-if (use node)
760   (declare (type node use) (type cif node))
761   (with-ir1-environment-from-node node
762     (let* ((block (node-block node))
763            (test (if-test node))
764            (cblock (if-consequent node))
765            (ablock (if-alternative node))
766            (use-block (node-block use))
767            (new-ctran (make-ctran))
768            (new-lvar (make-lvar))
769            (new-node (make-if :test new-lvar
770                               :consequent cblock
771                               :alternative ablock))
772            (new-block (ctran-starts-block new-ctran)))
773       (link-node-to-previous-ctran new-node new-ctran)
774       (setf (lvar-dest new-lvar) new-node)
775       (setf (block-last new-block) new-node)
776
777       (unlink-blocks use-block block)
778       (%delete-lvar-use use)
779       (add-lvar-use use new-lvar)
780       (link-blocks use-block new-block)
781
782       (link-blocks new-block cblock)
783       (link-blocks new-block ablock)
784
785       (push "<IF Duplication>" (node-source-path node))
786       (push "<IF Duplication>" (node-source-path new-node))
787
788       (reoptimize-lvar test)
789       (reoptimize-lvar new-lvar)
790       (setf (component-reanalyze *current-component*) t)))
791   (values))
792 \f
793 ;;;; exit IR1 optimization
794
795 ;;; This function attempts to delete an exit node, returning true if
796 ;;; it deletes the block as a consequence:
797 ;;; -- If the exit is degenerate (has no ENTRY), then we don't do
798 ;;;    anything, since there is nothing to be done.
799 ;;; -- If the exit node and its ENTRY have the same home lambda then
800 ;;;    we know the exit is local, and can delete the exit. We change
801 ;;;    uses of the Exit-Value to be uses of the original lvar,
802 ;;;    then unlink the node. If the exit is to a TR context, then we
803 ;;;    must do MERGE-TAIL-SETS on any local calls which delivered
804 ;;;    their value to this exit.
805 ;;; -- If there is no value (as in a GO), then we skip the value
806 ;;;    semantics.
807 ;;;
808 ;;; This function is also called by environment analysis, since it
809 ;;; wants all exits to be optimized even if normal optimization was
810 ;;; omitted.
811 (defun maybe-delete-exit (node)
812   (declare (type exit node))
813   (let ((value (exit-value node))
814         (entry (exit-entry node)))
815     (when (and entry
816                (eq (node-home-lambda node) (node-home-lambda entry)))
817       (setf (entry-exits entry) (delq node (entry-exits entry)))
818       (if value
819           (delete-filter node (node-lvar node) value)
820           (unlink-node node)))))
821
822 \f
823 ;;;; combination IR1 optimization
824
825 ;;; Report as we try each transform?
826 #!+sb-show
827 (defvar *show-transforms-p* nil)
828
829 (defun check-important-result (node info)
830   (when (and (null (node-lvar node))
831              (ir1-attributep (fun-info-attributes info) important-result))
832     (let ((*compiler-error-context* node))
833       (compiler-style-warn
834        "The return value of ~A should not be discarded."
835        (lvar-fun-name (basic-combination-fun node))))))
836
837 ;;; Do IR1 optimizations on a COMBINATION node.
838 (declaim (ftype (function (combination) (values)) ir1-optimize-combination))
839 (defun ir1-optimize-combination (node)
840   (when (lvar-reoptimize (basic-combination-fun node))
841     (propagate-fun-change node)
842     (maybe-terminate-block node nil))
843   (let ((args (basic-combination-args node))
844         (kind (basic-combination-kind node))
845         (info (basic-combination-fun-info node)))
846     (ecase kind
847       (:local
848        (let ((fun (combination-lambda node)))
849          (if (eq (functional-kind fun) :let)
850              (propagate-let-args node fun)
851              (propagate-local-call-args node fun))))
852       (:error
853        (dolist (arg args)
854          (when arg
855            (setf (lvar-reoptimize arg) nil))))
856       (:full
857        (dolist (arg args)
858          (when arg
859            (setf (lvar-reoptimize arg) nil)))
860        (cond (info
861               (check-important-result node info)
862               (let ((fun (fun-info-destroyed-constant-args info)))
863                 (when fun
864                   (let ((destroyed-constant-args (funcall fun args)))
865                     (when destroyed-constant-args
866                       (let ((*compiler-error-context* node))
867                         (warn 'constant-modified
868                               :fun-name (lvar-fun-name
869                                          (basic-combination-fun node)))
870                         (setf (basic-combination-kind node) :error)
871                         (return-from ir1-optimize-combination))))))
872               (let ((fun (fun-info-derive-type info)))
873                 (when fun
874                   (let ((res (funcall fun node)))
875                     (when res
876                       (derive-node-type node (coerce-to-values res))
877                       (maybe-terminate-block node nil))))))
878              (t
879               ;; Check against the DEFINED-TYPE unless TYPE is already good.
880               (let* ((fun (basic-combination-fun node))
881                      (uses (lvar-uses fun))
882                      (leaf (when (ref-p uses) (ref-leaf uses))))
883                 (multiple-value-bind (type defined-type)
884                     (if (global-var-p leaf)
885                         (values (leaf-type leaf) (leaf-defined-type leaf))
886                         (values nil nil))
887                   (when (and (not (fun-type-p type)) (fun-type-p defined-type))
888                     (validate-call-type node type leaf)))))))
889       (:known
890        (aver info)
891        (dolist (arg args)
892          (when arg
893            (setf (lvar-reoptimize arg) nil)))
894        (check-important-result node info)
895        (let ((fun (fun-info-destroyed-constant-args info)))
896          (when (and fun
897                     ;; If somebody is really sure that they want to modify
898                     ;; constants, let them.
899                     (policy node (> check-constant-modification 0)))
900            (let ((destroyed-constant-args (funcall fun args)))
901              (when destroyed-constant-args
902                (let ((*compiler-error-context* node))
903                  (warn 'constant-modified
904                        :fun-name (lvar-fun-name
905                                   (basic-combination-fun node)))
906                  (setf (basic-combination-kind node) :error)
907                  (return-from ir1-optimize-combination))))))
908
909        (let ((attr (fun-info-attributes info)))
910          (when (and (ir1-attributep attr foldable)
911                     ;; KLUDGE: The next test could be made more sensitive,
912                     ;; only suppressing constant-folding of functions with
913                     ;; CALL attributes when they're actually passed
914                     ;; function arguments. -- WHN 19990918
915                     (not (ir1-attributep attr call))
916                     (every #'constant-lvar-p args)
917                     (node-lvar node))
918            (constant-fold-call node)
919            (return-from ir1-optimize-combination)))
920
921        (let ((fun (fun-info-derive-type info)))
922          (when fun
923            (let ((res (funcall fun node)))
924              (when res
925                (derive-node-type node (coerce-to-values res))
926                (maybe-terminate-block node nil)))))
927
928        (let ((fun (fun-info-optimizer info)))
929          (unless (and fun (funcall fun node))
930            ;; First give the VM a peek at the call
931            (multiple-value-bind (style transform)
932                (combination-implementation-style node)
933              (ecase style
934                (:direct
935                 ;; The VM knows how to handle this.
936                 )
937                (:transform
938                 ;; The VM mostly knows how to handle this.  We need
939                 ;; to massage the call slightly, though.
940                 (transform-call node transform (combination-fun-source-name node)))
941                ((:default :maybe)
942                 ;; Let transforms have a crack at it.
943                 (dolist (x (fun-info-transforms info))
944                   #!+sb-show
945                   (when *show-transforms-p*
946                     (let* ((lvar (basic-combination-fun node))
947                            (fname (lvar-fun-name lvar t)))
948                       (/show "trying transform" x (transform-function x) "for" fname)))
949                   (unless (ir1-transform node x)
950                     #!+sb-show
951                     (when *show-transforms-p*
952                       (/show "quitting because IR1-TRANSFORM result was NIL"))
953                     (return)))))))))))
954
955   (values))
956
957 (defun xep-tail-combination-p (node)
958   (and (combination-p node)
959        (let* ((lvar (combination-lvar node))
960               (dest (when (lvar-p lvar) (lvar-dest lvar)))
961               (lambda (when (return-p dest) (return-lambda dest))))
962          (and (lambda-p lambda)
963               (eq :external (lambda-kind lambda))))))
964
965 ;;; If NODE doesn't return (i.e. return type is NIL), then terminate
966 ;;; the block there, and link it to the component tail.
967 ;;;
968 ;;; Except when called during IR1 convertion, we delete the
969 ;;; continuation if it has no other uses. (If it does have other uses,
970 ;;; we reoptimize.)
971 ;;;
972 ;;; Termination on the basis of a continuation type is
973 ;;; inhibited when:
974 ;;; -- The continuation is deleted (hence the assertion is spurious), or
975 ;;; -- We are in IR1 conversion (where THE assertions are subject to
976 ;;;    weakening.) FIXME: Now THE assertions are not weakened, but new
977 ;;;    uses can(?) be added later. -- APD, 2003-07-17
978 ;;;
979 ;;; Why do we need to consider LVAR type? -- APD, 2003-07-30
980 (defun maybe-terminate-block (node ir1-converting-not-optimizing-p)
981   (declare (type (or basic-combination cast ref) node))
982   (let* ((block (node-block node))
983          (lvar (node-lvar node))
984          (ctran (node-next node))
985          (tail (component-tail (block-component block)))
986          (succ (first (block-succ block))))
987     (declare (ignore lvar))
988     (unless (or (and (eq node (block-last block)) (eq succ tail))
989                 (block-delete-p block))
990       ;; Even if the combination will never return, don't terminate if this
991       ;; is the tail call of a XEP: doing that would inhibit TCO.
992       (when (and (eq (node-derived-type node) *empty-type*)
993                  (not (xep-tail-combination-p node)))
994         (cond (ir1-converting-not-optimizing-p
995                (cond
996                  ((block-last block)
997                   (aver (eq (block-last block) node)))
998                  (t
999                   (setf (block-last block) node)
1000                   (setf (ctran-use ctran) nil)
1001                   (setf (ctran-kind ctran) :unused)
1002                   (setf (ctran-block ctran) nil)
1003                   (setf (node-next node) nil)
1004                   (link-blocks block (ctran-starts-block ctran)))))
1005               (t
1006                (node-ends-block node)))
1007
1008         (let ((succ (first (block-succ block))))
1009           (unlink-blocks block succ)
1010           (setf (component-reanalyze (block-component block)) t)
1011           (aver (not (block-succ block)))
1012           (link-blocks block tail)
1013           (cond (ir1-converting-not-optimizing-p
1014                  (%delete-lvar-use node))
1015                 (t (delete-lvar-use node)
1016                    (when (null (block-pred succ))
1017                      (mark-for-deletion succ)))))
1018         t))))
1019
1020 ;;; This is called both by IR1 conversion and IR1 optimization when
1021 ;;; they have verified the type signature for the call, and are
1022 ;;; wondering if something should be done to special-case the call. If
1023 ;;; CALL is a call to a global function, then see whether it defined
1024 ;;; or known:
1025 ;;; -- If a DEFINED-FUN should be inline expanded, then convert
1026 ;;;    the expansion and change the call to call it. Expansion is
1027 ;;;    enabled if :INLINE or if SPACE=0. If the FUNCTIONAL slot is
1028 ;;;    true, we never expand, since this function has already been
1029 ;;;    converted. Local call analysis will duplicate the definition
1030 ;;;    if necessary. We claim that the parent form is LABELS for
1031 ;;;    context declarations, since we don't want it to be considered
1032 ;;;    a real global function.
1033 ;;; -- If it is a known function, mark it as such by setting the KIND.
1034 ;;;
1035 ;;; We return the leaf referenced (NIL if not a leaf) and the
1036 ;;; FUN-INFO assigned.
1037 (defun recognize-known-call (call ir1-converting-not-optimizing-p)
1038   (declare (type combination call))
1039   (let* ((ref (lvar-uses (basic-combination-fun call)))
1040          (leaf (when (ref-p ref) (ref-leaf ref)))
1041          (inlinep (if (defined-fun-p leaf)
1042                       (defined-fun-inlinep leaf)
1043                       :no-chance)))
1044     (cond
1045      ((eq inlinep :notinline)
1046       (let ((info (info :function :info (leaf-source-name leaf))))
1047         (when info
1048           (setf (basic-combination-fun-info call) info))
1049         (values nil nil)))
1050      ((not (and (global-var-p leaf)
1051                 (eq (global-var-kind leaf) :global-function)))
1052       (values leaf nil))
1053      ((and (ecase inlinep
1054              (:inline t)
1055              (:no-chance nil)
1056              ((nil :maybe-inline) (policy call (zerop space))))
1057            (defined-fun-p leaf)
1058            (defined-fun-inline-expansion leaf)
1059            (inline-expansion-ok call))
1060       ;; Inline: if the function has already been converted at another call
1061       ;; site in this component, we point this REF to the functional. If not,
1062       ;; we convert the expansion.
1063       ;;
1064       ;; For :INLINE case local call analysis will copy the expansion later,
1065       ;; but for :MAYBE-INLINE and NIL cases we only get one copy of the
1066       ;; expansion per component.
1067       ;;
1068       ;; FIXME: We also convert in :INLINE & FUNCTIONAL-KIND case below. What
1069       ;; is it for?
1070       (flet ((frob ()
1071                (let* ((name (leaf-source-name leaf))
1072                       (res (ir1-convert-inline-expansion
1073                             name
1074                             (defined-fun-inline-expansion leaf)
1075                             leaf
1076                             inlinep
1077                             (info :function :info name))))
1078                  ;; Allow backward references to this function from following
1079                  ;; forms. (Reused only if policy matches.)
1080                  (push res (defined-fun-functionals leaf))
1081                  (change-ref-leaf ref res))))
1082         (let ((fun (defined-fun-functional leaf)))
1083           (if (or (not fun)
1084                   (and (eq inlinep :inline) (functional-kind fun)))
1085               ;; Convert.
1086               (if ir1-converting-not-optimizing-p
1087                   (frob)
1088                   (with-ir1-environment-from-node call
1089                     (frob)
1090                     (locall-analyze-component *current-component*)))
1091               ;; If we've already converted, change ref to the converted
1092               ;; functional.
1093               (change-ref-leaf ref fun))))
1094       (values (ref-leaf ref) nil))
1095      (t
1096       (let ((info (info :function :info (leaf-source-name leaf))))
1097         (if info
1098             (values leaf
1099                     (progn
1100                       (setf (basic-combination-kind call) :known)
1101                       (setf (basic-combination-fun-info call) info)))
1102             (values leaf nil)))))))
1103
1104 ;;; Check whether CALL satisfies TYPE. If so, apply the type to the
1105 ;;; call, and do MAYBE-TERMINATE-BLOCK and return the values of
1106 ;;; RECOGNIZE-KNOWN-CALL. If an error, set the combination kind and
1107 ;;; return NIL, NIL. If the type is just FUNCTION, then skip the
1108 ;;; syntax check, arg/result type processing, but still call
1109 ;;; RECOGNIZE-KNOWN-CALL, since the call might be to a known lambda,
1110 ;;; and that checking is done by local call analysis.
1111 (defun validate-call-type (call type fun &optional ir1-converting-not-optimizing-p)
1112   (declare (type combination call) (type ctype type))
1113   (let* ((where (when fun (leaf-where-from fun)))
1114          (same-file-p (eq :defined-here where)))
1115     (cond ((not (fun-type-p type))
1116            (aver (multiple-value-bind (val win)
1117                      (csubtypep type (specifier-type 'function))
1118                    (or val (not win))))
1119            ;; Using the defined-type too early is a bit of a waste: during
1120            ;; conversion we cannot use the untrusted ASSERT-CALL-TYPE, etc.
1121            (when (and fun (not ir1-converting-not-optimizing-p))
1122              (let ((defined-type (leaf-defined-type fun)))
1123                (when (and (fun-type-p defined-type)
1124                           (neq fun (combination-type-validated-for-leaf call)))
1125                  ;; Don't validate multiple times against the same leaf --
1126                  ;; it doesn't add any information, but may generate the same warning
1127                  ;; multiple times.
1128                  (setf (combination-type-validated-for-leaf call) fun)
1129                  (when (and (valid-fun-use call defined-type
1130                                            :argument-test #'always-subtypep
1131                                            :result-test nil
1132                                            :lossage-fun (if same-file-p
1133                                                             #'compiler-warn
1134                                                             #'compiler-style-warn)
1135                                            :unwinnage-fun #'compiler-notify)
1136                             same-file-p)
1137                    (assert-call-type call defined-type nil)
1138                    (maybe-terminate-block call ir1-converting-not-optimizing-p)))))
1139            (recognize-known-call call ir1-converting-not-optimizing-p))
1140           ((valid-fun-use call type
1141                           :argument-test #'always-subtypep
1142                           :result-test nil
1143                           :lossage-fun #'compiler-warn
1144                           :unwinnage-fun #'compiler-notify)
1145            (assert-call-type call type)
1146            (maybe-terminate-block call ir1-converting-not-optimizing-p)
1147            (recognize-known-call call ir1-converting-not-optimizing-p))
1148           (t
1149            (setf (combination-kind call) :error)
1150            (values nil nil)))))
1151
1152 ;;; This is called by IR1-OPTIMIZE when the function for a call has
1153 ;;; changed. If the call is local, we try to LET-convert it, and
1154 ;;; derive the result type. If it is a :FULL call, we validate it
1155 ;;; against the type, which recognizes known calls, does inline
1156 ;;; expansion, etc. If a call to a predicate in a non-conditional
1157 ;;; position or to a function with a source transform, then we
1158 ;;; reconvert the form to give IR1 another chance.
1159 (defun propagate-fun-change (call)
1160   (declare (type combination call))
1161   (let ((*compiler-error-context* call)
1162         (fun-lvar (basic-combination-fun call)))
1163     (setf (lvar-reoptimize fun-lvar) nil)
1164     (case (combination-kind call)
1165       (:local
1166        (let ((fun (combination-lambda call)))
1167          (maybe-let-convert fun)
1168          (unless (member (functional-kind fun) '(:let :assignment :deleted))
1169            (derive-node-type call (tail-set-type (lambda-tail-set fun))))))
1170       (:full
1171        (multiple-value-bind (leaf info)
1172            (let* ((uses (lvar-uses fun-lvar))
1173                   (leaf (when (ref-p uses) (ref-leaf uses))))
1174              (validate-call-type call (lvar-type fun-lvar) leaf))
1175          (cond ((functional-p leaf)
1176                 (convert-call-if-possible
1177                  (lvar-uses (basic-combination-fun call))
1178                  call))
1179                ((not leaf))
1180                ((and (global-var-p leaf)
1181                      (eq (global-var-kind leaf) :global-function)
1182                      (leaf-has-source-name-p leaf)
1183                      (or (info :function :source-transform (leaf-source-name leaf))
1184                          (and info
1185                               (ir1-attributep (fun-info-attributes info)
1186                                               predicate)
1187                               (let ((lvar (node-lvar call)))
1188                                 (and lvar (not (if-p (lvar-dest lvar))))))))
1189                 (let ((name (leaf-source-name leaf))
1190                       (dummies (make-gensym-list
1191                                 (length (combination-args call)))))
1192                   (transform-call call
1193                                   `(lambda ,dummies
1194                                      (,@(if (symbolp name)
1195                                             `(,name)
1196                                             `(funcall #',name))
1197                                         ,@dummies))
1198                                   (leaf-source-name leaf)))))))))
1199   (values))
1200 \f
1201 ;;;; known function optimization
1202
1203 ;;; Add a failed optimization note to FAILED-OPTIMZATIONS for NODE,
1204 ;;; FUN and ARGS. If there is already a note for NODE and TRANSFORM,
1205 ;;; replace it, otherwise add a new one.
1206 (defun record-optimization-failure (node transform args)
1207   (declare (type combination node) (type transform transform)
1208            (type (or fun-type list) args))
1209   (let* ((table (component-failed-optimizations *component-being-compiled*))
1210          (found (assoc transform (gethash node table))))
1211     (if found
1212         (setf (cdr found) args)
1213         (push (cons transform args) (gethash node table))))
1214   (values))
1215
1216 ;;; Attempt to transform NODE using TRANSFORM-FUNCTION, subject to the
1217 ;;; call type constraint TRANSFORM-TYPE. If we are inhibited from
1218 ;;; doing the transform for some reason and FLAME is true, then we
1219 ;;; make a note of the message in FAILED-OPTIMIZATIONS for IR1
1220 ;;; finalize to pick up. We return true if the transform failed, and
1221 ;;; thus further transformation should be attempted. We return false
1222 ;;; if either the transform succeeded or was aborted.
1223 (defun ir1-transform (node transform)
1224   (declare (type combination node) (type transform transform))
1225   (let* ((type (transform-type transform))
1226          (fun (transform-function transform))
1227          (constrained (fun-type-p type))
1228          (table (component-failed-optimizations *component-being-compiled*))
1229          (flame (if (transform-important transform)
1230                     (policy node (>= speed inhibit-warnings))
1231                     (policy node (> speed inhibit-warnings))))
1232          (*compiler-error-context* node))
1233     (cond ((or (not constrained)
1234                (valid-fun-use node type))
1235            (multiple-value-bind (severity args)
1236                (catch 'give-up-ir1-transform
1237                  (transform-call node
1238                                  (funcall fun node)
1239                                  (combination-fun-source-name node))
1240                  (values :none nil))
1241              (ecase severity
1242                (:none
1243                 (remhash node table)
1244                 nil)
1245                (:aborted
1246                 (setf (combination-kind node) :error)
1247                 (when args
1248                   (apply #'warn args))
1249                 (remhash node table)
1250                 nil)
1251                (:failure
1252                 (if args
1253                     (when flame
1254                       (record-optimization-failure node transform args))
1255                     (setf (gethash node table)
1256                           (remove transform (gethash node table) :key #'car)))
1257                 t)
1258                (:delayed
1259                  (remhash node table)
1260                  nil))))
1261           ((and flame
1262                 (valid-fun-use node
1263                                type
1264                                :argument-test #'types-equal-or-intersect
1265                                :result-test #'values-types-equal-or-intersect))
1266            (record-optimization-failure node transform type)
1267            t)
1268           (t
1269            t))))
1270
1271 ;;; When we don't like an IR1 transform, we throw the severity/reason
1272 ;;; and args.
1273 ;;;
1274 ;;; GIVE-UP-IR1-TRANSFORM is used to throw out of an IR1 transform,
1275 ;;; aborting this attempt to transform the call, but admitting the
1276 ;;; possibility that this or some other transform will later succeed.
1277 ;;; If arguments are supplied, they are format arguments for an
1278 ;;; efficiency note.
1279 ;;;
1280 ;;; ABORT-IR1-TRANSFORM is used to throw out of an IR1 transform and
1281 ;;; force a normal call to the function at run time. No further
1282 ;;; optimizations will be attempted.
1283 ;;;
1284 ;;; DELAY-IR1-TRANSFORM is used to throw out of an IR1 transform, and
1285 ;;; delay the transform on the node until later. REASONS specifies
1286 ;;; when the transform will be later retried. The :OPTIMIZE reason
1287 ;;; causes the transform to be delayed until after the current IR1
1288 ;;; optimization pass. The :CONSTRAINT reason causes the transform to
1289 ;;; be delayed until after constraint propagation.
1290 ;;;
1291 ;;; FIXME: Now (0.6.11.44) that there are 4 variants of this (GIVE-UP,
1292 ;;; ABORT, DELAY/:OPTIMIZE, DELAY/:CONSTRAINT) and we're starting to
1293 ;;; do CASE operations on the various REASON values, it might be a
1294 ;;; good idea to go OO, representing the reasons by objects, using
1295 ;;; CLOS methods on the objects instead of CASE, and (possibly) using
1296 ;;; SIGNAL instead of THROW.
1297 (declaim (ftype (function (&rest t) nil) give-up-ir1-transform))
1298 (defun give-up-ir1-transform (&rest args)
1299   (throw 'give-up-ir1-transform (values :failure args)))
1300 (defun abort-ir1-transform (&rest args)
1301   (throw 'give-up-ir1-transform (values :aborted args)))
1302 (defun delay-ir1-transform (node &rest reasons)
1303   (let ((assoc (assoc node *delayed-ir1-transforms*)))
1304     (cond ((not assoc)
1305             (setf *delayed-ir1-transforms*
1306                     (acons node reasons *delayed-ir1-transforms*))
1307             (throw 'give-up-ir1-transform :delayed))
1308           ((cdr assoc)
1309             (dolist (reason reasons)
1310               (pushnew reason (cdr assoc)))
1311             (throw 'give-up-ir1-transform :delayed)))))
1312
1313 ;;; Clear any delayed transform with no reasons - these should have
1314 ;;; been tried in the last pass. Then remove the reason from the
1315 ;;; delayed transform reasons, and if any become empty then set
1316 ;;; reoptimize flags for the node. Return true if any transforms are
1317 ;;; to be retried.
1318 (defun retry-delayed-ir1-transforms (reason)
1319   (setf *delayed-ir1-transforms*
1320         (remove-if-not #'cdr *delayed-ir1-transforms*))
1321   (let ((reoptimize nil))
1322     (dolist (assoc *delayed-ir1-transforms*)
1323       (let ((reasons (remove reason (cdr assoc))))
1324         (setf (cdr assoc) reasons)
1325         (unless reasons
1326           (let ((node (car assoc)))
1327             (unless (node-deleted node)
1328               (setf reoptimize t)
1329               (setf (node-reoptimize node) t)
1330               (let ((block (node-block node)))
1331                 (setf (block-reoptimize block) t)
1332                 (reoptimize-component (block-component block) :maybe)))))))
1333     reoptimize))
1334
1335 ;;; Take the lambda-expression RES, IR1 convert it in the proper
1336 ;;; environment, and then install it as the function for the call
1337 ;;; NODE. We do local call analysis so that the new function is
1338 ;;; integrated into the control flow.
1339 ;;;
1340 ;;; We require the original function source name in order to generate
1341 ;;; a meaningful debug name for the lambda we set up. (It'd be
1342 ;;; possible to do this starting from debug names as well as source
1343 ;;; names, but as of sbcl-0.7.1.5, there was no need for this
1344 ;;; generality, since source names are always known to our callers.)
1345 (defun transform-call (call res source-name)
1346   (declare (type combination call) (list res))
1347   (aver (and (legal-fun-name-p source-name)
1348              (not (eql source-name '.anonymous.))))
1349   (node-ends-block call)
1350   ;; The internal variables of a transform are not going to be
1351   ;; interesting to the debugger, so there's no sense in
1352   ;; suppressing the substitution of variables with only one use
1353   ;; (the extra variables can slow down constraint propagation).
1354   ;;
1355   ;; This needs to be done before the WITH-IR1-ENVIRONMENT-FROM-NODE,
1356   ;; so that it will bind *LEXENV* to the right environment.
1357   (setf (combination-lexenv call)
1358         (make-lexenv :default (combination-lexenv call)
1359                      :policy (process-optimize-decl
1360                               '(optimize
1361                                 (preserve-single-use-debug-variables 0))
1362                               (lexenv-policy
1363                                (combination-lexenv call)))))
1364   (with-ir1-environment-from-node call
1365     (with-component-last-block (*current-component*
1366                                 (block-next (node-block call)))
1367
1368       (let ((new-fun (ir1-convert-inline-lambda
1369                       res
1370                       :debug-name (debug-name 'lambda-inlined source-name)
1371                       :system-lambda t))
1372             (ref (lvar-use (combination-fun call))))
1373         (change-ref-leaf ref new-fun)
1374         (setf (combination-kind call) :full)
1375         (locall-analyze-component *current-component*))))
1376   (values))
1377
1378 ;;; Replace a call to a foldable function of constant arguments with
1379 ;;; the result of evaluating the form. If there is an error during the
1380 ;;; evaluation, we give a warning and leave the call alone, making the
1381 ;;; call a :ERROR call.
1382 ;;;
1383 ;;; If there is more than one value, then we transform the call into a
1384 ;;; VALUES form.
1385 (defun constant-fold-call (call)
1386   (let ((args (mapcar #'lvar-value (combination-args call)))
1387         (fun-name (combination-fun-source-name call)))
1388     (multiple-value-bind (values win)
1389         (careful-call fun-name
1390                       args
1391                       call
1392                       ;; Note: CMU CL had COMPILER-WARN here, and that
1393                       ;; seems more natural, but it's probably not.
1394                       ;;
1395                       ;; It's especially not while bug 173 exists:
1396                       ;; Expressions like
1397                       ;;   (COND (END
1398                       ;;          (UNLESS (OR UNSAFE? (<= END SIZE)))
1399                       ;;            ...))
1400                       ;; can cause constant-folding TYPE-ERRORs (in
1401                       ;; #'<=) when END can be proved to be NIL, even
1402                       ;; though the code is perfectly legal and safe
1403                       ;; because a NIL value of END means that the
1404                       ;; #'<= will never be executed.
1405                       ;;
1406                       ;; Moreover, even without bug 173,
1407                       ;; quite-possibly-valid code like
1408                       ;;   (COND ((NONINLINED-PREDICATE END)
1409                       ;;          (UNLESS (<= END SIZE))
1410                       ;;            ...))
1411                       ;; (where NONINLINED-PREDICATE is something the
1412                       ;; compiler can't do at compile time, but which
1413                       ;; turns out to make the #'<= expression
1414                       ;; unreachable when END=NIL) could cause errors
1415                       ;; when the compiler tries to constant-fold (<=
1416                       ;; END SIZE).
1417                       ;;
1418                       ;; So, with or without bug 173, it'd be
1419                       ;; unnecessarily evil to do a full
1420                       ;; COMPILER-WARNING (and thus return FAILURE-P=T
1421                       ;; from COMPILE-FILE) for legal code, so we we
1422                       ;; use a wimpier COMPILE-STYLE-WARNING instead.
1423                       #-sb-xc-host #'compiler-style-warn
1424                       ;; On the other hand, for code we control, we
1425                       ;; should be able to work around any bug
1426                       ;; 173-related problems, and in particular we
1427                       ;; want to be alerted to calls to our own
1428                       ;; functions which aren't being folded away; a
1429                       ;; COMPILER-WARNING is butch enough to stop the
1430                       ;; SBCL build itself in its tracks.
1431                       #+sb-xc-host #'compiler-warn
1432                       "constant folding")
1433       (cond ((not win)
1434              (setf (combination-kind call) :error))
1435             ((and (proper-list-of-length-p values 1))
1436              (with-ir1-environment-from-node call
1437                (let* ((lvar (node-lvar call))
1438                       (prev (node-prev call))
1439                       (intermediate-ctran (make-ctran)))
1440                  (%delete-lvar-use call)
1441                  (setf (ctran-next prev) nil)
1442                  (setf (node-prev call) nil)
1443                  (reference-constant prev intermediate-ctran lvar
1444                                      (first values))
1445                  (link-node-to-previous-ctran call intermediate-ctran)
1446                  (reoptimize-lvar lvar)
1447                  (flush-combination call))))
1448             (t (let ((dummies (make-gensym-list (length args))))
1449                  (transform-call
1450                   call
1451                   `(lambda ,dummies
1452                      (declare (ignore ,@dummies))
1453                      (values ,@(mapcar (lambda (x) `',x) values)))
1454                   fun-name))))))
1455   (values))
1456 \f
1457 ;;;; local call optimization
1458
1459 ;;; Propagate TYPE to LEAF and its REFS, marking things changed.
1460 ;;;
1461 ;;; If the leaf type is a function type, then just leave it alone, since TYPE
1462 ;;; is never going to be more specific than that (and TYPE-INTERSECTION would
1463 ;;; choke.)
1464 ;;;
1465 ;;; Also, if the type is one requiring special care don't touch it if the leaf
1466 ;;; has multiple references -- otherwise LVAR-CONSERVATIVE-TYPE is screwed.
1467 (defun propagate-to-refs (leaf type)
1468   (declare (type leaf leaf) (type ctype type))
1469   (let ((var-type (leaf-type leaf))
1470         (refs (leaf-refs leaf)))
1471     (unless (or (fun-type-p var-type)
1472                 (and (cdr refs)
1473                      (eq :declared (leaf-where-from leaf))
1474                      (type-needs-conservation-p var-type)))
1475       (let ((int (type-approx-intersection2 var-type type)))
1476         (when (type/= int var-type)
1477           (setf (leaf-type leaf) int)
1478           (let ((s-int (make-single-value-type int)))
1479             (dolist (ref refs)
1480               (derive-node-type ref s-int)
1481               ;; KLUDGE: LET var substitution
1482               (let* ((lvar (node-lvar ref)))
1483                 (when (and lvar (combination-p (lvar-dest lvar)))
1484                   (reoptimize-lvar lvar)))))))
1485       (values))))
1486
1487 ;;; Iteration variable: exactly one SETQ of the form:
1488 ;;;
1489 ;;; (let ((var initial))
1490 ;;;   ...
1491 ;;;   (setq var (+ var step))
1492 ;;;   ...)
1493 (defun maybe-infer-iteration-var-type (var initial-type)
1494   (binding* ((sets (lambda-var-sets var) :exit-if-null)
1495              (set (first sets))
1496              (() (null (rest sets)) :exit-if-null)
1497              (set-use (principal-lvar-use (set-value set)))
1498              (() (and (combination-p set-use)
1499                       (eq (combination-kind set-use) :known)
1500                       (fun-info-p (combination-fun-info set-use))
1501                       (not (node-to-be-deleted-p set-use))
1502                       (or (eq (combination-fun-source-name set-use) '+)
1503                           (eq (combination-fun-source-name set-use) '-)))
1504               :exit-if-null)
1505              (minusp (eq (combination-fun-source-name set-use) '-))
1506              (+-args (basic-combination-args set-use))
1507              (() (and (proper-list-of-length-p +-args 2 2)
1508                       (let ((first (principal-lvar-use
1509                                     (first +-args))))
1510                         (and (ref-p first)
1511                              (eq (ref-leaf first) var))))
1512               :exit-if-null)
1513              (step-type (lvar-type (second +-args)))
1514              (set-type (lvar-type (set-value set))))
1515     (when (and (numeric-type-p initial-type)
1516                (numeric-type-p step-type)
1517                (or (numeric-type-equal initial-type step-type)
1518                    ;; Detect cases like (LOOP FOR 1.0 to 5.0 ...), where
1519                    ;; the initial and the step are of different types,
1520                    ;; and the step is less contagious.
1521                    (numeric-type-equal initial-type
1522                                        (numeric-contagion initial-type
1523                                                           step-type))))
1524       (labels ((leftmost (x y cmp cmp=)
1525                  (cond ((eq x nil) nil)
1526                        ((eq y nil) nil)
1527                        ((listp x)
1528                         (let ((x1 (first x)))
1529                           (cond ((listp y)
1530                                  (let ((y1 (first y)))
1531                                    (if (funcall cmp x1 y1) x y)))
1532                                 (t
1533                                  (if (funcall cmp x1 y) x y)))))
1534                        ((listp y)
1535                         (let ((y1 (first y)))
1536                           (if (funcall cmp= x y1) x y)))
1537                        (t (if (funcall cmp x y) x y))))
1538                (max* (x y) (leftmost x y #'> #'>=))
1539                (min* (x y) (leftmost x y #'< #'<=)))
1540         (multiple-value-bind (low high)
1541             (let ((step-type-non-negative (csubtypep step-type (specifier-type
1542                                                                 '(real 0 *))))
1543                   (step-type-non-positive (csubtypep step-type (specifier-type
1544                                                                 '(real * 0)))))
1545               (cond ((or (and step-type-non-negative (not minusp))
1546                          (and step-type-non-positive minusp))
1547                      (values (numeric-type-low initial-type)
1548                              (when (and (numeric-type-p set-type)
1549                                         (numeric-type-equal set-type initial-type))
1550                                (max* (numeric-type-high initial-type)
1551                                      (numeric-type-high set-type)))))
1552                     ((or (and step-type-non-positive (not minusp))
1553                          (and step-type-non-negative minusp))
1554                      (values (when (and (numeric-type-p set-type)
1555                                         (numeric-type-equal set-type initial-type))
1556                                (min* (numeric-type-low initial-type)
1557                                      (numeric-type-low set-type)))
1558                              (numeric-type-high initial-type)))
1559                     (t
1560                      (values nil nil))))
1561           (modified-numeric-type initial-type
1562                                  :low low
1563                                  :high high
1564                                  :enumerable nil))))))
1565 (deftransform + ((x y) * * :result result)
1566   "check for iteration variable reoptimization"
1567   (let ((dest (principal-lvar-end result))
1568         (use (principal-lvar-use x)))
1569     (when (and (ref-p use)
1570                (set-p dest)
1571                (eq (ref-leaf use)
1572                    (set-var dest)))
1573       (reoptimize-lvar (set-value dest))))
1574   (give-up-ir1-transform))
1575
1576 ;;; Figure out the type of a LET variable that has sets. We compute
1577 ;;; the union of the INITIAL-TYPE and the types of all the set
1578 ;;; values and to a PROPAGATE-TO-REFS with this type.
1579 (defun propagate-from-sets (var initial-type)
1580   (let ((changes (not (csubtypep (lambda-var-last-initial-type var) initial-type)))
1581         (types nil))
1582     (dolist (set (lambda-var-sets var))
1583       (let ((type (lvar-type (set-value set))))
1584         (push type types)
1585         (when (node-reoptimize set)
1586           (let ((old-type (node-derived-type set)))
1587             (unless (values-subtypep old-type type)
1588               (derive-node-type set (make-single-value-type type))
1589               (setf changes t)))
1590           (setf (node-reoptimize set) nil))))
1591     (when changes
1592       (setf (lambda-var-last-initial-type var) initial-type)
1593       (let ((res-type (or (maybe-infer-iteration-var-type var initial-type)
1594                           (apply #'type-union initial-type types))))
1595         (propagate-to-refs var res-type))))
1596   (values))
1597
1598 ;;; If a LET variable, find the initial value's type and do
1599 ;;; PROPAGATE-FROM-SETS. We also derive the VALUE's type as the node's
1600 ;;; type.
1601 (defun ir1-optimize-set (node)
1602   (declare (type cset node))
1603   (let ((var (set-var node)))
1604     (when (and (lambda-var-p var) (leaf-refs var))
1605       (let ((home (lambda-var-home var)))
1606         (when (eq (functional-kind home) :let)
1607           (let* ((initial-value (let-var-initial-value var))
1608                  (initial-type (lvar-type initial-value)))
1609             (setf (lvar-reoptimize initial-value) nil)
1610             (propagate-from-sets var initial-type))))))
1611   (derive-node-type node (make-single-value-type
1612                           (lvar-type (set-value node))))
1613   (setf (node-reoptimize node) nil)
1614   (values))
1615
1616 ;;; Return true if the value of REF will always be the same (and is
1617 ;;; thus legal to substitute.)
1618 (defun constant-reference-p (ref)
1619   (declare (type ref ref))
1620   (let ((leaf (ref-leaf ref)))
1621     (typecase leaf
1622       ((or constant functional) t)
1623       (lambda-var
1624        (null (lambda-var-sets leaf)))
1625       (defined-fun
1626        (not (eq (defined-fun-inlinep leaf) :notinline)))
1627       (global-var
1628        (case (global-var-kind leaf)
1629          (:global-function
1630           (let ((name (leaf-source-name leaf)))
1631             (or #-sb-xc-host
1632                 (eq (symbol-package (fun-name-block-name name))
1633                     *cl-package*)
1634                 (info :function :info name)))))))))
1635
1636 ;;; If we have a non-set LET var with a single use, then (if possible)
1637 ;;; replace the variable reference's LVAR with the arg lvar.
1638 ;;;
1639 ;;; We change the REF to be a reference to NIL with unused value, and
1640 ;;; let it be flushed as dead code. A side effect of this substitution
1641 ;;; is to delete the variable.
1642 (defun substitute-single-use-lvar (arg var)
1643   (declare (type lvar arg) (type lambda-var var))
1644   (binding* ((ref (first (leaf-refs var)))
1645              (lvar (node-lvar ref) :exit-if-null)
1646              (dest (lvar-dest lvar))
1647              (dest-lvar (when (valued-node-p dest) (node-lvar dest))))
1648     (when (and
1649            ;; Think about (LET ((A ...)) (IF ... A ...)): two
1650            ;; LVAR-USEs should not be met on one path. Another problem
1651            ;; is with dynamic-extent.
1652            (eq (lvar-uses lvar) ref)
1653            (not (block-delete-p (node-block ref)))
1654            ;; If the destinatation is dynamic extent, don't substitute unless
1655            ;; the source is as well.
1656            (or (not dest-lvar)
1657                (not (lvar-dynamic-extent dest-lvar))
1658                (lvar-dynamic-extent lvar))
1659            (typecase dest
1660              ;; we should not change lifetime of unknown values lvars
1661              (cast
1662               (and (type-single-value-p (lvar-derived-type arg))
1663                    (multiple-value-bind (pdest pprev)
1664                        (principal-lvar-end lvar)
1665                      (declare (ignore pdest))
1666                      (lvar-single-value-p pprev))))
1667              (mv-combination
1668               (or (eq (basic-combination-fun dest) lvar)
1669                   (and (eq (basic-combination-kind dest) :local)
1670                        (type-single-value-p (lvar-derived-type arg)))))
1671              ((or creturn exit)
1672               ;; While CRETURN and EXIT nodes may be known-values,
1673               ;; they have their own complications, such as
1674               ;; substitution into CRETURN may create new tail calls.
1675               nil)
1676              (t
1677               (aver (lvar-single-value-p lvar))
1678               t))
1679            (eq (node-home-lambda ref)
1680                (lambda-home (lambda-var-home var))))
1681       (let ((ref-type (single-value-type (node-derived-type ref))))
1682         (cond ((csubtypep (single-value-type (lvar-type arg)) ref-type)
1683                (substitute-lvar-uses lvar arg
1684                                      ;; Really it is (EQ (LVAR-USES LVAR) REF):
1685                                      t)
1686                (delete-lvar-use ref))
1687               (t
1688                (let* ((value (make-lvar))
1689                       (cast (insert-cast-before ref value ref-type
1690                                                 ;; KLUDGE: it should be (TYPE-CHECK 0)
1691                                                 *policy*)))
1692                  (setf (cast-type-to-check cast) *wild-type*)
1693                  (substitute-lvar-uses value arg
1694                                        ;; FIXME
1695                                        t)
1696                  (%delete-lvar-use ref)
1697                  (add-lvar-use cast lvar)))))
1698       (setf (node-derived-type ref) *wild-type*)
1699       (change-ref-leaf ref (find-constant nil))
1700       (delete-ref ref)
1701       (unlink-node ref)
1702       (reoptimize-lvar lvar)
1703       t)))
1704
1705 ;;; Delete a LET, removing the call and bind nodes, and warning about
1706 ;;; any unreferenced variables. Note that FLUSH-DEAD-CODE will come
1707 ;;; along right away and delete the REF and then the lambda, since we
1708 ;;; flush the FUN lvar.
1709 (defun delete-let (clambda)
1710   (declare (type clambda clambda))
1711   (aver (functional-letlike-p clambda))
1712   (note-unreferenced-vars clambda)
1713   (let ((call (let-combination clambda)))
1714     (flush-dest (basic-combination-fun call))
1715     (unlink-node call)
1716     (unlink-node (lambda-bind clambda))
1717     (setf (lambda-bind clambda) nil))
1718   (setf (functional-kind clambda) :zombie)
1719   (let ((home (lambda-home clambda)))
1720     (setf (lambda-lets home) (delete clambda (lambda-lets home))))
1721   (values))
1722
1723 ;;; This function is called when one of the arguments to a LET
1724 ;;; changes. We look at each changed argument. If the corresponding
1725 ;;; variable is set, then we call PROPAGATE-FROM-SETS. Otherwise, we
1726 ;;; consider substituting for the variable, and also propagate
1727 ;;; derived-type information for the arg to all the VAR's refs.
1728 ;;;
1729 ;;; Substitution is inhibited when the arg leaf's derived type isn't a
1730 ;;; subtype of the argument's leaf type. This prevents type checking
1731 ;;; from being defeated, and also ensures that the best representation
1732 ;;; for the variable can be used.
1733 ;;;
1734 ;;; Substitution of individual references is inhibited if the
1735 ;;; reference is in a different component from the home. This can only
1736 ;;; happen with closures over top level lambda vars. In such cases,
1737 ;;; the references may have already been compiled, and thus can't be
1738 ;;; retroactively modified.
1739 ;;;
1740 ;;; If all of the variables are deleted (have no references) when we
1741 ;;; are done, then we delete the LET.
1742 ;;;
1743 ;;; Note that we are responsible for clearing the LVAR-REOPTIMIZE
1744 ;;; flags.
1745 (defun propagate-let-args (call fun)
1746   (declare (type combination call) (type clambda fun))
1747   (loop for arg in (combination-args call)
1748         and var in (lambda-vars fun) do
1749     (when (and arg (lvar-reoptimize arg))
1750       (setf (lvar-reoptimize arg) nil)
1751       (cond
1752         ((lambda-var-sets var)
1753          (propagate-from-sets var (lvar-type arg)))
1754         ((let ((use (lvar-uses arg)))
1755            (when (ref-p use)
1756              (let ((leaf (ref-leaf use)))
1757                (when (and (constant-reference-p use)
1758                           (csubtypep (leaf-type leaf)
1759                                      ;; (NODE-DERIVED-TYPE USE) would
1760                                      ;; be better -- APD, 2003-05-15
1761                                      (leaf-type var)))
1762                  (propagate-to-refs var (lvar-type arg))
1763                  (let ((use-component (node-component use)))
1764                    (prog1 (substitute-leaf-if
1765                            (lambda (ref)
1766                              (cond ((eq (node-component ref) use-component)
1767                                     t)
1768                                    (t
1769                                     (aver (lambda-toplevelish-p (lambda-home fun)))
1770                                     nil)))
1771                            leaf var)))
1772                  t)))))
1773         ((and (null (rest (leaf-refs var)))
1774               (not (preserve-single-use-debug-var-p call var))
1775               (substitute-single-use-lvar arg var)))
1776         (t
1777          (propagate-to-refs var (lvar-type arg))))))
1778
1779   (when (every #'not (combination-args call))
1780     (delete-let fun))
1781
1782   (values))
1783
1784 ;;; This function is called when one of the args to a non-LET local
1785 ;;; call changes. For each changed argument corresponding to an unset
1786 ;;; variable, we compute the union of the types across all calls and
1787 ;;; propagate this type information to the var's refs.
1788 ;;;
1789 ;;; If the function has an entry-fun, then we don't do anything: since
1790 ;;; it has a XEP we would not discover anything.
1791 ;;;
1792 ;;; If the function is an optional-entry-point, we will just make sure
1793 ;;; &REST lists are known to be lists. Doing the regular rigamarole
1794 ;;; can erronously propagate too strict types into refs: see
1795 ;;; BUG-655203-REGRESSION in tests/compiler.pure.lisp.
1796 ;;;
1797 ;;; We can clear the LVAR-REOPTIMIZE flags for arguments in all calls
1798 ;;; corresponding to changed arguments in CALL, since the only use in
1799 ;;; IR1 optimization of the REOPTIMIZE flag for local call args is
1800 ;;; right here.
1801 (defun propagate-local-call-args (call fun)
1802   (declare (type combination call) (type clambda fun))
1803   (unless (functional-entry-fun fun)
1804     (if (lambda-optional-dispatch fun)
1805         ;; We can still make sure &REST is known to be a list.
1806         (loop for var in (lambda-vars fun)
1807               do (let ((info (lambda-var-arg-info var)))
1808                    (when (and info (eq :rest (arg-info-kind info)))
1809                      (propagate-from-sets var (specifier-type 'list)))))
1810         ;; The normal case.
1811         (let* ((vars (lambda-vars fun))
1812                (union (mapcar (lambda (arg var)
1813                                 (when (and arg
1814                                            (lvar-reoptimize arg)
1815                                            (null (basic-var-sets var)))
1816                                   (lvar-type arg)))
1817                               (basic-combination-args call)
1818                               vars))
1819                (this-ref (lvar-use (basic-combination-fun call))))
1820
1821           (dolist (arg (basic-combination-args call))
1822             (when arg
1823               (setf (lvar-reoptimize arg) nil)))
1824
1825           (dolist (ref (leaf-refs fun))
1826             (let ((dest (node-dest ref)))
1827               (unless (or (eq ref this-ref) (not dest))
1828                 (setq union
1829                       (mapcar (lambda (this-arg old)
1830                                 (when old
1831                                   (setf (lvar-reoptimize this-arg) nil)
1832                                   (type-union (lvar-type this-arg) old)))
1833                               (basic-combination-args dest)
1834                               union)))))
1835
1836           (loop for var in vars
1837                 and type in union
1838                 when type do (propagate-to-refs var type)))))
1839
1840   (values))
1841 \f
1842 ;;;; multiple values optimization
1843
1844 ;;; Do stuff to notice a change to a MV combination node. There are
1845 ;;; two main branches here:
1846 ;;;  -- If the call is local, then it is already a MV let, or should
1847 ;;;     become one. Note that although all :LOCAL MV calls must eventually
1848 ;;;     be converted to :MV-LETs, there can be a window when the call
1849 ;;;     is local, but has not been LET converted yet. This is because
1850 ;;;     the entry-point lambdas may have stray references (in other
1851 ;;;     entry points) that have not been deleted yet.
1852 ;;;  -- The call is full. This case is somewhat similar to the non-MV
1853 ;;;     combination optimization: we propagate return type information and
1854 ;;;     notice non-returning calls. We also have an optimization
1855 ;;;     which tries to convert MV-CALLs into MV-binds.
1856 (defun ir1-optimize-mv-combination (node)
1857   (ecase (basic-combination-kind node)
1858     (:local
1859      (let ((fun-lvar (basic-combination-fun node)))
1860        (when (lvar-reoptimize fun-lvar)
1861          (setf (lvar-reoptimize fun-lvar) nil)
1862          (maybe-let-convert (combination-lambda node))))
1863      (setf (lvar-reoptimize (first (basic-combination-args node))) nil)
1864      (when (eq (functional-kind (combination-lambda node)) :mv-let)
1865        (unless (convert-mv-bind-to-let node)
1866          (ir1-optimize-mv-bind node))))
1867     (:full
1868      (let* ((fun (basic-combination-fun node))
1869             (fun-changed (lvar-reoptimize fun))
1870             (args (basic-combination-args node)))
1871        (when fun-changed
1872          (setf (lvar-reoptimize fun) nil)
1873          (let ((type (lvar-type fun)))
1874            (when (fun-type-p type)
1875              (derive-node-type node (fun-type-returns type))))
1876          (maybe-terminate-block node nil)
1877          (let ((use (lvar-uses fun)))
1878            (when (and (ref-p use) (functional-p (ref-leaf use)))
1879              (convert-call-if-possible use node)
1880              (when (eq (basic-combination-kind node) :local)
1881                (maybe-let-convert (ref-leaf use))))))
1882        (unless (or (eq (basic-combination-kind node) :local)
1883                    (eq (lvar-fun-name fun) '%throw))
1884          (ir1-optimize-mv-call node))
1885        (dolist (arg args)
1886          (setf (lvar-reoptimize arg) nil))))
1887     (:error))
1888   (values))
1889
1890 ;;; Propagate derived type info from the values lvar to the vars.
1891 (defun ir1-optimize-mv-bind (node)
1892   (declare (type mv-combination node))
1893   (let* ((arg (first (basic-combination-args node)))
1894          (vars (lambda-vars (combination-lambda node)))
1895          (n-vars (length vars))
1896          (types (values-type-in (lvar-derived-type arg)
1897                                 n-vars)))
1898     (loop for var in vars
1899           and type in types
1900           do (if (basic-var-sets var)
1901                  (propagate-from-sets var type)
1902                  (propagate-to-refs var type)))
1903     (setf (lvar-reoptimize arg) nil))
1904   (values))
1905
1906 ;;; If possible, convert a general MV call to an MV-BIND. We can do
1907 ;;; this if:
1908 ;;; -- The call has only one argument, and
1909 ;;; -- The function has a known fixed number of arguments, or
1910 ;;; -- The argument yields a known fixed number of values.
1911 ;;;
1912 ;;; What we do is change the function in the MV-CALL to be a lambda
1913 ;;; that "looks like an MV bind", which allows
1914 ;;; IR1-OPTIMIZE-MV-COMBINATION to notice that this call can be
1915 ;;; converted (the next time around.) This new lambda just calls the
1916 ;;; actual function with the MV-BIND variables as arguments. Note that
1917 ;;; this new MV bind is not let-converted immediately, as there are
1918 ;;; going to be stray references from the entry-point functions until
1919 ;;; they get deleted.
1920 ;;;
1921 ;;; In order to avoid loss of argument count checking, we only do the
1922 ;;; transformation according to a known number of expected argument if
1923 ;;; safety is unimportant. We can always convert if we know the number
1924 ;;; of actual values, since the normal call that we build will still
1925 ;;; do any appropriate argument count checking.
1926 ;;;
1927 ;;; We only attempt the transformation if the called function is a
1928 ;;; constant reference. This allows us to just splice the leaf into
1929 ;;; the new function, instead of trying to somehow bind the function
1930 ;;; expression. The leaf must be constant because we are evaluating it
1931 ;;; again in a different place. This also has the effect of squelching
1932 ;;; multiple warnings when there is an argument count error.
1933 (defun ir1-optimize-mv-call (node)
1934   (let ((fun (basic-combination-fun node))
1935         (*compiler-error-context* node)
1936         (ref (lvar-uses (basic-combination-fun node)))
1937         (args (basic-combination-args node)))
1938
1939     (unless (and (ref-p ref) (constant-reference-p ref)
1940                  (singleton-p args))
1941       (return-from ir1-optimize-mv-call))
1942
1943     (multiple-value-bind (min max)
1944         (fun-type-nargs (lvar-type fun))
1945       (let ((total-nvals
1946              (multiple-value-bind (types nvals)
1947                  (values-types (lvar-derived-type (first args)))
1948                (declare (ignore types))
1949                (if (eq nvals :unknown) nil nvals))))
1950
1951         (when total-nvals
1952           (when (and min (< total-nvals min))
1953             (compiler-warn
1954              "MULTIPLE-VALUE-CALL with ~R values when the function expects ~
1955               at least ~R."
1956              total-nvals min)
1957             (setf (basic-combination-kind node) :error)
1958             (return-from ir1-optimize-mv-call))
1959           (when (and max (> total-nvals max))
1960             (compiler-warn
1961              "MULTIPLE-VALUE-CALL with ~R values when the function expects ~
1962               at most ~R."
1963              total-nvals max)
1964             (setf (basic-combination-kind node) :error)
1965             (return-from ir1-optimize-mv-call)))
1966
1967         (let ((count (cond (total-nvals)
1968                            ((and (policy node (zerop verify-arg-count))
1969                                  (eql min max))
1970                             min)
1971                            (t nil))))
1972           (when count
1973             (with-ir1-environment-from-node node
1974               (let* ((dums (make-gensym-list count))
1975                      (ignore (gensym))
1976                      (leaf (ref-leaf ref))
1977                      (fun (ir1-convert-lambda
1978                            `(lambda (&optional ,@dums &rest ,ignore)
1979                               (declare (ignore ,ignore))
1980                               (%funcall ,leaf ,@dums))
1981                            :source-name (leaf-%source-name leaf)
1982                            :debug-name (leaf-%debug-name leaf))))
1983                 (change-ref-leaf ref fun)
1984                 (aver (eq (basic-combination-kind node) :full))
1985                 (locall-analyze-component *current-component*)
1986                 (aver (eq (basic-combination-kind node) :local)))))))))
1987   (values))
1988
1989 ;;; If we see:
1990 ;;;    (multiple-value-bind
1991 ;;;     (x y)
1992 ;;;     (values xx yy)
1993 ;;;      ...)
1994 ;;; Convert to:
1995 ;;;    (let ((x xx)
1996 ;;;       (y yy))
1997 ;;;      ...)
1998 ;;;
1999 ;;; What we actually do is convert the VALUES combination into a
2000 ;;; normal LET combination calling the original :MV-LET lambda. If
2001 ;;; there are extra args to VALUES, discard the corresponding
2002 ;;; lvars. If there are insufficient args, insert references to NIL.
2003 (defun convert-mv-bind-to-let (call)
2004   (declare (type mv-combination call))
2005   (let* ((arg (first (basic-combination-args call)))
2006          (use (lvar-uses arg)))
2007     (when (and (combination-p use)
2008                (eq (lvar-fun-name (combination-fun use))
2009                    'values))
2010       (let* ((fun (combination-lambda call))
2011              (vars (lambda-vars fun))
2012              (vals (combination-args use))
2013              (nvars (length vars))
2014              (nvals (length vals)))
2015         (cond ((> nvals nvars)
2016                (mapc #'flush-dest (subseq vals nvars))
2017                (setq vals (subseq vals 0 nvars)))
2018               ((< nvals nvars)
2019                (with-ir1-environment-from-node use
2020                  (let ((node-prev (node-prev use)))
2021                    (setf (node-prev use) nil)
2022                    (setf (ctran-next node-prev) nil)
2023                    (collect ((res vals))
2024                      (loop for count below (- nvars nvals)
2025                            for prev = node-prev then ctran
2026                            for ctran = (make-ctran)
2027                            and lvar = (make-lvar use)
2028                            do (reference-constant prev ctran lvar nil)
2029                               (res lvar)
2030                            finally (link-node-to-previous-ctran
2031                                     use ctran))
2032                      (setq vals (res)))))))
2033         (setf (combination-args use) vals)
2034         (flush-dest (combination-fun use))
2035         (let ((fun-lvar (basic-combination-fun call)))
2036           (setf (lvar-dest fun-lvar) use)
2037           (setf (combination-fun use) fun-lvar)
2038           (flush-lvar-externally-checkable-type fun-lvar))
2039         (setf (combination-kind use) :local)
2040         (setf (functional-kind fun) :let)
2041         (flush-dest (first (basic-combination-args call)))
2042         (unlink-node call)
2043         (when vals
2044           (reoptimize-lvar (first vals)))
2045         ;; Propagate derived types from the VALUES call to its args:
2046         ;; transforms can leave the VALUES call with a better type
2047         ;; than its args have, so make sure not to throw that away.
2048         (let ((types (values-type-types (node-derived-type use))))
2049           (dolist (val vals)
2050             (when types
2051               (let ((type (pop types)))
2052                 (assert-lvar-type val type '((type-check . 0)))))))
2053         ;; Propagate declared types of MV-BIND variables.
2054         (propagate-to-args use fun)
2055         (reoptimize-call use))
2056       t)))
2057
2058 ;;; If we see:
2059 ;;;    (values-list (list x y z))
2060 ;;;
2061 ;;; Convert to:
2062 ;;;    (values x y z)
2063 ;;;
2064 ;;; In implementation, this is somewhat similar to
2065 ;;; CONVERT-MV-BIND-TO-LET. We grab the args of LIST and make them
2066 ;;; args of the VALUES-LIST call, flushing the old argument lvar
2067 ;;; (allowing the LIST to be flushed.)
2068 ;;;
2069 ;;; FIXME: Thus we lose possible type assertions on (LIST ...).
2070 (defoptimizer (values-list optimizer) ((list) node)
2071   (let ((use (lvar-uses list)))
2072     (when (and (combination-p use)
2073                (eq (lvar-fun-name (combination-fun use))
2074                    'list))
2075
2076       ;; FIXME: VALUES might not satisfy an assertion on NODE-LVAR.
2077       (change-ref-leaf (lvar-uses (combination-fun node))
2078                        (find-free-fun 'values "in a strange place"))
2079       (setf (combination-kind node) :full)
2080       (let ((args (combination-args use)))
2081         (dolist (arg args)
2082           (setf (lvar-dest arg) node)
2083           (flush-lvar-externally-checkable-type arg))
2084         (setf (combination-args use) nil)
2085         (flush-dest list)
2086         (flush-combination use)
2087         (setf (combination-args node) args))
2088       t)))
2089
2090 ;;; If VALUES appears in a non-MV context, then effectively convert it
2091 ;;; to a PROG1. This allows the computation of the additional values
2092 ;;; to become dead code.
2093 (deftransform values ((&rest vals) * * :node node)
2094   (unless (lvar-single-value-p (node-lvar node))
2095     (give-up-ir1-transform))
2096   (setf (node-derived-type node)
2097         (make-short-values-type (list (single-value-type
2098                                        (node-derived-type node)))))
2099   (principal-lvar-single-valuify (node-lvar node))
2100   (if vals
2101       (let ((dummies (make-gensym-list (length (cdr vals)))))
2102         `(lambda (val ,@dummies)
2103            (declare (ignore ,@dummies))
2104            val))
2105       nil))
2106
2107 ;;; TODO:
2108 ;;; - CAST chains;
2109 (defun delete-cast (cast)
2110   (declare (type cast cast))
2111   (let ((value (cast-value cast))
2112         (lvar (node-lvar cast)))
2113     (delete-filter cast lvar value)
2114     (when lvar
2115       (reoptimize-lvar lvar)
2116       (when (lvar-single-value-p lvar)
2117         (note-single-valuified-lvar lvar)))
2118     (values)))
2119
2120 (defun ir1-optimize-cast (cast &optional do-not-optimize)
2121   (declare (type cast cast))
2122   (let ((value (cast-value cast))
2123         (atype (cast-asserted-type cast)))
2124     (when (not do-not-optimize)
2125       (let ((lvar (node-lvar cast)))
2126         (when (values-subtypep (lvar-derived-type value)
2127                                (cast-asserted-type cast))
2128           (delete-cast cast)
2129           (return-from ir1-optimize-cast t))
2130
2131         (when (and (listp (lvar-uses value))
2132                    lvar)
2133           ;; Pathwise removing of CAST
2134           (let ((ctran (node-next cast))
2135                 (dest (lvar-dest lvar))
2136                 next-block)
2137             (collect ((merges))
2138               (do-uses (use value)
2139                 (when (and (values-subtypep (node-derived-type use) atype)
2140                            (immediately-used-p value use))
2141                   (unless next-block
2142                     (when ctran (ensure-block-start ctran))
2143                     (setq next-block (first (block-succ (node-block cast))))
2144                     (ensure-block-start (node-prev cast))
2145                     (reoptimize-lvar lvar)
2146                     (setf (lvar-%derived-type value) nil))
2147                   (%delete-lvar-use use)
2148                   (add-lvar-use use lvar)
2149                   (unlink-blocks (node-block use) (node-block cast))
2150                   (link-blocks (node-block use) next-block)
2151                   (when (and (return-p dest)
2152                              (basic-combination-p use)
2153                              (eq (basic-combination-kind use) :local))
2154                     (merges use))))
2155               (dolist (use (merges))
2156                 (merge-tail-sets use)))))))
2157
2158     (let* ((value-type (lvar-derived-type value))
2159            (int (values-type-intersection value-type atype)))
2160       (derive-node-type cast int)
2161       (when (eq int *empty-type*)
2162         (unless (eq value-type *empty-type*)
2163
2164           ;; FIXME: Do it in one step.
2165           (let ((context (cons (node-source-form cast)
2166                                (lvar-all-sources (cast-value cast)))))
2167             (filter-lvar
2168              value
2169              (if (cast-single-value-p cast)
2170                  `(list 'dummy)
2171                  `(multiple-value-call #'list 'dummy)))
2172             (filter-lvar
2173              (cast-value cast)
2174              ;; FIXME: Derived type.
2175              `(%compile-time-type-error 'dummy
2176                                         ',(type-specifier atype)
2177                                         ',(type-specifier value-type)
2178                                         ',context)))
2179           ;; KLUDGE: FILTER-LVAR does not work for non-returning
2180           ;; functions, so we declare the return type of
2181           ;; %COMPILE-TIME-TYPE-ERROR to be * and derive the real type
2182           ;; here.
2183           (setq value (cast-value cast))
2184           (derive-node-type (lvar-uses value) *empty-type*)
2185           (maybe-terminate-block (lvar-uses value) nil)
2186           ;; FIXME: Is it necessary?
2187           (aver (null (block-pred (node-block cast))))
2188           (delete-block-lazily (node-block cast))
2189           (return-from ir1-optimize-cast)))
2190       (when (eq (node-derived-type cast) *empty-type*)
2191         (maybe-terminate-block cast nil))
2192
2193       (when (and (cast-%type-check cast)
2194                  (values-subtypep value-type
2195                                   (cast-type-to-check cast)))
2196         (setf (cast-%type-check cast) nil))))
2197
2198   (unless do-not-optimize
2199     (setf (node-reoptimize cast) nil)))
2200
2201 (deftransform make-symbol ((string) (simple-string))
2202   `(%make-symbol string))