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