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