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