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