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