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