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