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