618b3d72c70c20a78e7e600b96a9bd08402d34b0
[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   (and (lvar-p thing)
25        (let ((use (principal-lvar-use thing)))
26          (and (ref-p use) (constant-p (ref-leaf use))))))
27
28 ;;; Return the constant value for an LVAR whose only use is a constant
29 ;;; node.
30 (declaim (ftype (function (lvar) t) lvar-value))
31 (defun lvar-value (lvar)
32   (let ((use (principal-lvar-use lvar)))
33     (constant-value (ref-leaf use))))
34 \f
35 ;;;; interface for obtaining results of type inference
36
37 ;;; Our best guess for the type of this lvar's value. Note that this
38 ;;; may be VALUES or FUNCTION type, which cannot be passed as an
39 ;;; argument to the normal type operations. See LVAR-TYPE.
40 ;;;
41 ;;; The result value is cached in the LVAR-%DERIVED-TYPE slot. If the
42 ;;; slot is true, just return that value, otherwise recompute and
43 ;;; stash the value there.
44 #!-sb-fluid (declaim (inline lvar-derived-type))
45 (defun lvar-derived-type (lvar)
46   (declare (type lvar lvar))
47   (or (lvar-%derived-type lvar)
48       (setf (lvar-%derived-type lvar)
49             (%lvar-derived-type lvar))))
50 (defun %lvar-derived-type (lvar)
51   (declare (type lvar lvar))
52   (let ((uses (lvar-uses lvar)))
53     (cond ((null uses) *empty-type*)
54           ((listp uses)
55            (do ((res (node-derived-type (first uses))
56                      (values-type-union (node-derived-type (first current))
57                                         res))
58                 (current (rest uses) (rest current)))
59                ((null current) res)))
60           (t
61            (node-derived-type (lvar-uses lvar))))))
62
63 ;;; Return the derived type for LVAR's first value. This is guaranteed
64 ;;; not to be a VALUES or FUNCTION type.
65 (declaim (ftype (sfunction (lvar) ctype) lvar-type))
66 (defun lvar-type (lvar)
67   (single-value-type (lvar-derived-type lvar)))
68
69 ;;; If LVAR is an argument of a function, return a type which the
70 ;;; function checks LVAR for.
71 #!-sb-fluid (declaim (inline lvar-externally-checkable-type))
72 (defun lvar-externally-checkable-type (lvar)
73   (or (lvar-%externally-checkable-type lvar)
74       (%lvar-%externally-checkable-type lvar)))
75 (defun %lvar-%externally-checkable-type (lvar)
76   (declare (type lvar lvar))
77   (let ((dest (lvar-dest lvar)))
78     (if (not (and dest (combination-p dest)))
79         ;; TODO: MV-COMBINATION
80         (setf (lvar-%externally-checkable-type lvar) *wild-type*)
81         (let* ((fun (combination-fun dest))
82                (args (combination-args dest))
83                (fun-type (lvar-type fun)))
84           (setf (lvar-%externally-checkable-type fun) *wild-type*)
85           (if (or (not (call-full-like-p dest))
86                   (not (fun-type-p fun-type))
87                   ;; FUN-TYPE might be (AND FUNCTION (SATISFIES ...)).
88                   (fun-type-wild-args fun-type))
89               (dolist (arg args)
90                 (when arg
91                   (setf (lvar-%externally-checkable-type arg)
92                         *wild-type*)))
93               (map-combination-args-and-types
94                (lambda (arg type)
95                  (setf (lvar-%externally-checkable-type arg)
96                        (acond ((lvar-%externally-checkable-type arg)
97                                (values-type-intersection
98                                 it (coerce-to-values type)))
99                               (t (coerce-to-values type)))))
100                dest)))))
101   (lvar-%externally-checkable-type lvar))
102 #!-sb-fluid(declaim (inline flush-lvar-externally-checkable-type))
103 (defun flush-lvar-externally-checkable-type (lvar)
104   (declare (type lvar lvar))
105   (setf (lvar-%externally-checkable-type lvar) nil))
106 \f
107 ;;;; interface routines used by optimizers
108
109 ;;; This function is called by optimizers to indicate that something
110 ;;; interesting has happened to the value of LVAR. Optimizers must
111 ;;; make sure that they don't call for reoptimization when nothing has
112 ;;; happened, since optimization will fail to terminate.
113 ;;;
114 ;;; We clear any cached type for the lvar and set the reoptimize flags
115 ;;; on everything in sight.
116 (defun reoptimize-lvar (lvar)
117   (declare (type (or lvar null) lvar))
118   (when lvar
119     (setf (lvar-%derived-type lvar) nil)
120     (let ((dest (lvar-dest lvar)))
121       (when dest
122         (setf (lvar-reoptimize lvar) t)
123         (setf (node-reoptimize dest) t)
124         (binding* (;; Since this may be called during IR1 conversion,
125                    ;; PREV may be missing.
126                    (prev (node-prev dest) :exit-if-null)
127                    (block (ctran-block prev))
128                    (component (block-component block)))
129           (when (typep dest 'cif)
130             (setf (block-test-modified block) t))
131           (setf (block-reoptimize block) t)
132           (setf (component-reoptimize component) t))))
133     (do-uses (node lvar)
134       (setf (block-type-check (node-block node)) t)))
135   (values))
136
137 (defun reoptimize-lvar-uses (lvar)
138   (declare (type lvar lvar))
139   (do-uses (use lvar)
140     (setf (node-reoptimize use) t)
141     (setf (block-reoptimize (node-block use)) t)
142     (setf (component-reoptimize (node-component use)) t)))
143
144 ;;; Annotate NODE to indicate that its result has been proven to be
145 ;;; TYPEP to RTYPE. After IR1 conversion has happened, this is the
146 ;;; only correct way to supply information discovered about a node's
147 ;;; type. If you screw with the NODE-DERIVED-TYPE directly, then
148 ;;; information may be lost and reoptimization may not happen.
149 ;;;
150 ;;; What we do is intersect RTYPE with NODE's DERIVED-TYPE. If the
151 ;;; intersection is different from the old type, then we do a
152 ;;; REOPTIMIZE-LVAR on the NODE-LVAR.
153 (defun derive-node-type (node rtype)
154   (declare (type valued-node node) (type ctype rtype))
155   (let ((node-type (node-derived-type node)))
156     (unless (eq node-type rtype)
157       (let ((int (values-type-intersection node-type rtype))
158             (lvar (node-lvar node)))
159         (when (type/= node-type int)
160           (when (and *check-consistency*
161                      (eq int *empty-type*)
162                      (not (eq rtype *empty-type*)))
163             (let ((*compiler-error-context* node))
164               (compiler-warn
165                "New inferred type ~S conflicts with old type:~
166                 ~%  ~S~%*** possible internal error? Please report this."
167                (type-specifier rtype) (type-specifier node-type))))
168           (setf (node-derived-type node) int)
169           ;; If the new type consists of only one object, replace the
170           ;; node with a constant reference.
171           (when (and (ref-p node)
172                      (lambda-var-p (ref-leaf node)))
173             (let ((type (single-value-type int)))
174               (when (and (member-type-p type)
175                          (null (rest (member-type-members type))))
176                 (change-ref-leaf node (find-constant
177                                        (first (member-type-members type)))))))
178           (reoptimize-lvar lvar)))))
179   (values))
180
181 ;;; This is similar to DERIVE-NODE-TYPE, but asserts that it is an
182 ;;; error for LVAR's value not to be TYPEP to TYPE. We implement it
183 ;;; splitting off DEST a new CAST node; old LVAR will deliver values
184 ;;; to CAST. If we improve the assertion, we set TYPE-CHECK and
185 ;;; TYPE-ASSERTED to guarantee that the new assertion will be checked.
186 (defun assert-lvar-type (lvar type policy)
187   (declare (type lvar lvar) (type ctype type))
188   (unless (values-subtypep (lvar-derived-type lvar) type)
189     (let* ((dest (lvar-dest lvar))
190            (ctran (node-prev dest)))
191       (with-ir1-environment-from-node dest
192         (let* ((cast (make-cast lvar type policy))
193                (internal-lvar (make-lvar))
194                (internal-ctran (make-ctran)))
195           (setf (ctran-next ctran) cast
196                 (node-prev cast) ctran)
197           (use-continuation cast internal-ctran internal-lvar)
198           (link-node-to-previous-ctran dest internal-ctran)
199           (substitute-lvar internal-lvar lvar)
200           (setf (lvar-dest lvar) cast)
201           (reoptimize-lvar lvar)
202           (when (return-p dest)
203             (node-ends-block cast))
204           (setf (block-attributep (block-flags (node-block cast))
205                                   type-check type-asserted)
206                 t))))))
207
208 \f
209 ;;;; IR1-OPTIMIZE
210
211 ;;; Do one forward pass over COMPONENT, deleting unreachable blocks
212 ;;; and doing IR1 optimizations. We can ignore all blocks that don't
213 ;;; have the REOPTIMIZE flag set. If COMPONENT-REOPTIMIZE is true when
214 ;;; we are done, then another iteration would be beneficial.
215 (defun ir1-optimize (component)
216   (declare (type component component))
217   (setf (component-reoptimize component) nil)
218   (do-blocks (block component)
219     (cond
220       ;; We delete blocks when there is either no predecessor or the
221       ;; block is in a lambda that has been deleted. These blocks
222       ;; would eventually be deleted by DFO recomputation, but doing
223       ;; it here immediately makes the effect available to IR1
224       ;; optimization.
225       ((or (block-delete-p block)
226            (null (block-pred block)))
227        (delete-block block))
228       ((eq (functional-kind (block-home-lambda block)) :deleted)
229        ;; Preserve the BLOCK-SUCC invariant that almost every block has
230        ;; one successor (and a block with DELETE-P set is an acceptable
231        ;; exception).
232        (mark-for-deletion block)
233        (delete-block block))
234       (t
235        (loop
236           (let ((succ (block-succ block)))
237             (unless (singleton-p succ)
238               (return)))
239
240           (let ((last (block-last block)))
241             (typecase last
242               (cif
243                (flush-dest (if-test last))
244                (when (unlink-node last)
245                  (return)))
246               (exit
247                (when (maybe-delete-exit last)
248                  (return)))))
249
250           (unless (join-successor-if-possible block)
251             (return)))
252
253        (when (and (block-reoptimize block) (block-component block))
254          (aver (not (block-delete-p block)))
255          (ir1-optimize-block block))
256
257        (cond ((and (block-delete-p block) (block-component block))
258               (delete-block block))
259              ((and (block-flush-p block) (block-component block))
260               (flush-dead-code block))))))
261
262   (values))
263
264 ;;; Loop over the nodes in BLOCK, acting on (and clearing) REOPTIMIZE
265 ;;; flags.
266 ;;;
267 ;;; Note that although they are cleared here, REOPTIMIZE flags might
268 ;;; still be set upon return from this function, meaning that further
269 ;;; optimization is wanted (as a consequence of optimizations we did).
270 (defun ir1-optimize-block (block)
271   (declare (type cblock block))
272   ;; We clear the node and block REOPTIMIZE flags before doing the
273   ;; optimization, not after. This ensures that the node or block will
274   ;; be reoptimized if necessary.
275   (setf (block-reoptimize block) nil)
276   (do-nodes (node nil block :restart-p t)
277     (when (node-reoptimize node)
278       ;; As above, we clear the node REOPTIMIZE flag before optimizing.
279       (setf (node-reoptimize node) nil)
280       (typecase node
281         (ref)
282         (combination
283          ;; With a COMBINATION, we call PROPAGATE-FUN-CHANGE whenever
284          ;; the function changes, and call IR1-OPTIMIZE-COMBINATION if
285          ;; any argument changes.
286          (ir1-optimize-combination node))
287         (cif
288          (ir1-optimize-if node))
289         (creturn
290          ;; KLUDGE: We leave the NODE-OPTIMIZE flag set going into
291          ;; IR1-OPTIMIZE-RETURN, since IR1-OPTIMIZE-RETURN wants to
292          ;; clear the flag itself. -- WHN 2002-02-02, quoting original
293          ;; CMU CL comments
294          (setf (node-reoptimize node) t)
295          (ir1-optimize-return node))
296         (mv-combination
297          (ir1-optimize-mv-combination node))
298         (exit
299          ;; With an EXIT, we derive the node's type from the VALUE's
300          ;; type.
301          (let ((value (exit-value node)))
302            (when value
303              (derive-node-type node (lvar-derived-type value)))))
304         (cset
305          (ir1-optimize-set node))
306         (cast
307          (ir1-optimize-cast node)))))
308
309   (values))
310
311 ;;; Try to join with a successor block. If we succeed, we return true,
312 ;;; otherwise false.
313 (defun join-successor-if-possible (block)
314   (declare (type cblock block))
315   (let ((next (first (block-succ block))))
316     (when (block-start next)  ; NEXT is not an END-OF-COMPONENT marker
317       (cond ( ;; We cannot combine with a successor block if:
318              (or
319               ;; The successor has more than one predecessor.
320               (rest (block-pred next))
321               ;; The successor is the current block (infinite loop).
322               (eq next block)
323               ;; The next block has a different cleanup, and thus
324               ;; we may want to insert cleanup code between the
325               ;; two blocks at some point.
326               (not (eq (block-end-cleanup block)
327                        (block-start-cleanup next)))
328               ;; The next block has a different home lambda, and
329               ;; thus the control transfer is a non-local exit.
330               (not (eq (block-home-lambda block)
331                        (block-home-lambda next))))
332              nil)
333             (t
334              (join-blocks block next)
335              t)))))
336
337 ;;; Join together two blocks. The code in BLOCK2 is moved into BLOCK1
338 ;;; and BLOCK2 is deleted from the DFO. We combine the optimize flags
339 ;;; for the two blocks so that any indicated optimization gets done.
340 (defun join-blocks (block1 block2)
341   (declare (type cblock block1 block2))
342   (let* ((last1 (block-last block1))
343          (last2 (block-last block2))
344          (succ (block-succ block2))
345          (start2 (block-start block2)))
346     (do ((ctran start2 (node-next (ctran-next ctran))))
347         ((not ctran))
348       (setf (ctran-block ctran) block1))
349
350     (unlink-blocks block1 block2)
351     (dolist (block succ)
352       (unlink-blocks block2 block)
353       (link-blocks block1 block))
354
355     (setf (ctran-kind start2) :inside-block)
356     (setf (node-next last1) start2)
357     (setf (ctran-use start2) last1)
358     (setf (block-last block1) last2))
359
360   (setf (block-flags block1)
361         (attributes-union (block-flags block1)
362                           (block-flags block2)
363                           (block-attributes type-asserted test-modified)))
364
365   (let ((next (block-next block2))
366         (prev (block-prev block2)))
367     (setf (block-next prev) next)
368     (setf (block-prev next) prev))
369
370   (values))
371
372 ;;; Delete any nodes in BLOCK whose value is unused and which have no
373 ;;; side effects. We can delete sets of lexical variables when the set
374 ;;; variable has no references.
375 (defun flush-dead-code (block)
376   (declare (type cblock block))
377   (setf (block-flush-p block) nil)
378   (do-nodes-backwards (node lvar block)
379     (unless lvar
380       (typecase node
381         (ref
382          (delete-ref node)
383          (unlink-node node))
384         (combination
385          (let ((info (combination-kind node)))
386            (when (fun-info-p info)
387              (let ((attr (fun-info-attributes info)))
388                (when (and (not (ir1-attributep attr call))
389                           ;; ### For now, don't delete potentially
390                           ;; flushable calls when they have the CALL
391                           ;; attribute. Someday we should look at the
392                           ;; functional args to determine if they have
393                           ;; any side effects.
394                           (if (policy node (= safety 3))
395                               (ir1-attributep attr flushable)
396                               (ir1-attributep attr unsafely-flushable)))
397                  (flush-combination node))))))
398         (mv-combination
399          (when (eq (basic-combination-kind node) :local)
400            (let ((fun (combination-lambda node)))
401              (when (dolist (var (lambda-vars fun) t)
402                      (when (or (leaf-refs var)
403                                (lambda-var-sets var))
404                        (return nil)))
405                (flush-dest (first (basic-combination-args node)))
406                (delete-let fun)))))
407         (exit
408          (let ((value (exit-value node)))
409            (when value
410              (flush-dest value)
411              (setf (exit-value node) nil))))
412         (cset
413          (let ((var (set-var node)))
414            (when (and (lambda-var-p var)
415                       (null (leaf-refs var)))
416              (flush-dest (set-value node))
417              (setf (basic-var-sets var)
418                    (delq node (basic-var-sets var)))
419              (unlink-node node))))
420         (cast
421          (unless (cast-type-check node)
422            (flush-dest (cast-value node))
423            (unlink-node node))))))
424
425   (values))
426 \f
427 ;;;; local call return type propagation
428
429 ;;; This function is called on RETURN nodes that have their REOPTIMIZE
430 ;;; flag set. It iterates over the uses of the RESULT, looking for
431 ;;; interesting stuff to update the TAIL-SET. If a use isn't a local
432 ;;; call, then we union its type together with the types of other such
433 ;;; uses. We assign to the RETURN-RESULT-TYPE the intersection of this
434 ;;; type with the RESULT's asserted type. We can make this
435 ;;; intersection now (potentially before type checking) because this
436 ;;; assertion on the result will eventually be checked (if
437 ;;; appropriate.)
438 ;;;
439 ;;; We call MAYBE-CONVERT-TAIL-LOCAL-CALL on each local non-MV
440 ;;; combination, which may change the succesor of the call to be the
441 ;;; called function, and if so, checks if the call can become an
442 ;;; assignment. If we convert to an assignment, we abort, since the
443 ;;; RETURN has been deleted.
444 (defun find-result-type (node)
445   (declare (type creturn node))
446   (let ((result (return-result node)))
447     (collect ((use-union *empty-type* values-type-union))
448       (do-uses (use result)
449         (let ((use-home (node-home-lambda use)))
450           (cond ((or (eq (functional-kind use-home) :deleted)
451                      (block-delete-p (node-block use))))
452                 ((and (basic-combination-p use)
453                       (eq (basic-combination-kind use) :local))
454                  (aver (eq (lambda-tail-set use-home)
455                            (lambda-tail-set (combination-lambda use))))
456                  (when (combination-p use)
457                    (when (nth-value 1 (maybe-convert-tail-local-call use))
458                      (return-from find-result-type (values)))))
459                 (t
460                  (use-union (node-derived-type use))))))
461       (let ((int
462              ;; (values-type-intersection
463              ;; (continuation-asserted-type result) ; FIXME -- APD, 2002-01-26
464              (use-union)
465               ;; )
466               ))
467         (setf (return-result-type node) int))))
468   (values))
469
470 ;;; Do stuff to realize that something has changed about the value
471 ;;; delivered to a return node. Since we consider the return values of
472 ;;; all functions in the tail set to be equivalent, this amounts to
473 ;;; bringing the entire tail set up to date. We iterate over the
474 ;;; returns for all the functions in the tail set, reanalyzing them
475 ;;; all (not treating NODE specially.)
476 ;;;
477 ;;; When we are done, we check whether the new type is different from
478 ;;; the old TAIL-SET-TYPE. If so, we set the type and also reoptimize
479 ;;; all the lvars for references to functions in the tail set. This
480 ;;; will cause IR1-OPTIMIZE-COMBINATION to derive the new type as the
481 ;;; results of the calls.
482 (defun ir1-optimize-return (node)
483   (declare (type creturn node))
484   (let* ((tails (lambda-tail-set (return-lambda node)))
485          (funs (tail-set-funs tails)))
486     (collect ((res *empty-type* values-type-union))
487       (dolist (fun funs)
488         (let ((return (lambda-return fun)))
489           (when return
490             (when (node-reoptimize return)
491               (setf (node-reoptimize return) nil)
492               (find-result-type return))
493             (res (return-result-type return)))))
494
495       (when (type/= (res) (tail-set-type tails))
496         (setf (tail-set-type tails) (res))
497         (dolist (fun (tail-set-funs tails))
498           (dolist (ref (leaf-refs fun))
499             (reoptimize-lvar (node-lvar ref)))))))
500
501   (values))
502 \f
503 ;;;; IF optimization
504
505 ;;; If the test has multiple uses, replicate the node when possible.
506 ;;; Also check whether the predicate is known to be true or false,
507 ;;; deleting the IF node in favor of the appropriate branch when this
508 ;;; is the case.
509 (defun ir1-optimize-if (node)
510   (declare (type cif node))
511   (let ((test (if-test node))
512         (block (node-block node)))
513
514     (when (and (eq (block-start-node block) node)
515                (listp (lvar-uses test)))
516       (do-uses (use test)
517         (when (immediately-used-p test use)
518           (convert-if-if use node)
519           (when (not (listp (lvar-uses test))) (return)))))
520
521     (let* ((type (lvar-type test))
522            (victim
523             (cond ((constant-lvar-p test)
524                    (if (lvar-value test)
525                        (if-alternative node)
526                        (if-consequent node)))
527                   ((not (types-equal-or-intersect type (specifier-type 'null)))
528                    (if-alternative node))
529                   ((type= type (specifier-type 'null))
530                    (if-consequent node)))))
531       (when victim
532         (flush-dest test)
533         (when (rest (block-succ block))
534           (unlink-blocks block victim))
535         (setf (component-reanalyze (node-component node)) t)
536         (unlink-node node))))
537   (values))
538
539 ;;; Create a new copy of an IF node that tests the value of the node
540 ;;; USE. The test must have >1 use, and must be immediately used by
541 ;;; USE. NODE must be the only node in its block (implying that
542 ;;; block-start = if-test).
543 ;;;
544 ;;; This optimization has an effect semantically similar to the
545 ;;; source-to-source transformation:
546 ;;;    (IF (IF A B C) D E) ==>
547 ;;;    (IF A (IF B D E) (IF C D E))
548 ;;;
549 ;;; We clobber the NODE-SOURCE-PATH of both the original and the new
550 ;;; node so that dead code deletion notes will definitely not consider
551 ;;; either node to be part of the original source. One node might
552 ;;; become unreachable, resulting in a spurious note.
553 (defun convert-if-if (use node)
554   (declare (type node use) (type cif node))
555   (with-ir1-environment-from-node node
556     (let* ((block (node-block node))
557            (test (if-test node))
558            (cblock (if-consequent node))
559            (ablock (if-alternative node))
560            (use-block (node-block use))
561            (new-ctran (make-ctran))
562            (new-lvar (make-lvar))
563            (new-node (make-if :test new-lvar
564                               :consequent cblock
565                               :alternative ablock))
566            (new-block (ctran-starts-block new-ctran)))
567       (link-node-to-previous-ctran new-node new-ctran)
568       (setf (lvar-dest new-lvar) new-node)
569       (setf (block-last new-block) new-node)
570
571       (unlink-blocks use-block block)
572       (%delete-lvar-use use)
573       (add-lvar-use use new-lvar)
574       (link-blocks use-block new-block)
575
576       (link-blocks new-block cblock)
577       (link-blocks new-block ablock)
578
579       (push "<IF Duplication>" (node-source-path node))
580       (push "<IF Duplication>" (node-source-path new-node))
581
582       (reoptimize-lvar test)
583       (reoptimize-lvar new-lvar)
584       (setf (component-reanalyze *current-component*) t)))
585   (values))
586 \f
587 ;;;; exit IR1 optimization
588
589 ;;; This function attempts to delete an exit node, returning true if
590 ;;; it deletes the block as a consequence:
591 ;;; -- If the exit is degenerate (has no ENTRY), then we don't do
592 ;;;    anything, since there is nothing to be done.
593 ;;; -- If the exit node and its ENTRY have the same home lambda then
594 ;;;    we know the exit is local, and can delete the exit. We change
595 ;;;    uses of the Exit-Value to be uses of the original lvar,
596 ;;;    then unlink the node. If the exit is to a TR context, then we
597 ;;;    must do MERGE-TAIL-SETS on any local calls which delivered
598 ;;;    their value to this exit.
599 ;;; -- If there is no value (as in a GO), then we skip the value
600 ;;;    semantics.
601 ;;;
602 ;;; This function is also called by environment analysis, since it
603 ;;; wants all exits to be optimized even if normal optimization was
604 ;;; omitted.
605 (defun maybe-delete-exit (node)
606   (declare (type exit node))
607   (let ((value (exit-value node))
608         (entry (exit-entry node)))
609     (when (and entry
610                (eq (node-home-lambda node) (node-home-lambda entry)))
611       (setf (entry-exits entry) (delq node (entry-exits entry)))
612       (if value
613           (delete-filter node (node-lvar node) value)
614           (unlink-node node)))))
615
616 \f
617 ;;;; combination IR1 optimization
618
619 ;;; Report as we try each transform?
620 #!+sb-show
621 (defvar *show-transforms-p* nil)
622
623 ;;; Do IR1 optimizations on a COMBINATION node.
624 (declaim (ftype (function (combination) (values)) ir1-optimize-combination))
625 (defun ir1-optimize-combination (node)
626   (when (lvar-reoptimize (basic-combination-fun node))
627     (propagate-fun-change node))
628   (let ((args (basic-combination-args node))
629         (kind (basic-combination-kind node)))
630     (case kind
631       (:local
632        (let ((fun (combination-lambda node)))
633          (if (eq (functional-kind fun) :let)
634              (propagate-let-args node fun)
635              (propagate-local-call-args node fun))))
636       ((:full :error)
637        (dolist (arg args)
638          (when arg
639            (setf (lvar-reoptimize arg) nil))))
640       (t
641        (dolist (arg args)
642          (when arg
643            (setf (lvar-reoptimize arg) nil)))
644
645        (let ((attr (fun-info-attributes kind)))
646          (when (and (ir1-attributep attr foldable)
647                     ;; KLUDGE: The next test could be made more sensitive,
648                     ;; only suppressing constant-folding of functions with
649                     ;; CALL attributes when they're actually passed
650                     ;; function arguments. -- WHN 19990918
651                     (not (ir1-attributep attr call))
652                     (every #'constant-lvar-p args)
653                     (node-lvar node)
654                     ;; Even if the function is foldable in principle,
655                     ;; it might be one of our low-level
656                     ;; implementation-specific functions. Such
657                     ;; functions don't necessarily exist at runtime on
658                     ;; a plain vanilla ANSI Common Lisp
659                     ;; cross-compilation host, in which case the
660                     ;; cross-compiler can't fold it because the
661                     ;; cross-compiler doesn't know how to evaluate it.
662                     #+sb-xc-host
663                     (or (fboundp (combination-fun-source-name node))
664                         (progn (format t ";;; !!! Unbound fun: (~S~{ ~S~})~%"
665                                        (combination-fun-source-name node)
666                                        (mapcar #'lvar-value args))
667                                nil)))
668            (constant-fold-call node)
669            (return-from ir1-optimize-combination)))
670
671        (let ((fun (fun-info-derive-type kind)))
672          (when fun
673            (let ((res (funcall fun node)))
674              (when res
675                (derive-node-type node (coerce-to-values res))
676                (maybe-terminate-block node nil)))))
677
678        (let ((fun (fun-info-optimizer kind)))
679          (unless (and fun (funcall fun node))
680            (dolist (x (fun-info-transforms kind))
681              #!+sb-show
682              (when *show-transforms-p*
683                (let* ((lvar (basic-combination-fun node))
684                       (fname (lvar-fun-name lvar t)))
685                  (/show "trying transform" x (transform-function x) "for" fname)))
686              (unless (ir1-transform node x)
687                #!+sb-show
688                (when *show-transforms-p*
689                  (/show "quitting because IR1-TRANSFORM result was NIL"))
690                (return))))))))
691
692   (values))
693
694 ;;; If NODE doesn't return (i.e. return type is NIL), then terminate
695 ;;; the block there, and link it to the component tail.
696 ;;;
697 ;;; Except when called during IR1 convertion, we delete the
698 ;;; continuation if it has no other uses. (If it does have other uses,
699 ;;; we reoptimize.)
700 ;;;
701 ;;; Termination on the basis of a continuation type is
702 ;;; inhibited when:
703 ;;; -- The continuation is deleted (hence the assertion is spurious), or
704 ;;; -- We are in IR1 conversion (where THE assertions are subject to
705 ;;;    weakening.) FIXME: Now THE assertions are not weakened, but new
706 ;;;    uses can(?) be added later. -- APD, 2003-07-17
707 ;;;
708 ;;; Why do we need to consider LVAR type? -- APD, 2003-07-30
709 (defun maybe-terminate-block (node ir1-converting-not-optimizing-p)
710   (declare (type (or basic-combination cast) node))
711   (let* ((block (node-block node))
712          (lvar (node-lvar node))
713          (ctran (node-next node))
714          (tail (component-tail (block-component block)))
715          (succ (first (block-succ block))))
716     (unless (or (and (eq node (block-last block)) (eq succ tail))
717                 (block-delete-p block))
718       (when (eq (node-derived-type node) *empty-type*)
719         (cond (ir1-converting-not-optimizing-p
720                (cond
721                  ((block-last block)
722                   (aver (eq (block-last block) node)))
723                  (t
724                   (setf (block-last block) node)
725                   (setf (ctran-use ctran) nil)
726                   (setf (ctran-kind ctran) :unused)
727                   (setf (ctran-block ctran) nil)
728                   (setf (node-next node) nil)
729                   (link-blocks block (ctran-starts-block ctran)))))
730               (t
731                (node-ends-block node)))
732
733         (unlink-blocks block (first (block-succ block)))
734         (setf (component-reanalyze (block-component block)) t)
735         (aver (not (block-succ block)))
736         (link-blocks block tail)
737         (if ir1-converting-not-optimizing-p
738             (%delete-lvar-use node)
739             (delete-lvar-use node))
740         t))))
741
742 ;;; This is called both by IR1 conversion and IR1 optimization when
743 ;;; they have verified the type signature for the call, and are
744 ;;; wondering if something should be done to special-case the call. If
745 ;;; CALL is a call to a global function, then see whether it defined
746 ;;; or known:
747 ;;; -- If a DEFINED-FUN should be inline expanded, then convert
748 ;;;    the expansion and change the call to call it. Expansion is
749 ;;;    enabled if :INLINE or if SPACE=0. If the FUNCTIONAL slot is
750 ;;;    true, we never expand, since this function has already been
751 ;;;    converted. Local call analysis will duplicate the definition
752 ;;;    if necessary. We claim that the parent form is LABELS for
753 ;;;    context declarations, since we don't want it to be considered
754 ;;;    a real global function.
755 ;;; -- If it is a known function, mark it as such by setting the KIND.
756 ;;;
757 ;;; We return the leaf referenced (NIL if not a leaf) and the
758 ;;; FUN-INFO assigned.
759 (defun recognize-known-call (call ir1-converting-not-optimizing-p)
760   (declare (type combination call))
761   (let* ((ref (lvar-uses (basic-combination-fun call)))
762          (leaf (when (ref-p ref) (ref-leaf ref)))
763          (inlinep (if (defined-fun-p leaf)
764                       (defined-fun-inlinep leaf)
765                       :no-chance)))
766     (cond
767      ((eq inlinep :notinline) (values nil nil))
768      ((not (and (global-var-p leaf)
769                 (eq (global-var-kind leaf) :global-function)))
770       (values leaf nil))
771      ((and (ecase inlinep
772              (:inline t)
773              (:no-chance nil)
774              ((nil :maybe-inline) (policy call (zerop space))))
775            (defined-fun-p leaf)
776            (defined-fun-inline-expansion leaf)
777            (let ((fun (defined-fun-functional leaf)))
778              (or (not fun)
779                  (and (eq inlinep :inline) (functional-kind fun))))
780            (inline-expansion-ok call))
781       (flet (;; FIXME: Is this what the old CMU CL internal documentation
782              ;; called semi-inlining? A more descriptive name would
783              ;; be nice. -- WHN 2002-01-07
784              (frob ()
785                (let ((res (ir1-convert-lambda-for-defun
786                            (defined-fun-inline-expansion leaf)
787                            leaf t
788                            #'ir1-convert-inline-lambda)))
789                  (setf (defined-fun-functional leaf) res)
790                  (change-ref-leaf ref res))))
791         (if ir1-converting-not-optimizing-p
792             (frob)
793             (with-ir1-environment-from-node call
794               (frob)
795               (locall-analyze-component *current-component*))))
796
797       (values (ref-leaf (lvar-uses (basic-combination-fun call)))
798               nil))
799      (t
800       (let ((info (info :function :info (leaf-source-name leaf))))
801         (if info
802             (values leaf (setf (basic-combination-kind call) info))
803             (values leaf nil)))))))
804
805 ;;; Check whether CALL satisfies TYPE. If so, apply the type to the
806 ;;; call, and do MAYBE-TERMINATE-BLOCK and return the values of
807 ;;; RECOGNIZE-KNOWN-CALL. If an error, set the combination kind and
808 ;;; return NIL, NIL. If the type is just FUNCTION, then skip the
809 ;;; syntax check, arg/result type processing, but still call
810 ;;; RECOGNIZE-KNOWN-CALL, since the call might be to a known lambda,
811 ;;; and that checking is done by local call analysis.
812 (defun validate-call-type (call type ir1-converting-not-optimizing-p)
813   (declare (type combination call) (type ctype type))
814   (cond ((not (fun-type-p type))
815          (aver (multiple-value-bind (val win)
816                    (csubtypep type (specifier-type 'function))
817                  (or val (not win))))
818          (recognize-known-call call ir1-converting-not-optimizing-p))
819         ((valid-fun-use call type
820                         :argument-test #'always-subtypep
821                         :result-test #'always-subtypep
822                         ;; KLUDGE: Common Lisp is such a dynamic
823                         ;; language that all we can do here in
824                         ;; general is issue a STYLE-WARNING. It
825                         ;; would be nice to issue a full WARNING
826                         ;; in the special case of of type
827                         ;; mismatches within a compilation unit
828                         ;; (as in section 3.2.2.3 of the spec)
829                         ;; but at least as of sbcl-0.6.11, we
830                         ;; don't keep track of whether the
831                         ;; mismatched data came from the same
832                         ;; compilation unit, so we can't do that.
833                         ;; -- WHN 2001-02-11
834                         ;;
835                         ;; FIXME: Actually, I think we could
836                         ;; issue a full WARNING if the call
837                         ;; violates a DECLAIM FTYPE.
838                         :lossage-fun #'compiler-style-warn
839                         :unwinnage-fun #'compiler-notify)
840          (assert-call-type call type)
841          (maybe-terminate-block call ir1-converting-not-optimizing-p)
842          (recognize-known-call call ir1-converting-not-optimizing-p))
843         (t
844          (setf (combination-kind call) :error)
845          (values nil nil))))
846
847 ;;; This is called by IR1-OPTIMIZE when the function for a call has
848 ;;; changed. If the call is local, we try to LET-convert it, and
849 ;;; derive the result type. If it is a :FULL call, we validate it
850 ;;; against the type, which recognizes known calls, does inline
851 ;;; expansion, etc. If a call to a predicate in a non-conditional
852 ;;; position or to a function with a source transform, then we
853 ;;; reconvert the form to give IR1 another chance.
854 (defun propagate-fun-change (call)
855   (declare (type combination call))
856   (let ((*compiler-error-context* call)
857         (fun-lvar (basic-combination-fun call)))
858     (setf (lvar-reoptimize fun-lvar) nil)
859     (case (combination-kind call)
860       (:local
861        (let ((fun (combination-lambda call)))
862          (maybe-let-convert fun)
863          (unless (member (functional-kind fun) '(:let :assignment :deleted))
864            (derive-node-type call (tail-set-type (lambda-tail-set fun))))))
865       (:full
866        (multiple-value-bind (leaf info)
867            (validate-call-type call (lvar-type fun-lvar) nil)
868          (cond ((functional-p leaf)
869                 (convert-call-if-possible
870                  (lvar-uses (basic-combination-fun call))
871                  call))
872                ((not leaf))
873                ((and (leaf-has-source-name-p leaf)
874                      (or (info :function :source-transform (leaf-source-name leaf))
875                          (and info
876                               (ir1-attributep (fun-info-attributes info)
877                                               predicate)
878                               (let ((lvar (node-lvar call)))
879                                 (and lvar (not (if-p (lvar-dest lvar))))))))
880                 (let ((name (leaf-source-name leaf))
881                       (dummies (make-gensym-list
882                                 (length (combination-args call)))))
883                   (transform-call call
884                                   `(lambda ,dummies
885                                      (,@(if (symbolp name)
886                                             `(,name)
887                                             `(funcall #',name))
888                                         ,@dummies))
889                                   (leaf-source-name leaf)))))))))
890   (values))
891 \f
892 ;;;; known function optimization
893
894 ;;; Add a failed optimization note to FAILED-OPTIMZATIONS for NODE,
895 ;;; FUN and ARGS. If there is already a note for NODE and TRANSFORM,
896 ;;; replace it, otherwise add a new one.
897 (defun record-optimization-failure (node transform args)
898   (declare (type combination node) (type transform transform)
899            (type (or fun-type list) args))
900   (let* ((table (component-failed-optimizations *component-being-compiled*))
901          (found (assoc transform (gethash node table))))
902     (if found
903         (setf (cdr found) args)
904         (push (cons transform args) (gethash node table))))
905   (values))
906
907 ;;; Attempt to transform NODE using TRANSFORM-FUNCTION, subject to the
908 ;;; call type constraint TRANSFORM-TYPE. If we are inhibited from
909 ;;; doing the transform for some reason and FLAME is true, then we
910 ;;; make a note of the message in FAILED-OPTIMIZATIONS for IR1
911 ;;; finalize to pick up. We return true if the transform failed, and
912 ;;; thus further transformation should be attempted. We return false
913 ;;; if either the transform succeeded or was aborted.
914 (defun ir1-transform (node transform)
915   (declare (type combination node) (type transform transform))
916   (let* ((type (transform-type transform))
917          (fun (transform-function transform))
918          (constrained (fun-type-p type))
919          (table (component-failed-optimizations *component-being-compiled*))
920          (flame (if (transform-important transform)
921                     (policy node (>= speed inhibit-warnings))
922                     (policy node (> speed inhibit-warnings))))
923          (*compiler-error-context* node))
924     (cond ((or (not constrained)
925                (valid-fun-use node type))
926            (multiple-value-bind (severity args)
927                (catch 'give-up-ir1-transform
928                  (transform-call node
929                                  (funcall fun node)
930                                  (combination-fun-source-name node))
931                  (values :none nil))
932              (ecase severity
933                (:none
934                 (remhash node table)
935                 nil)
936                (:aborted
937                 (setf (combination-kind node) :error)
938                 (when args
939                   (apply #'compiler-warn args))
940                 (remhash node table)
941                 nil)
942                (:failure
943                 (if args
944                     (when flame
945                       (record-optimization-failure node transform args))
946                     (setf (gethash node table)
947                           (remove transform (gethash node table) :key #'car)))
948                 t)
949                (:delayed
950                  (remhash node table)
951                  nil))))
952           ((and flame
953                 (valid-fun-use node
954                                type
955                                :argument-test #'types-equal-or-intersect
956                                :result-test #'values-types-equal-or-intersect))
957            (record-optimization-failure node transform type)
958            t)
959           (t
960            t))))
961
962 ;;; When we don't like an IR1 transform, we throw the severity/reason
963 ;;; and args.
964 ;;;
965 ;;; GIVE-UP-IR1-TRANSFORM is used to throw out of an IR1 transform,
966 ;;; aborting this attempt to transform the call, but admitting the
967 ;;; possibility that this or some other transform will later succeed.
968 ;;; If arguments are supplied, they are format arguments for an
969 ;;; efficiency note.
970 ;;;
971 ;;; ABORT-IR1-TRANSFORM is used to throw out of an IR1 transform and
972 ;;; force a normal call to the function at run time. No further
973 ;;; optimizations will be attempted.
974 ;;;
975 ;;; DELAY-IR1-TRANSFORM is used to throw out of an IR1 transform, and
976 ;;; delay the transform on the node until later. REASONS specifies
977 ;;; when the transform will be later retried. The :OPTIMIZE reason
978 ;;; causes the transform to be delayed until after the current IR1
979 ;;; optimization pass. The :CONSTRAINT reason causes the transform to
980 ;;; be delayed until after constraint propagation.
981 ;;;
982 ;;; FIXME: Now (0.6.11.44) that there are 4 variants of this (GIVE-UP,
983 ;;; ABORT, DELAY/:OPTIMIZE, DELAY/:CONSTRAINT) and we're starting to
984 ;;; do CASE operations on the various REASON values, it might be a
985 ;;; good idea to go OO, representing the reasons by objects, using
986 ;;; CLOS methods on the objects instead of CASE, and (possibly) using
987 ;;; SIGNAL instead of THROW.
988 (declaim (ftype (function (&rest t) nil) give-up-ir1-transform))
989 (defun give-up-ir1-transform (&rest args)
990   (throw 'give-up-ir1-transform (values :failure args)))
991 (defun abort-ir1-transform (&rest args)
992   (throw 'give-up-ir1-transform (values :aborted args)))
993 (defun delay-ir1-transform (node &rest reasons)
994   (let ((assoc (assoc node *delayed-ir1-transforms*)))
995     (cond ((not assoc)
996             (setf *delayed-ir1-transforms*
997                     (acons node reasons *delayed-ir1-transforms*))
998             (throw 'give-up-ir1-transform :delayed))
999           ((cdr assoc)
1000             (dolist (reason reasons)
1001               (pushnew reason (cdr assoc)))
1002             (throw 'give-up-ir1-transform :delayed)))))
1003
1004 ;;; Clear any delayed transform with no reasons - these should have
1005 ;;; been tried in the last pass. Then remove the reason from the
1006 ;;; delayed transform reasons, and if any become empty then set
1007 ;;; reoptimize flags for the node. Return true if any transforms are
1008 ;;; to be retried.
1009 (defun retry-delayed-ir1-transforms (reason)
1010   (setf *delayed-ir1-transforms*
1011         (remove-if-not #'cdr *delayed-ir1-transforms*))
1012   (let ((reoptimize nil))
1013     (dolist (assoc *delayed-ir1-transforms*)
1014       (let ((reasons (remove reason (cdr assoc))))
1015         (setf (cdr assoc) reasons)
1016         (unless reasons
1017           (let ((node (car assoc)))
1018             (unless (node-deleted node)
1019               (setf reoptimize t)
1020               (setf (node-reoptimize node) t)
1021               (let ((block (node-block node)))
1022                 (setf (block-reoptimize block) t)
1023                 (setf (component-reoptimize (block-component block)) t)))))))
1024     reoptimize))
1025
1026 ;;; Take the lambda-expression RES, IR1 convert it in the proper
1027 ;;; environment, and then install it as the function for the call
1028 ;;; NODE. We do local call analysis so that the new function is
1029 ;;; integrated into the control flow.
1030 ;;;
1031 ;;; We require the original function source name in order to generate
1032 ;;; a meaningful debug name for the lambda we set up. (It'd be
1033 ;;; possible to do this starting from debug names as well as source
1034 ;;; names, but as of sbcl-0.7.1.5, there was no need for this
1035 ;;; generality, since source names are always known to our callers.)
1036 (defun transform-call (call res source-name)
1037   (declare (type combination call) (list res))
1038   (aver (and (legal-fun-name-p source-name)
1039              (not (eql source-name '.anonymous.))))
1040   (node-ends-block call)
1041   (with-ir1-environment-from-node call
1042     (with-component-last-block (*current-component*
1043                                 (block-next (node-block call)))
1044       (let ((new-fun (ir1-convert-inline-lambda
1045                       res
1046                       :debug-name (debug-namify "LAMBDA-inlined ~A"
1047                                                 (as-debug-name
1048                                                  source-name
1049                                                  "<unknown function>"))))
1050             (ref (lvar-use (combination-fun call))))
1051         (change-ref-leaf ref new-fun)
1052         (setf (combination-kind call) :full)
1053         (locall-analyze-component *current-component*))))
1054   (values))
1055
1056 ;;; Replace a call to a foldable function of constant arguments with
1057 ;;; the result of evaluating the form. If there is an error during the
1058 ;;; evaluation, we give a warning and leave the call alone, making the
1059 ;;; call a :ERROR call.
1060 ;;;
1061 ;;; If there is more than one value, then we transform the call into a
1062 ;;; VALUES form.
1063 (defun constant-fold-call (call)
1064   (let ((args (mapcar #'lvar-value (combination-args call)))
1065         (fun-name (combination-fun-source-name call)))
1066     (multiple-value-bind (values win)
1067         (careful-call fun-name
1068                       args
1069                       call
1070                       ;; Note: CMU CL had COMPILER-WARN here, and that
1071                       ;; seems more natural, but it's probably not.
1072                       ;;
1073                       ;; It's especially not while bug 173 exists:
1074                       ;; Expressions like
1075                       ;;   (COND (END
1076                       ;;          (UNLESS (OR UNSAFE? (<= END SIZE)))
1077                       ;;            ...))
1078                       ;; can cause constant-folding TYPE-ERRORs (in
1079                       ;; #'<=) when END can be proved to be NIL, even
1080                       ;; though the code is perfectly legal and safe
1081                       ;; because a NIL value of END means that the
1082                       ;; #'<= will never be executed.
1083                       ;;
1084                       ;; Moreover, even without bug 173,
1085                       ;; quite-possibly-valid code like
1086                       ;;   (COND ((NONINLINED-PREDICATE END)
1087                       ;;          (UNLESS (<= END SIZE))
1088                       ;;            ...))
1089                       ;; (where NONINLINED-PREDICATE is something the
1090                       ;; compiler can't do at compile time, but which
1091                       ;; turns out to make the #'<= expression
1092                       ;; unreachable when END=NIL) could cause errors
1093                       ;; when the compiler tries to constant-fold (<=
1094                       ;; END SIZE).
1095                       ;;
1096                       ;; So, with or without bug 173, it'd be
1097                       ;; unnecessarily evil to do a full
1098                       ;; COMPILER-WARNING (and thus return FAILURE-P=T
1099                       ;; from COMPILE-FILE) for legal code, so we we
1100                       ;; use a wimpier COMPILE-STYLE-WARNING instead.
1101                       #'compiler-style-warn
1102                       "constant folding")
1103       (cond ((not win)
1104              (setf (combination-kind call) :error))
1105             ((and (proper-list-of-length-p values 1))
1106              (with-ir1-environment-from-node call
1107                (let* ((lvar (node-lvar call))
1108                       (prev (node-prev call))
1109                       (intermediate-ctran (make-ctran)))
1110                  (%delete-lvar-use call)
1111                  (setf (ctran-next prev) nil)
1112                  (setf (node-prev call) nil)
1113                  (reference-constant prev intermediate-ctran lvar
1114                                      (first values))
1115                  (link-node-to-previous-ctran call intermediate-ctran)
1116                  (reoptimize-lvar lvar)
1117                  (flush-combination call))))
1118             (t (let ((dummies (make-gensym-list (length args))))
1119                  (transform-call
1120                   call
1121                   `(lambda ,dummies
1122                      (declare (ignore ,@dummies))
1123                      (values ,@(mapcar (lambda (x) `',x) values)))
1124                   fun-name))))))
1125   (values))
1126 \f
1127 ;;;; local call optimization
1128
1129 ;;; Propagate TYPE to LEAF and its REFS, marking things changed. If
1130 ;;; the leaf type is a function type, then just leave it alone, since
1131 ;;; TYPE is never going to be more specific than that (and
1132 ;;; TYPE-INTERSECTION would choke.)
1133 (defun propagate-to-refs (leaf type)
1134   (declare (type leaf leaf) (type ctype type))
1135   (let ((var-type (leaf-type leaf)))
1136     (unless (fun-type-p var-type)
1137       (let ((int (type-approx-intersection2 var-type type)))
1138         (when (type/= int var-type)
1139           (setf (leaf-type leaf) int)
1140           (dolist (ref (leaf-refs leaf))
1141             (derive-node-type ref (make-single-value-type int))
1142             ;; KLUDGE: LET var substitution
1143             (let* ((lvar (node-lvar ref)))
1144               (when (and lvar (combination-p (lvar-dest lvar)))
1145                 (reoptimize-lvar lvar))))))
1146       (values))))
1147
1148 ;;; Iteration variable: exactly one SETQ of the form:
1149 ;;;
1150 ;;; (let ((var initial))
1151 ;;;   ...
1152 ;;;   (setq var (+ var step))
1153 ;;;   ...)
1154 (defun maybe-infer-iteration-var-type (var initial-type)
1155   (binding* ((sets (lambda-var-sets var) :exit-if-null)
1156              (set (first sets))
1157              (() (null (rest sets)) :exit-if-null)
1158              (set-use (principal-lvar-use (set-value set)))
1159              (() (and (combination-p set-use)
1160                       (fun-info-p (combination-kind set-use))
1161                       (eq (combination-fun-source-name set-use) '+))
1162                :exit-if-null)
1163              (+-args (basic-combination-args set-use))
1164              (() (and (proper-list-of-length-p +-args 2 2)
1165                       (let ((first (principal-lvar-use
1166                                     (first +-args))))
1167                         (and (ref-p first)
1168                              (eq (ref-leaf first) var))))
1169                :exit-if-null)
1170              (step-type (lvar-type (second +-args)))
1171              (set-type (lvar-type (set-value set))))
1172     (when (and (numeric-type-p initial-type)
1173                (numeric-type-p step-type)
1174                (numeric-type-equal initial-type step-type))
1175       (multiple-value-bind (low high)
1176           (cond ((csubtypep step-type (specifier-type '(real 0 *)))
1177                  (values (numeric-type-low initial-type)
1178                          (when (and (numeric-type-p set-type)
1179                                     (numeric-type-equal set-type initial-type))
1180                            (numeric-type-high set-type))))
1181                 ((csubtypep step-type (specifier-type '(real * 0)))
1182                  (values (when (and (numeric-type-p set-type)
1183                                     (numeric-type-equal set-type initial-type))
1184                            (numeric-type-low set-type))
1185                          (numeric-type-high initial-type)))
1186                 (t
1187                  (values nil nil)))
1188         (modified-numeric-type initial-type
1189                                :low low
1190                                :high high
1191                                :enumerable nil)))))
1192 (deftransform + ((x y) * * :result result)
1193   "check for iteration variable reoptimization"
1194   (let ((dest (principal-lvar-end result))
1195         (use (principal-lvar-use x)))
1196     (when (and (ref-p use)
1197                (set-p dest)
1198                (eq (ref-leaf use)
1199                    (set-var dest)))
1200       (reoptimize-lvar (set-value dest))))
1201   (give-up-ir1-transform))
1202
1203 ;;; Figure out the type of a LET variable that has sets. We compute
1204 ;;; the union of the INITIAL-TYPE and the types of all the set
1205 ;;; values and to a PROPAGATE-TO-REFS with this type.
1206 (defun propagate-from-sets (var initial-type)
1207   (collect ((res initial-type type-union))
1208     (dolist (set (basic-var-sets var))
1209       (let ((type (lvar-type (set-value set))))
1210         (res type)
1211         (when (node-reoptimize set)
1212           (derive-node-type set (make-single-value-type type))
1213           (setf (node-reoptimize set) nil))))
1214     (let ((res (res)))
1215       (awhen (maybe-infer-iteration-var-type var initial-type)
1216         (setq res it))
1217       (propagate-to-refs var res)))
1218   (values))
1219
1220 ;;; If a LET variable, find the initial value's type and do
1221 ;;; PROPAGATE-FROM-SETS. We also derive the VALUE's type as the node's
1222 ;;; type.
1223 (defun ir1-optimize-set (node)
1224   (declare (type cset node))
1225   (let ((var (set-var node)))
1226     (when (and (lambda-var-p var) (leaf-refs var))
1227       (let ((home (lambda-var-home var)))
1228         (when (eq (functional-kind home) :let)
1229           (let* ((initial-value (let-var-initial-value var))
1230                  (initial-type (lvar-type initial-value)))
1231             (setf (lvar-reoptimize initial-value) nil)
1232             (propagate-from-sets var initial-type))))))
1233
1234   (derive-node-type node (make-single-value-type
1235                           (lvar-type (set-value node))))
1236   (values))
1237
1238 ;;; Return true if the value of REF will always be the same (and is
1239 ;;; thus legal to substitute.)
1240 (defun constant-reference-p (ref)
1241   (declare (type ref ref))
1242   (let ((leaf (ref-leaf ref)))
1243     (typecase leaf
1244       ((or constant functional) t)
1245       (lambda-var
1246        (null (lambda-var-sets leaf)))
1247       (defined-fun
1248        (not (eq (defined-fun-inlinep leaf) :notinline)))
1249       (global-var
1250        (case (global-var-kind leaf)
1251          (:global-function
1252           (let ((name (leaf-source-name leaf)))
1253             (or #-sb-xc-host
1254                 (eq (symbol-package (fun-name-block-name name))
1255                     *cl-package*)
1256                 (info :function :info name)))))))))
1257
1258 ;;; If we have a non-set LET var with a single use, then (if possible)
1259 ;;; replace the variable reference's LVAR with the arg lvar.
1260 ;;;
1261 ;;; We change the REF to be a reference to NIL with unused value, and
1262 ;;; let it be flushed as dead code. A side effect of this substitution
1263 ;;; is to delete the variable.
1264 (defun substitute-single-use-lvar (arg var)
1265   (declare (type lvar arg) (type lambda-var var))
1266   (binding* ((ref (first (leaf-refs var)))
1267              (lvar (node-lvar ref) :exit-if-null)
1268              (dest (lvar-dest lvar)))
1269     (when (and
1270            ;; Think about (LET ((A ...)) (IF ... A ...)): two
1271            ;; LVAR-USEs should not be met on one path.
1272            (eq (lvar-uses lvar) ref)
1273            (typecase dest
1274              ;; we should not change lifetime of unknown values lvars
1275              (cast
1276               (and (type-single-value-p (lvar-derived-type arg))
1277                    (multiple-value-bind (pdest pprev)
1278                        (principal-lvar-end lvar)
1279                      (declare (ignore pdest))
1280                      (lvar-single-value-p pprev))))
1281              (mv-combination
1282               (or (eq (basic-combination-fun dest) lvar)
1283                   (and (eq (basic-combination-kind dest) :local)
1284                        (type-single-value-p (lvar-derived-type arg)))))
1285              ((or creturn exit)
1286               ;; While CRETURN and EXIT nodes may be known-values,
1287               ;; they have their own complications, such as
1288               ;; substitution into CRETURN may create new tail calls.
1289               nil)
1290              (t
1291               (aver (lvar-single-value-p lvar))
1292               t))
1293            (eq (node-home-lambda ref)
1294                (lambda-home (lambda-var-home var))))
1295       (setf (node-derived-type ref) *wild-type*)
1296       (substitute-lvar-uses lvar arg)
1297       (delete-lvar-use ref)
1298       (change-ref-leaf ref (find-constant nil))
1299       (delete-ref ref)
1300       (unlink-node ref)
1301       (reoptimize-lvar lvar)
1302       t)))
1303
1304 ;;; Delete a LET, removing the call and bind nodes, and warning about
1305 ;;; any unreferenced variables. Note that FLUSH-DEAD-CODE will come
1306 ;;; along right away and delete the REF and then the lambda, since we
1307 ;;; flush the FUN lvar.
1308 (defun delete-let (clambda)
1309   (declare (type clambda clambda))
1310   (aver (functional-letlike-p clambda))
1311   (note-unreferenced-vars clambda)
1312   (let ((call (let-combination clambda)))
1313     (flush-dest (basic-combination-fun call))
1314     (unlink-node call)
1315     (unlink-node (lambda-bind clambda))
1316     (setf (lambda-bind clambda) nil))
1317   (values))
1318
1319 ;;; This function is called when one of the arguments to a LET
1320 ;;; changes. We look at each changed argument. If the corresponding
1321 ;;; variable is set, then we call PROPAGATE-FROM-SETS. Otherwise, we
1322 ;;; consider substituting for the variable, and also propagate
1323 ;;; derived-type information for the arg to all the VAR's refs.
1324 ;;;
1325 ;;; Substitution is inhibited when the arg leaf's derived type isn't a
1326 ;;; subtype of the argument's leaf type. This prevents type checking
1327 ;;; from being defeated, and also ensures that the best representation
1328 ;;; for the variable can be used.
1329 ;;;
1330 ;;; Substitution of individual references is inhibited if the
1331 ;;; reference is in a different component from the home. This can only
1332 ;;; happen with closures over top level lambda vars. In such cases,
1333 ;;; the references may have already been compiled, and thus can't be
1334 ;;; retroactively modified.
1335 ;;;
1336 ;;; If all of the variables are deleted (have no references) when we
1337 ;;; are done, then we delete the LET.
1338 ;;;
1339 ;;; Note that we are responsible for clearing the LVAR-REOPTIMIZE
1340 ;;; flags.
1341 (defun propagate-let-args (call fun)
1342   (declare (type combination call) (type clambda fun))
1343   (loop for arg in (combination-args call)
1344         and var in (lambda-vars fun) do
1345     (when (and arg (lvar-reoptimize arg))
1346       (setf (lvar-reoptimize arg) nil)
1347       (cond
1348         ((lambda-var-sets var)
1349          (propagate-from-sets var (lvar-type arg)))
1350         ((let ((use (lvar-uses arg)))
1351            (when (ref-p use)
1352              (let ((leaf (ref-leaf use)))
1353                (when (and (constant-reference-p use)
1354                           (csubtypep (leaf-type leaf)
1355                                      ;; (NODE-DERIVED-TYPE USE) would
1356                                      ;; be better -- APD, 2003-05-15
1357                                      (leaf-type var)))
1358                  (propagate-to-refs var (lvar-type arg))
1359                  (let ((use-component (node-component use)))
1360                    (prog1 (substitute-leaf-if
1361                            (lambda (ref)
1362                              (cond ((eq (node-component ref) use-component)
1363                                     t)
1364                                    (t
1365                                     (aver (lambda-toplevelish-p (lambda-home fun)))
1366                                     nil)))
1367                            leaf var)))
1368                  t)))))
1369         ((and (null (rest (leaf-refs var)))
1370               (substitute-single-use-lvar arg var)))
1371         (t
1372          (propagate-to-refs var (lvar-type arg))))))
1373
1374   (when (every #'not (combination-args call))
1375     (delete-let fun))
1376
1377   (values))
1378
1379 ;;; This function is called when one of the args to a non-LET local
1380 ;;; call changes. For each changed argument corresponding to an unset
1381 ;;; variable, we compute the union of the types across all calls and
1382 ;;; propagate this type information to the var's refs.
1383 ;;;
1384 ;;; If the function has an XEP, then we don't do anything, since we
1385 ;;; won't discover anything.
1386 ;;;
1387 ;;; We can clear the LVAR-REOPTIMIZE flags for arguments in all calls
1388 ;;; corresponding to changed arguments in CALL, since the only use in
1389 ;;; IR1 optimization of the REOPTIMIZE flag for local call args is
1390 ;;; right here.
1391 (defun propagate-local-call-args (call fun)
1392   (declare (type combination call) (type clambda fun))
1393
1394   (unless (or (functional-entry-fun fun)
1395               (lambda-optional-dispatch fun))
1396     (let* ((vars (lambda-vars fun))
1397            (union (mapcar (lambda (arg var)
1398                             (when (and arg
1399                                        (lvar-reoptimize arg)
1400                                        (null (basic-var-sets var)))
1401                               (lvar-type arg)))
1402                           (basic-combination-args call)
1403                           vars))
1404            (this-ref (lvar-use (basic-combination-fun call))))
1405
1406       (dolist (arg (basic-combination-args call))
1407         (when arg
1408           (setf (lvar-reoptimize arg) nil)))
1409
1410       (dolist (ref (leaf-refs fun))
1411         (let ((dest (node-dest ref)))
1412           (unless (or (eq ref this-ref) (not dest))
1413             (setq union
1414                   (mapcar (lambda (this-arg old)
1415                             (when old
1416                               (setf (lvar-reoptimize this-arg) nil)
1417                               (type-union (lvar-type this-arg) old)))
1418                           (basic-combination-args dest)
1419                           union)))))
1420
1421       (loop for var in vars
1422             and type in union
1423             when type do (propagate-to-refs var type))))
1424
1425   (values))
1426 \f
1427 ;;;; multiple values optimization
1428
1429 ;;; Do stuff to notice a change to a MV combination node. There are
1430 ;;; two main branches here:
1431 ;;;  -- If the call is local, then it is already a MV let, or should
1432 ;;;     become one. Note that although all :LOCAL MV calls must eventually
1433 ;;;     be converted to :MV-LETs, there can be a window when the call
1434 ;;;     is local, but has not been LET converted yet. This is because
1435 ;;;     the entry-point lambdas may have stray references (in other
1436 ;;;     entry points) that have not been deleted yet.
1437 ;;;  -- The call is full. This case is somewhat similar to the non-MV
1438 ;;;     combination optimization: we propagate return type information and
1439 ;;;     notice non-returning calls. We also have an optimization
1440 ;;;     which tries to convert MV-CALLs into MV-binds.
1441 (defun ir1-optimize-mv-combination (node)
1442   (ecase (basic-combination-kind node)
1443     (:local
1444      (let ((fun-lvar (basic-combination-fun node)))
1445        (when (lvar-reoptimize fun-lvar)
1446          (setf (lvar-reoptimize fun-lvar) nil)
1447          (maybe-let-convert (combination-lambda node))))
1448      (setf (lvar-reoptimize (first (basic-combination-args node))) nil)
1449      (when (eq (functional-kind (combination-lambda node)) :mv-let)
1450        (unless (convert-mv-bind-to-let node)
1451          (ir1-optimize-mv-bind node))))
1452     (:full
1453      (let* ((fun (basic-combination-fun node))
1454             (fun-changed (lvar-reoptimize fun))
1455             (args (basic-combination-args node)))
1456        (when fun-changed
1457          (setf (lvar-reoptimize fun) nil)
1458          (let ((type (lvar-type fun)))
1459            (when (fun-type-p type)
1460              (derive-node-type node (fun-type-returns type))))
1461          (maybe-terminate-block node nil)
1462          (let ((use (lvar-uses fun)))
1463            (when (and (ref-p use) (functional-p (ref-leaf use)))
1464              (convert-call-if-possible use node)
1465              (when (eq (basic-combination-kind node) :local)
1466                (maybe-let-convert (ref-leaf use))))))
1467        (unless (or (eq (basic-combination-kind node) :local)
1468                    (eq (lvar-fun-name fun) '%throw))
1469          (ir1-optimize-mv-call node))
1470        (dolist (arg args)
1471          (setf (lvar-reoptimize arg) nil))))
1472     (:error))
1473   (values))
1474
1475 ;;; Propagate derived type info from the values lvar to the vars.
1476 (defun ir1-optimize-mv-bind (node)
1477   (declare (type mv-combination node))
1478   (let* ((arg (first (basic-combination-args node)))
1479          (vars (lambda-vars (combination-lambda node)))
1480          (n-vars (length vars))
1481          (types (values-type-in (lvar-derived-type arg)
1482                                 n-vars)))
1483     (loop for var in vars
1484           and type in types
1485           do (if (basic-var-sets var)
1486                  (propagate-from-sets var type)
1487                  (propagate-to-refs var type)))
1488     (setf (lvar-reoptimize arg) nil))
1489   (values))
1490
1491 ;;; If possible, convert a general MV call to an MV-BIND. We can do
1492 ;;; this if:
1493 ;;; -- The call has only one argument, and
1494 ;;; -- The function has a known fixed number of arguments, or
1495 ;;; -- The argument yields a known fixed number of values.
1496 ;;;
1497 ;;; What we do is change the function in the MV-CALL to be a lambda
1498 ;;; that "looks like an MV bind", which allows
1499 ;;; IR1-OPTIMIZE-MV-COMBINATION to notice that this call can be
1500 ;;; converted (the next time around.) This new lambda just calls the
1501 ;;; actual function with the MV-BIND variables as arguments. Note that
1502 ;;; this new MV bind is not let-converted immediately, as there are
1503 ;;; going to be stray references from the entry-point functions until
1504 ;;; they get deleted.
1505 ;;;
1506 ;;; In order to avoid loss of argument count checking, we only do the
1507 ;;; transformation according to a known number of expected argument if
1508 ;;; safety is unimportant. We can always convert if we know the number
1509 ;;; of actual values, since the normal call that we build will still
1510 ;;; do any appropriate argument count checking.
1511 ;;;
1512 ;;; We only attempt the transformation if the called function is a
1513 ;;; constant reference. This allows us to just splice the leaf into
1514 ;;; the new function, instead of trying to somehow bind the function
1515 ;;; expression. The leaf must be constant because we are evaluating it
1516 ;;; again in a different place. This also has the effect of squelching
1517 ;;; multiple warnings when there is an argument count error.
1518 (defun ir1-optimize-mv-call (node)
1519   (let ((fun (basic-combination-fun node))
1520         (*compiler-error-context* node)
1521         (ref (lvar-uses (basic-combination-fun node)))
1522         (args (basic-combination-args node)))
1523
1524     (unless (and (ref-p ref) (constant-reference-p ref)
1525                  (singleton-p args))
1526       (return-from ir1-optimize-mv-call))
1527
1528     (multiple-value-bind (min max)
1529         (fun-type-nargs (lvar-type fun))
1530       (let ((total-nvals
1531              (multiple-value-bind (types nvals)
1532                  (values-types (lvar-derived-type (first args)))
1533                (declare (ignore types))
1534                (if (eq nvals :unknown) nil nvals))))
1535
1536         (when total-nvals
1537           (when (and min (< total-nvals min))
1538             (compiler-warn
1539              "MULTIPLE-VALUE-CALL with ~R values when the function expects ~
1540              at least ~R."
1541              total-nvals min)
1542             (setf (basic-combination-kind node) :error)
1543             (return-from ir1-optimize-mv-call))
1544           (when (and max (> total-nvals max))
1545             (compiler-warn
1546              "MULTIPLE-VALUE-CALL with ~R values when the function expects ~
1547              at most ~R."
1548              total-nvals max)
1549             (setf (basic-combination-kind node) :error)
1550             (return-from ir1-optimize-mv-call)))
1551
1552         (let ((count (cond (total-nvals)
1553                            ((and (policy node (zerop verify-arg-count))
1554                                  (eql min max))
1555                             min)
1556                            (t nil))))
1557           (when count
1558             (with-ir1-environment-from-node node
1559               (let* ((dums (make-gensym-list count))
1560                      (ignore (gensym))
1561                      (fun (ir1-convert-lambda
1562                            `(lambda (&optional ,@dums &rest ,ignore)
1563                               (declare (ignore ,ignore))
1564                               (funcall ,(ref-leaf ref) ,@dums)))))
1565                 (change-ref-leaf ref fun)
1566                 (aver (eq (basic-combination-kind node) :full))
1567                 (locall-analyze-component *current-component*)
1568                 (aver (eq (basic-combination-kind node) :local)))))))))
1569   (values))
1570
1571 ;;; If we see:
1572 ;;;    (multiple-value-bind
1573 ;;;     (x y)
1574 ;;;     (values xx yy)
1575 ;;;      ...)
1576 ;;; Convert to:
1577 ;;;    (let ((x xx)
1578 ;;;       (y yy))
1579 ;;;      ...)
1580 ;;;
1581 ;;; What we actually do is convert the VALUES combination into a
1582 ;;; normal LET combination calling the original :MV-LET lambda. If
1583 ;;; there are extra args to VALUES, discard the corresponding
1584 ;;; lvars. If there are insufficient args, insert references to NIL.
1585 (defun convert-mv-bind-to-let (call)
1586   (declare (type mv-combination call))
1587   (let* ((arg (first (basic-combination-args call)))
1588          (use (lvar-uses arg)))
1589     (when (and (combination-p use)
1590                (eq (lvar-fun-name (combination-fun use))
1591                    'values))
1592       (let* ((fun (combination-lambda call))
1593              (vars (lambda-vars fun))
1594              (vals (combination-args use))
1595              (nvars (length vars))
1596              (nvals (length vals)))
1597         (cond ((> nvals nvars)
1598                (mapc #'flush-dest (subseq vals nvars))
1599                (setq vals (subseq vals 0 nvars)))
1600               ((< nvals nvars)
1601                (with-ir1-environment-from-node use
1602                  (let ((node-prev (node-prev use)))
1603                    (setf (node-prev use) nil)
1604                    (setf (ctran-next node-prev) nil)
1605                    (collect ((res vals))
1606                      (loop for count below (- nvars nvals)
1607                            for prev = node-prev then ctran
1608                            for ctran = (make-ctran)
1609                            and lvar = (make-lvar use)
1610                            do (reference-constant prev ctran lvar nil)
1611                               (res lvar)
1612                            finally (link-node-to-previous-ctran
1613                                     use ctran))
1614                      (setq vals (res)))))))
1615         (setf (combination-args use) vals)
1616         (flush-dest (combination-fun use))
1617         (let ((fun-lvar (basic-combination-fun call)))
1618           (setf (lvar-dest fun-lvar) use)
1619           (setf (combination-fun use) fun-lvar)
1620           (flush-lvar-externally-checkable-type fun-lvar))
1621         (setf (combination-kind use) :local)
1622         (setf (functional-kind fun) :let)
1623         (flush-dest (first (basic-combination-args call)))
1624         (unlink-node call)
1625         (when vals
1626           (reoptimize-lvar (first vals)))
1627         (propagate-to-args use fun)
1628         (reoptimize-call use))
1629       t)))
1630
1631 ;;; If we see:
1632 ;;;    (values-list (list x y z))
1633 ;;;
1634 ;;; Convert to:
1635 ;;;    (values x y z)
1636 ;;;
1637 ;;; In implementation, this is somewhat similar to
1638 ;;; CONVERT-MV-BIND-TO-LET. We grab the args of LIST and make them
1639 ;;; args of the VALUES-LIST call, flushing the old argument lvar
1640 ;;; (allowing the LIST to be flushed.)
1641 ;;;
1642 ;;; FIXME: Thus we lose possible type assertions on (LIST ...).
1643 (defoptimizer (values-list optimizer) ((list) node)
1644   (let ((use (lvar-uses list)))
1645     (when (and (combination-p use)
1646                (eq (lvar-fun-name (combination-fun use))
1647                    'list))
1648
1649       ;; FIXME: VALUES might not satisfy an assertion on NODE-LVAR.
1650       (change-ref-leaf (lvar-uses (combination-fun node))
1651                        (find-free-fun 'values "in a strange place"))
1652       (setf (combination-kind node) :full)
1653       (let ((args (combination-args use)))
1654         (dolist (arg args)
1655           (setf (lvar-dest arg) node)
1656           (flush-lvar-externally-checkable-type arg))
1657         (setf (combination-args use) nil)
1658         (flush-dest list)
1659         (setf (combination-args node) args))
1660       t)))
1661
1662 ;;; If VALUES appears in a non-MV context, then effectively convert it
1663 ;;; to a PROG1. This allows the computation of the additional values
1664 ;;; to become dead code.
1665 (deftransform values ((&rest vals) * * :node node)
1666   (unless (lvar-single-value-p (node-lvar node))
1667     (give-up-ir1-transform))
1668   (setf (node-derived-type node) *wild-type*)
1669   (principal-lvar-single-valuify (node-lvar node))
1670   (if vals
1671       (let ((dummies (make-gensym-list (length (cdr vals)))))
1672         `(lambda (val ,@dummies)
1673            (declare (ignore ,@dummies))
1674            val))
1675       nil))
1676
1677 ;;; TODO:
1678 ;;; - CAST chains;
1679 (defun ir1-optimize-cast (cast &optional do-not-optimize)
1680   (declare (type cast cast))
1681   (let* ((value (cast-value cast))
1682          (value-type (lvar-derived-type value))
1683          (atype (cast-asserted-type cast))
1684          (int (values-type-intersection value-type atype)))
1685     (derive-node-type cast int)
1686     (when (eq int *empty-type*)
1687       (unless (eq value-type *empty-type*)
1688
1689         ;; FIXME: Do it in one step.
1690         (filter-lvar
1691          value
1692          `(multiple-value-call #'list 'dummy))
1693         (filter-lvar
1694          (cast-value cast)
1695          ;; FIXME: Derived type.
1696          `(%compile-time-type-error 'dummy
1697                                     ',(type-specifier atype)
1698                                     ',(type-specifier value-type)))
1699         ;; KLUDGE: FILTER-LVAR does not work for non-returning
1700         ;; functions, so we declare the return type of
1701         ;; %COMPILE-TIME-TYPE-ERROR to be * and derive the real type
1702         ;; here.
1703         (setq value (cast-value cast))
1704         (derive-node-type (lvar-uses value) *empty-type*)
1705         (maybe-terminate-block (lvar-uses value) nil)
1706         ;; FIXME: Is it necessary?
1707         (aver (null (block-pred (node-block cast))))
1708         (setf (block-delete-p (node-block cast)) t)
1709         (return-from ir1-optimize-cast)))
1710     (when (eq (node-derived-type cast) *empty-type*)
1711       (maybe-terminate-block cast nil))
1712
1713     (when (not do-not-optimize)
1714       (let ((lvar (node-lvar cast)))
1715         (when (values-subtypep value-type (cast-asserted-type cast))
1716           (delete-filter cast lvar value)
1717           (when lvar
1718             (reoptimize-lvar lvar)
1719             (when (lvar-single-value-p lvar)
1720               (note-single-valuified-lvar lvar)))
1721           (return-from ir1-optimize-cast t))
1722
1723         (when (and (listp (lvar-uses value))
1724                    lvar)
1725           ;; Pathwise removing of CAST
1726           (let ((ctran (node-next cast))
1727                 (dest (lvar-dest lvar))
1728                 next-block)
1729             (collect ((merges))
1730               (do-uses (use value)
1731                 (when (and (values-subtypep (node-derived-type use) atype)
1732                            (immediately-used-p value use))
1733                   (unless next-block
1734                     (when ctran (ensure-block-start ctran))
1735                     (setq next-block (first (block-succ (node-block cast)))))
1736                   (%delete-lvar-use use)
1737                   (add-lvar-use use lvar)
1738                   (unlink-blocks (node-block use) (node-block cast))
1739                   (link-blocks (node-block use) next-block)
1740                   (when (and (return-p dest)
1741                              (basic-combination-p use)
1742                              (eq (basic-combination-kind use) :local))
1743                     (merges use))))
1744               (dolist (use (merges))
1745                 (merge-tail-sets use)))))))
1746
1747     (when (and (cast-%type-check cast)
1748                (values-subtypep value-type
1749                                 (cast-type-to-check cast)))
1750       (setf (cast-%type-check cast) nil)))
1751
1752   (unless do-not-optimize
1753     (setf (node-reoptimize cast) nil)))