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