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