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