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