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