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