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