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