7a57b266c2e959c28a4f97c5163cd66b758ad11b
[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                  (let ((block (node-block call)))
1186                    (when (eq (block-last block) call)
1187                      (setf (block-last block) (continuation-next prev))))
1188                  ;; FIXME: type checking?
1189                  (reoptimize-continuation cont)
1190                  (reoptimize-continuation prev)
1191                  (flush-combination call))))
1192             (t (let ((dummies (make-gensym-list (length args))))
1193                  (transform-call
1194                   call
1195                   `(lambda ,dummies
1196                      (declare (ignore ,@dummies))
1197                      (values ,@(mapcar (lambda (x) `',x) values)))
1198                   fun-name))))))
1199   (values))
1200 \f
1201 ;;;; local call optimization
1202
1203 ;;; Propagate TYPE to LEAF and its REFS, marking things changed. If
1204 ;;; the leaf type is a function type, then just leave it alone, since
1205 ;;; TYPE is never going to be more specific than that (and
1206 ;;; TYPE-INTERSECTION would choke.)
1207 (defun propagate-to-refs (leaf type)
1208   (declare (type leaf leaf) (type ctype type))
1209   (let ((var-type (leaf-type leaf)))
1210     (unless (fun-type-p var-type)
1211       (let ((int (type-approx-intersection2 var-type type)))
1212         (when (type/= int var-type)
1213           (setf (leaf-type leaf) int)
1214           (dolist (ref (leaf-refs leaf))
1215             (derive-node-type ref (make-single-value-type int))
1216             (let* ((cont (node-cont ref))
1217                    (dest (continuation-dest cont)))
1218               ;; KLUDGE: LET var substitution
1219               (when (combination-p dest)
1220                 (reoptimize-continuation cont))))))
1221       (values))))
1222
1223 ;;; Iteration variable: exactly one SETQ of the form:
1224 ;;;
1225 ;;; (let ((var initial))
1226 ;;;   ...
1227 ;;;   (setq var (+ var step))
1228 ;;;   ...)
1229 (defun maybe-infer-iteration-var-type (var initial-type)
1230   (binding* ((sets (lambda-var-sets var) :exit-if-null)
1231              (set (first sets))
1232              (() (null (rest sets)) :exit-if-null)
1233              (set-use (principal-continuation-use (set-value set)))
1234              (() (and (combination-p set-use)
1235                       (fun-info-p (combination-kind set-use))
1236                       (eq (combination-fun-source-name set-use) '+))
1237                :exit-if-null)
1238              (+-args (basic-combination-args set-use))
1239              (() (and (proper-list-of-length-p +-args 2 2)
1240                       (let ((first (principal-continuation-use
1241                                     (first +-args))))
1242                         (and (ref-p first)
1243                              (eq (ref-leaf first) var))))
1244                :exit-if-null)
1245              (step-type (continuation-type (second +-args)))
1246              (set-type (continuation-type (set-value set))))
1247     (when (and (numeric-type-p initial-type)
1248                (numeric-type-p step-type)
1249                (numeric-type-equal initial-type step-type))
1250       (multiple-value-bind (low high)
1251           (cond ((csubtypep step-type (specifier-type '(real 0 *)))
1252                  (values (numeric-type-low initial-type)
1253                          (when (and (numeric-type-p set-type)
1254                                     (numeric-type-equal set-type initial-type))
1255                            (numeric-type-high set-type))))
1256                 ((csubtypep step-type (specifier-type '(real * 0)))
1257                  (values (when (and (numeric-type-p set-type)
1258                                     (numeric-type-equal set-type initial-type))
1259                            (numeric-type-low set-type))
1260                          (numeric-type-high initial-type)))
1261                 (t
1262                  (values nil nil)))
1263         (modified-numeric-type initial-type
1264                                :low low
1265                                :high high
1266                                :enumerable nil)))))
1267 (deftransform + ((x y) * * :result result)
1268   "check for iteration variable reoptimization"
1269   (let ((dest (principal-continuation-end result))
1270         (use (principal-continuation-use x)))
1271     (when (and (ref-p use)
1272                (set-p dest)
1273                (eq (ref-leaf use)
1274                    (set-var dest)))
1275       (reoptimize-continuation (set-value dest))))
1276   (give-up-ir1-transform))
1277
1278 ;;; Figure out the type of a LET variable that has sets. We compute
1279 ;;; the union of the INITIAL-TYPE and the types of all the set
1280 ;;; values and to a PROPAGATE-TO-REFS with this type.
1281 (defun propagate-from-sets (var initial-type)
1282   (collect ((res initial-type type-union))
1283     (dolist (set (basic-var-sets var))
1284       (let ((type (continuation-type (set-value set))))
1285         (res type)
1286         (when (node-reoptimize set)
1287           (derive-node-type set (make-single-value-type type))
1288           (setf (node-reoptimize set) nil))))
1289     (let ((res (res)))
1290       (awhen (maybe-infer-iteration-var-type var initial-type)
1291         (setq res it))
1292       (propagate-to-refs var res)))
1293   (values))
1294
1295 ;;; If a LET variable, find the initial value's type and do
1296 ;;; PROPAGATE-FROM-SETS. We also derive the VALUE's type as the node's
1297 ;;; type.
1298 (defun ir1-optimize-set (node)
1299   (declare (type cset node))
1300   (let ((var (set-var node)))
1301     (when (and (lambda-var-p var) (leaf-refs var))
1302       (let ((home (lambda-var-home var)))
1303         (when (eq (functional-kind home) :let)
1304           (let* ((initial-value (let-var-initial-value var))
1305                  (initial-type (continuation-type initial-value)))
1306             (setf (continuation-reoptimize initial-value) nil)
1307             (propagate-from-sets var initial-type))))))
1308
1309   (derive-node-type node (make-single-value-type
1310                           (continuation-type (set-value node))))
1311   (values))
1312
1313 ;;; Return true if the value of REF will always be the same (and is
1314 ;;; thus legal to substitute.)
1315 (defun constant-reference-p (ref)
1316   (declare (type ref ref))
1317   (let ((leaf (ref-leaf ref)))
1318     (typecase leaf
1319       ((or constant functional) t)
1320       (lambda-var
1321        (null (lambda-var-sets leaf)))
1322       (defined-fun
1323        (not (eq (defined-fun-inlinep leaf) :notinline)))
1324       (global-var
1325        (case (global-var-kind leaf)
1326          (:global-function
1327           (let ((name (leaf-source-name leaf)))
1328             (or #-sb-xc-host
1329                 (eq (symbol-package (fun-name-block-name name))
1330                     *cl-package*)
1331                 (info :function :info name)))))))))
1332
1333 ;;; If we have a non-set LET var with a single use, then (if possible)
1334 ;;; replace the variable reference's CONT with the arg continuation.
1335 ;;; This is inhibited when:
1336 ;;; -- CONT has other uses, or
1337 ;;; -- the reference is in a different environment from the variable, or
1338 ;;; -- CONT carries unknown number of values, or
1339 ;;; -- DEST is return or exit, or
1340 ;;; -- DEST is sensitive to the number of values and ARG return non-one value.
1341 ;;;
1342 ;;; We change the REF to be a reference to NIL with unused value, and
1343 ;;; let it be flushed as dead code. A side effect of this substitution
1344 ;;; is to delete the variable.
1345 (defun substitute-single-use-continuation (arg var)
1346   (declare (type continuation arg) (type lambda-var var))
1347   (let* ((ref (first (leaf-refs var)))
1348          (cont (node-cont ref))
1349          (dest (continuation-dest cont)))
1350     (when (and (eq (continuation-use cont) ref)
1351                dest
1352                (typecase dest
1353                  (cast
1354                   (and (type-single-value-p (continuation-derived-type arg))
1355                        (multiple-value-bind (pdest pprev)
1356                            (principal-continuation-end cont)
1357                          (declare (ignore pdest))
1358                          (continuation-single-value-p pprev))))
1359                  (mv-combination
1360                   (or (eq (basic-combination-fun dest) cont)
1361                       (and (eq (basic-combination-kind dest) :local)
1362                            (type-single-value-p (continuation-derived-type arg)))))
1363                  ((or creturn exit)
1364                   nil)
1365                  (t
1366                   ;; (AVER (CONTINUATION-SINGLE-VALUE-P CONT))
1367                   t))
1368                (eq (node-home-lambda ref)
1369                    (lambda-home (lambda-var-home var))))
1370       (aver (member (continuation-kind arg)
1371                     '(:block-start :deleted-block-start :inside-block)))
1372       (setf (node-derived-type ref) *wild-type*)
1373       (change-ref-leaf ref (find-constant nil))
1374       (substitute-continuation arg cont)
1375       (reoptimize-continuation arg)
1376       t)))
1377
1378 ;;; Delete a LET, removing the call and bind nodes, and warning about
1379 ;;; any unreferenced variables. Note that FLUSH-DEAD-CODE will come
1380 ;;; along right away and delete the REF and then the lambda, since we
1381 ;;; flush the FUN continuation.
1382 (defun delete-let (clambda)
1383   (declare (type clambda clambda))
1384   (aver (functional-letlike-p clambda))
1385   (note-unreferenced-vars clambda)
1386   (let ((call (let-combination clambda)))
1387     (flush-dest (basic-combination-fun call))
1388     (unlink-node call)
1389     (unlink-node (lambda-bind clambda))
1390     (setf (lambda-bind clambda) nil))
1391   (values))
1392
1393 ;;; This function is called when one of the arguments to a LET
1394 ;;; changes. We look at each changed argument. If the corresponding
1395 ;;; variable is set, then we call PROPAGATE-FROM-SETS. Otherwise, we
1396 ;;; consider substituting for the variable, and also propagate
1397 ;;; derived-type information for the arg to all the VAR's refs.
1398 ;;;
1399 ;;; Substitution is inhibited when the arg leaf's derived type isn't a
1400 ;;; subtype of the argument's leaf type. This prevents type checking
1401 ;;; from being defeated, and also ensures that the best representation
1402 ;;; for the variable can be used.
1403 ;;;
1404 ;;; Substitution of individual references is inhibited if the
1405 ;;; reference is in a different component from the home. This can only
1406 ;;; happen with closures over top level lambda vars. In such cases,
1407 ;;; the references may have already been compiled, and thus can't be
1408 ;;; retroactively modified.
1409 ;;;
1410 ;;; If all of the variables are deleted (have no references) when we
1411 ;;; are done, then we delete the LET.
1412 ;;;
1413 ;;; Note that we are responsible for clearing the
1414 ;;; CONTINUATION-REOPTIMIZE flags.
1415 (defun propagate-let-args (call fun)
1416   (declare (type combination call) (type clambda fun))
1417   (loop for arg in (combination-args call)
1418         and var in (lambda-vars fun) do
1419     (when (and arg (continuation-reoptimize arg))
1420       (setf (continuation-reoptimize arg) nil)
1421       (cond
1422        ((lambda-var-sets var)
1423         (propagate-from-sets var (continuation-type arg)))
1424        ((let ((use (continuation-use arg)))
1425           (when (ref-p use)
1426             (let ((leaf (ref-leaf use)))
1427               (when (and (constant-reference-p use)
1428                          (csubtypep (leaf-type leaf)
1429                                     ;; (NODE-DERIVED-TYPE USE) would
1430                                     ;; be better -- APD, 2003-05-15
1431                                     (leaf-type var)))
1432                 (propagate-to-refs var (continuation-type arg))
1433                 (let ((use-component (node-component use)))
1434                   (substitute-leaf-if
1435                    (lambda (ref)
1436                      (cond ((eq (node-component ref) use-component)
1437                             t)
1438                            (t
1439                             (aver (lambda-toplevelish-p (lambda-home fun)))
1440                             nil)))
1441                    leaf var))
1442                 t)))))
1443        ((and (null (rest (leaf-refs var)))
1444              (substitute-single-use-continuation arg var)))
1445        (t
1446         (propagate-to-refs var (continuation-type arg))))))
1447
1448   (when (every #'not (combination-args call))
1449     (delete-let fun))
1450
1451   (values))
1452
1453 ;;; This function is called when one of the args to a non-LET local
1454 ;;; call changes. For each changed argument corresponding to an unset
1455 ;;; variable, we compute the union of the types across all calls and
1456 ;;; propagate this type information to the var's refs.
1457 ;;;
1458 ;;; If the function has an XEP, then we don't do anything, since we
1459 ;;; won't discover anything.
1460 ;;;
1461 ;;; We can clear the CONTINUATION-REOPTIMIZE flags for arguments in
1462 ;;; all calls corresponding to changed arguments in CALL, since the
1463 ;;; only use in IR1 optimization of the REOPTIMIZE flag for local call
1464 ;;; args is right here.
1465 (defun propagate-local-call-args (call fun)
1466   (declare (type combination call) (type clambda fun))
1467
1468   (unless (or (functional-entry-fun fun)
1469               (lambda-optional-dispatch fun))
1470     (let* ((vars (lambda-vars fun))
1471            (union (mapcar (lambda (arg var)
1472                             (when (and arg
1473                                        (continuation-reoptimize arg)
1474                                        (null (basic-var-sets var)))
1475                               (continuation-type arg)))
1476                           (basic-combination-args call)
1477                           vars))
1478            (this-ref (continuation-use (basic-combination-fun call))))
1479
1480       (dolist (arg (basic-combination-args call))
1481         (when arg
1482           (setf (continuation-reoptimize arg) nil)))
1483
1484       (dolist (ref (leaf-refs fun))
1485         (let ((dest (continuation-dest (node-cont ref))))
1486           (unless (or (eq ref this-ref) (not dest))
1487             (setq union
1488                   (mapcar (lambda (this-arg old)
1489                             (when old
1490                               (setf (continuation-reoptimize this-arg) nil)
1491                               (type-union (continuation-type this-arg) old)))
1492                           (basic-combination-args dest)
1493                           union)))))
1494
1495       (mapc (lambda (var type)
1496               (when type
1497                 (propagate-to-refs var type)))
1498             vars union)))
1499
1500   (values))
1501 \f
1502 ;;;; multiple values optimization
1503
1504 ;;; Do stuff to notice a change to a MV combination node. There are
1505 ;;; two main branches here:
1506 ;;;  -- If the call is local, then it is already a MV let, or should
1507 ;;;     become one. Note that although all :LOCAL MV calls must eventually
1508 ;;;     be converted to :MV-LETs, there can be a window when the call
1509 ;;;     is local, but has not been LET converted yet. This is because
1510 ;;;     the entry-point lambdas may have stray references (in other
1511 ;;;     entry points) that have not been deleted yet.
1512 ;;;  -- The call is full. This case is somewhat similar to the non-MV
1513 ;;;     combination optimization: we propagate return type information and
1514 ;;;     notice non-returning calls. We also have an optimization
1515 ;;;     which tries to convert MV-CALLs into MV-binds.
1516 (defun ir1-optimize-mv-combination (node)
1517   (ecase (basic-combination-kind node)
1518     (:local
1519      (let ((fun-cont (basic-combination-fun node)))
1520        (when (continuation-reoptimize fun-cont)
1521          (setf (continuation-reoptimize fun-cont) nil)
1522          (maybe-let-convert (combination-lambda node))))
1523      (setf (continuation-reoptimize (first (basic-combination-args node))) nil)
1524      (when (eq (functional-kind (combination-lambda node)) :mv-let)
1525        (unless (convert-mv-bind-to-let node)
1526          (ir1-optimize-mv-bind node))))
1527     (:full
1528      (let* ((fun (basic-combination-fun node))
1529             (fun-changed (continuation-reoptimize fun))
1530             (args (basic-combination-args node)))
1531        (when fun-changed
1532          (setf (continuation-reoptimize fun) nil)
1533          (let ((type (continuation-type fun)))
1534            (when (fun-type-p type)
1535              (derive-node-type node (fun-type-returns type))))
1536          (maybe-terminate-block node nil)
1537          (let ((use (continuation-use fun)))
1538            (when (and (ref-p use) (functional-p (ref-leaf use)))
1539              (convert-call-if-possible use node)
1540              (when (eq (basic-combination-kind node) :local)
1541                (maybe-let-convert (ref-leaf use))))))
1542        (unless (or (eq (basic-combination-kind node) :local)
1543                    (eq (continuation-fun-name fun) '%throw))
1544          (ir1-optimize-mv-call node))
1545        (dolist (arg args)
1546          (setf (continuation-reoptimize arg) nil))))
1547     (:error))
1548   (values))
1549
1550 ;;; Propagate derived type info from the values continuation to the
1551 ;;; vars.
1552 (defun ir1-optimize-mv-bind (node)
1553   (declare (type mv-combination node))
1554   (let* ((arg (first (basic-combination-args node)))
1555          (vars (lambda-vars (combination-lambda node)))
1556          (n-vars (length vars))
1557          (types (values-type-in (continuation-derived-type arg)
1558                                 n-vars)))
1559     (loop for var in vars
1560           and type in types
1561           do (if (basic-var-sets var)
1562                  (propagate-from-sets var type)
1563                  (propagate-to-refs var type)))
1564     (setf (continuation-reoptimize arg) nil))
1565   (values))
1566
1567 ;;; If possible, convert a general MV call to an MV-BIND. We can do
1568 ;;; this if:
1569 ;;; -- The call has only one argument, and
1570 ;;; -- The function has a known fixed number of arguments, or
1571 ;;; -- The argument yields a known fixed number of values.
1572 ;;;
1573 ;;; What we do is change the function in the MV-CALL to be a lambda
1574 ;;; that "looks like an MV bind", which allows
1575 ;;; IR1-OPTIMIZE-MV-COMBINATION to notice that this call can be
1576 ;;; converted (the next time around.) This new lambda just calls the
1577 ;;; actual function with the MV-BIND variables as arguments. Note that
1578 ;;; this new MV bind is not let-converted immediately, as there are
1579 ;;; going to be stray references from the entry-point functions until
1580 ;;; they get deleted.
1581 ;;;
1582 ;;; In order to avoid loss of argument count checking, we only do the
1583 ;;; transformation according to a known number of expected argument if
1584 ;;; safety is unimportant. We can always convert if we know the number
1585 ;;; of actual values, since the normal call that we build will still
1586 ;;; do any appropriate argument count checking.
1587 ;;;
1588 ;;; We only attempt the transformation if the called function is a
1589 ;;; constant reference. This allows us to just splice the leaf into
1590 ;;; the new function, instead of trying to somehow bind the function
1591 ;;; expression. The leaf must be constant because we are evaluating it
1592 ;;; again in a different place. This also has the effect of squelching
1593 ;;; multiple warnings when there is an argument count error.
1594 (defun ir1-optimize-mv-call (node)
1595   (let ((fun (basic-combination-fun node))
1596         (*compiler-error-context* node)
1597         (ref (continuation-use (basic-combination-fun node)))
1598         (args (basic-combination-args node)))
1599
1600     (unless (and (ref-p ref) (constant-reference-p ref)
1601                  (singleton-p args))
1602       (return-from ir1-optimize-mv-call))
1603
1604     (multiple-value-bind (min max)
1605         (fun-type-nargs (continuation-type fun))
1606       (let ((total-nvals
1607              (multiple-value-bind (types nvals)
1608                  (values-types (continuation-derived-type (first args)))
1609                (declare (ignore types))
1610                (if (eq nvals :unknown) nil nvals))))
1611
1612         (when total-nvals
1613           (when (and min (< total-nvals min))
1614             (compiler-warn
1615              "MULTIPLE-VALUE-CALL with ~R values when the function expects ~
1616              at least ~R."
1617              total-nvals min)
1618             (setf (basic-combination-kind node) :error)
1619             (return-from ir1-optimize-mv-call))
1620           (when (and max (> total-nvals max))
1621             (compiler-warn
1622              "MULTIPLE-VALUE-CALL with ~R values when the function expects ~
1623              at most ~R."
1624              total-nvals max)
1625             (setf (basic-combination-kind node) :error)
1626             (return-from ir1-optimize-mv-call)))
1627
1628         (let ((count (cond (total-nvals)
1629                            ((and (policy node (zerop verify-arg-count))
1630                                  (eql min max))
1631                             min)
1632                            (t nil))))
1633           (when count
1634             (with-ir1-environment-from-node node
1635               (let* ((dums (make-gensym-list count))
1636                      (ignore (gensym))
1637                      (fun (ir1-convert-lambda
1638                            `(lambda (&optional ,@dums &rest ,ignore)
1639                               (declare (ignore ,ignore))
1640                               (funcall ,(ref-leaf ref) ,@dums)))))
1641                 (change-ref-leaf ref fun)
1642                 (aver (eq (basic-combination-kind node) :full))
1643                 (locall-analyze-component *current-component*)
1644                 (aver (eq (basic-combination-kind node) :local)))))))))
1645   (values))
1646
1647 ;;; If we see:
1648 ;;;    (multiple-value-bind
1649 ;;;     (x y)
1650 ;;;     (values xx yy)
1651 ;;;      ...)
1652 ;;; Convert to:
1653 ;;;    (let ((x xx)
1654 ;;;       (y yy))
1655 ;;;      ...)
1656 ;;;
1657 ;;; What we actually do is convert the VALUES combination into a
1658 ;;; normal LET combination calling the original :MV-LET lambda. If
1659 ;;; there are extra args to VALUES, discard the corresponding
1660 ;;; continuations. If there are insufficient args, insert references
1661 ;;; to NIL.
1662 (defun convert-mv-bind-to-let (call)
1663   (declare (type mv-combination call))
1664   (let* ((arg (first (basic-combination-args call)))
1665          (use (continuation-use arg)))
1666     (when (and (combination-p use)
1667                (eq (continuation-fun-name (combination-fun use))
1668                    'values))
1669       (let* ((fun (combination-lambda call))
1670              (vars (lambda-vars fun))
1671              (vals (combination-args use))
1672              (nvars (length vars))
1673              (nvals (length vals)))
1674         (cond ((> nvals nvars)
1675                (mapc #'flush-dest (subseq vals nvars))
1676                (setq vals (subseq vals 0 nvars)))
1677               ((< nvals nvars)
1678                (with-ir1-environment-from-node use
1679                  (let ((node-prev (node-prev use)))
1680                    (setf (node-prev use) nil)
1681                    (setf (continuation-next node-prev) nil)
1682                    (collect ((res vals))
1683                      (loop for cont = (make-continuation use)
1684                            and prev = node-prev then cont
1685                            repeat (- nvars nvals)
1686                            do (reference-constant prev cont nil)
1687                               (res cont))
1688                      (setq vals (res)))
1689                    (link-node-to-previous-continuation use
1690                                                        (car (last vals)))))))
1691         (setf (combination-args use) vals)
1692         (flush-dest (combination-fun use))
1693         (let ((fun-cont (basic-combination-fun call)))
1694           (setf (continuation-dest fun-cont) use)
1695           (setf (combination-fun use) fun-cont)
1696           (flush-continuation-externally-checkable-type fun-cont))
1697         (setf (combination-kind use) :local)
1698         (setf (functional-kind fun) :let)
1699         (flush-dest (first (basic-combination-args call)))
1700         (unlink-node call)
1701         (when vals
1702           (reoptimize-continuation (first vals)))
1703         (propagate-to-args use fun)
1704         (reoptimize-call use))
1705       t)))
1706
1707 ;;; If we see:
1708 ;;;    (values-list (list x y z))
1709 ;;;
1710 ;;; Convert to:
1711 ;;;    (values x y z)
1712 ;;;
1713 ;;; In implementation, this is somewhat similar to
1714 ;;; CONVERT-MV-BIND-TO-LET. We grab the args of LIST and make them
1715 ;;; args of the VALUES-LIST call, flushing the old argument
1716 ;;; continuation (allowing the LIST to be flushed.)
1717 ;;;
1718 ;;; FIXME: Thus we lose possible type assertions on (LIST ...).
1719 (defoptimizer (values-list optimizer) ((list) node)
1720   (let ((use (continuation-use list)))
1721     (when (and (combination-p use)
1722                (eq (continuation-fun-name (combination-fun use))
1723                    'list))
1724
1725       ;; FIXME: VALUES might not satisfy an assertion on NODE-CONT.
1726       (change-ref-leaf (continuation-use (combination-fun node))
1727                        (find-free-fun 'values "in a strange place"))
1728       (setf (combination-kind node) :full)
1729       (let ((args (combination-args use)))
1730         (dolist (arg args)
1731           (setf (continuation-dest arg) node)
1732           (flush-continuation-externally-checkable-type arg))
1733         (setf (combination-args use) nil)
1734         (flush-dest list)
1735         (setf (combination-args node) args))
1736       t)))
1737
1738 ;;; If VALUES appears in a non-MV context, then effectively convert it
1739 ;;; to a PROG1. This allows the computation of the additional values
1740 ;;; to become dead code.
1741 (deftransform values ((&rest vals) * * :node node)
1742   (unless (continuation-single-value-p (node-cont node))
1743     (give-up-ir1-transform))
1744   (setf (node-derived-type node) *wild-type*)
1745   (principal-continuation-single-valuify (node-cont node))
1746   (if vals
1747       (let ((dummies (make-gensym-list (length (cdr vals)))))
1748         `(lambda (val ,@dummies)
1749            (declare (ignore ,@dummies))
1750            val))
1751       nil))
1752
1753 ;;; TODO:
1754 ;;; - CAST chains;
1755 (defun ir1-optimize-cast (cast &optional do-not-optimize)
1756   (declare (type cast cast))
1757   (let* ((value (cast-value cast))
1758          (value-type (continuation-derived-type value))
1759          (cont (node-cont cast))
1760          (dest (continuation-dest cont))
1761          (atype (cast-asserted-type cast))
1762          (int (values-type-intersection value-type atype)))
1763     (derive-node-type cast int)
1764     (when (eq int *empty-type*)
1765       (unless (eq value-type *empty-type*)
1766
1767         ;; FIXME: Do it in one step.
1768         (filter-continuation
1769          value
1770          `(multiple-value-call #'list 'dummy))
1771         (filter-continuation
1772          value
1773          ;; FIXME: Derived type.
1774          `(%compile-time-type-error 'dummy
1775                                     ',(type-specifier atype)
1776                                     ',(type-specifier value-type)))
1777         ;; KLUDGE: FILTER-CONTINUATION does not work for
1778         ;; non-returning functions, so we declare the return type of
1779         ;; %COMPILE-TIME-TYPE-ERROR to be * and derive the real type
1780         ;; here.
1781         (derive-node-type (continuation-use value) *empty-type*)
1782         (maybe-terminate-block (continuation-use value) nil)
1783         ;; FIXME: Is it necessary?
1784         (aver (null (block-pred (node-block cast))))
1785         (setf (block-delete-p (node-block cast)) t)
1786         (return-from ir1-optimize-cast)))
1787     (when (eq (node-derived-type cast) *empty-type*)
1788       (maybe-terminate-block cast nil))
1789
1790     (when (and (not do-not-optimize)
1791                (values-subtypep value-type
1792                                 (cast-asserted-type cast)))
1793       (delete-filter cast cont value)
1794       (reoptimize-continuation cont)
1795       (when (continuation-single-value-p cont)
1796         (note-single-valuified-continuation cont))
1797       (when (not dest)
1798         (reoptimize-continuation-uses cont))
1799       (return-from ir1-optimize-cast t))
1800
1801     (when (and (not do-not-optimize)
1802                (not (continuation-use value))
1803                dest)
1804       (collect ((merges))
1805         (do-uses (use value)
1806           (when (and (values-subtypep (node-derived-type use) atype)
1807                      (immediately-used-p value use))
1808             (ensure-block-start cont)
1809             (delete-continuation-use use)
1810             (add-continuation-use use cont)
1811             (unlink-blocks (node-block use) (node-block cast))
1812             (link-blocks (node-block use)
1813                          (first (block-succ (node-block cast))))
1814             (when (and (return-p dest)
1815                        (basic-combination-p use)
1816                        (eq (basic-combination-kind use) :local))
1817               (merges use))))
1818         (dolist (use (merges))
1819           (merge-tail-sets use))))
1820
1821     (when (and (cast-%type-check cast)
1822                (values-subtypep value-type
1823                                 (cast-type-to-check cast)))
1824       (setf (cast-%type-check cast) nil)))
1825
1826   (unless do-not-optimize
1827     (setf (node-reoptimize cast) nil)))