Initial revision
[sbcl.git] / src / compiler / ltn.lisp
1 ;;;; This file contains the LTN pass in the compiler. LTN allocates
2 ;;;; expression evaluation TNs, makes nearly all the implementation
3 ;;;; policy decisions, and also does a few other miscellaneous things.
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15
16 (file-comment
17   "$Header$")
18 \f
19 ;;;; utilities
20
21 ;;; Return the policies keyword indicated by the node policy.
22 (defun translation-policy (node)
23   (declare (type node node))
24   (let* ((cookie (lexenv-cookie (node-lexenv node)))
25          (safety (cookie-safety cookie))
26          (space (max (cookie-space cookie)
27                      (cookie-cspeed cookie)))
28          (speed (cookie-speed cookie)))
29     (if (zerop safety)
30         (if (>= speed space) :fast :small)
31         (if (>= speed space) :fast-safe :safe))))
32
33 ;;; Return true if Policy is a safe policy.
34 #!-sb-fluid (declaim (inline policy-safe-p))
35 (defun policy-safe-p (policy)
36   (declare (type policies policy))
37   (or (eq policy :safe) (eq policy :fast-safe)))
38
39 ;;; Called when an unsafe policy indicates that no type check should be done
40 ;;; on CONT. We delete the type check unless it is :ERROR (indicating a
41 ;;; compile-time type error.)
42 #!-sb-fluid (declaim (inline flush-type-check))
43 (defun flush-type-check (cont)
44   (declare (type continuation cont))
45   (when (member (continuation-type-check cont) '(t :no-check))
46     (setf (continuation-%type-check cont) :deleted))
47   (values))
48
49 ;;; An annotated continuation's primitive-type.
50 #!-sb-fluid (declaim (inline continuation-ptype))
51 (defun continuation-ptype (cont)
52   (declare (type continuation cont))
53   (ir2-continuation-primitive-type (continuation-info cont)))
54
55 ;;; Return true if a constant Leaf is of a type which we can legally
56 ;;; directly reference in code. Named constants with arbitrary pointer values
57 ;;; cannot, since we must preserve EQLness.
58 (defun legal-immediate-constant-p (leaf)
59   (declare (type constant leaf))
60   (or (null (leaf-name leaf))
61       (typecase (constant-value leaf)
62         ((or number character) t)
63         (symbol (symbol-package (constant-value leaf)))
64         (t nil))))
65
66 ;;; If Cont is used only by a Ref to a leaf that can be delayed, then return
67 ;;; the leaf, otherwise return NIL.
68 (defun continuation-delayed-leaf (cont)
69   (declare (type continuation cont))
70   (let ((use (continuation-use cont)))
71     (and (ref-p use)
72          (let ((leaf (ref-leaf use)))
73            (etypecase leaf
74              (lambda-var (if (null (lambda-var-sets leaf)) leaf nil))
75              (constant (if (legal-immediate-constant-p leaf) leaf nil))
76              ((or functional global-var) nil))))))
77
78 ;;; Annotate a normal single-value continuation. If its only use is a ref
79 ;;; that we are allowed to delay the evaluation of, then we mark the
80 ;;; continuation for delayed evaluation, otherwise we assign a TN to hold the
81 ;;; continuation's value. If the continuation has a type check, we make the TN
82 ;;; according to the proven type to ensure that the possibly erroneous value
83 ;;; can be represented.
84 (defun annotate-1-value-continuation (cont)
85   (declare (type continuation cont))
86   (let ((info (continuation-info cont)))
87     (assert (eq (ir2-continuation-kind info) :fixed))
88     (cond
89      ((continuation-delayed-leaf cont)
90       (setf (ir2-continuation-kind info) :delayed))
91      ((member (continuation-type-check cont) '(:deleted nil))
92       (setf (ir2-continuation-locs info)
93             (list (make-normal-tn (ir2-continuation-primitive-type info)))))
94      (t
95       (setf (ir2-continuation-locs info)
96             (list (make-normal-tn
97                    (primitive-type
98                     (single-value-type (continuation-proven-type cont)))))))))
99   (values))
100
101 ;;; Make an IR2-Continuation corresponding to the continuation type and then
102 ;;; do Annotate-1-Value-Continuation. If Policy isn't a safe policy, then we
103 ;;; clear the type-check flag.
104 (defun annotate-ordinary-continuation (cont policy)
105   (declare (type continuation cont)
106            (type policies policy))
107   (let ((info (make-ir2-continuation
108                (primitive-type (continuation-type cont)))))
109     (setf (continuation-info cont) info)
110     (unless (policy-safe-p policy) (flush-type-check cont))
111     (annotate-1-value-continuation cont))
112   (values))
113
114 ;;; Annotate the function continuation for a full call. If the only
115 ;;; reference is to a global function and Delay is true, then we delay
116 ;;; the reference, otherwise we annotate for a single value.
117 ;;;
118 ;;; Unlike for an argument, we only clear the type check flag when the policy
119 ;;; is unsafe, since the check for a valid function object must be done before
120 ;;; the call.
121 (defun annotate-function-continuation (cont policy &optional (delay t))
122   (declare (type continuation cont) (type policies policy))
123   (unless (policy-safe-p policy) (flush-type-check cont))
124   (let* ((ptype (primitive-type (continuation-type cont)))
125          (tn-ptype (if (member (continuation-type-check cont) '(:deleted nil))
126                        ptype
127                        (primitive-type
128                         (single-value-type
129                          (continuation-proven-type cont)))))
130          (info (make-ir2-continuation ptype)))
131     (setf (continuation-info cont) info)
132     (let ((name (continuation-function-name cont t)))
133       (if (and delay name)
134           (setf (ir2-continuation-kind info) :delayed)
135           (setf (ir2-continuation-locs info)
136                 (list (make-normal-tn tn-ptype))))))
137   (values))
138
139 ;;; If TAIL-P is true, then we check to see whether the call can really
140 ;;; be a tail call by seeing if this function's return convention is :UNKNOWN.
141 ;;; If so, we move the call block succssor link from the return block to
142 ;;; the component tail (after ensuring that they are in separate blocks.)
143 ;;; This allows the return to be deleted when there are no non-tail uses.
144 (defun flush-full-call-tail-transfer (call)
145   (declare (type basic-combination call))
146   (let ((tails (and (node-tail-p call)
147                     (lambda-tail-set (node-home-lambda call)))))
148     (when tails
149       (cond ((eq (return-info-kind (tail-set-info tails)) :unknown)
150              (node-ends-block call)
151              (let ((block (node-block call)))
152                (unlink-blocks block (first (block-succ block)))
153                (link-blocks block (component-tail (block-component block)))))
154             (t
155              (setf (node-tail-p call) nil)))))
156   (values))
157
158 ;;; We set the kind to :FULL or :FUNNY, depending on whether there is an
159 ;;; IR2-CONVERT method. If a funny function, then we inhibit tail recursion
160 ;;; and type check normally, since the IR2 convert method is going to want to
161 ;;; deliver values normally. We still annotate the function continuation,
162 ;;; since IR2tran might decide to call after all.
163 ;;;
164 ;;; If not funny, we always flush arg type checks, but do it after
165 ;;; annotation when the policy is safe, since we don't want to choose the TNs
166 ;;; according to a type assertions that may not hold.
167 ;;;
168 ;;; Note that args may already be annotated because template selection can
169 ;;; bail out to here.
170 (defun ltn-default-call (call policy)
171   (declare (type combination call) (type policies policy))
172   (let ((kind (basic-combination-kind call)))
173     (annotate-function-continuation (basic-combination-fun call) policy)
174
175     (cond
176      ((and (function-info-p kind)
177            (function-info-ir2-convert kind))
178       (setf (basic-combination-info call) :funny)
179       (setf (node-tail-p call) nil)
180       (dolist (arg (basic-combination-args call))
181         (unless (continuation-info arg)
182           (setf (continuation-info arg)
183                 (make-ir2-continuation
184                  (primitive-type
185                   (continuation-type arg)))))
186         (annotate-1-value-continuation arg)))
187      (t
188       (let ((safe-p (policy-safe-p policy)))
189         (dolist (arg (basic-combination-args call))
190           (unless safe-p (flush-type-check arg))
191           (unless (continuation-info arg)
192             (setf (continuation-info arg)
193                   (make-ir2-continuation
194                    (primitive-type
195                     (continuation-type arg)))))
196           (annotate-1-value-continuation arg)
197           (when safe-p (flush-type-check arg))))
198       (when (eq kind :error)
199         (setf (basic-combination-kind call) :full))
200       (setf (basic-combination-info call) :full)
201       (flush-full-call-tail-transfer call))))
202
203   (values))
204
205 ;;; Annotate a continuation for unknown multiple values:
206 ;;; -- Delete any type check, regardless of policy, since we IR2 conversion
207 ;;;    isn't prepared to check unknown-values continuations. If we delete a
208 ;;;    type check when the policy is safe, then we emit a warning.
209 ;;; -- Add the continuation to the IR2-Block-Popped if it is used across a
210 ;;;    block boundary.
211 ;;; -- Assign a :Unknown IR2-Continuation.
212 ;;;
213 ;;; Note: it is critical that this be called only during LTN analysis of Cont's
214 ;;; DEST, and called in the order that the continuations are received.
215 ;;; Otherwise the IR2-Block-Popped and IR2-Component-Values-XXX will get all
216 ;;; messed up.
217 (defun annotate-unknown-values-continuation (cont policy)
218   (declare (type continuation cont) (type policies policy))
219   (when (eq (continuation-type-check cont) t)
220     (let* ((dest (continuation-dest cont))
221            (*compiler-error-context* dest))
222       (when (and (policy-safe-p policy)
223                  (policy dest (>= safety brevity)))
224         (compiler-note "unable to check type assertion in unknown-values ~
225                         context:~% ~S"
226                        (continuation-asserted-type cont))))
227     (setf (continuation-%type-check cont) :deleted))
228
229   (let* ((block (node-block (continuation-dest cont)))
230          (use (continuation-use cont))
231          (2block (block-info block)))
232     (unless (and use (eq (node-block use) block))
233       (setf (ir2-block-popped 2block)
234             (nconc (ir2-block-popped 2block) (list cont)))))
235
236   (let ((2cont (make-ir2-continuation nil)))
237     (setf (ir2-continuation-kind 2cont) :unknown)
238     (setf (ir2-continuation-locs 2cont) (make-unknown-values-locations))
239     (setf (continuation-info cont) 2cont))
240
241   (values))
242
243 ;;; Annotate Cont for a fixed, but arbitrary number of values, of the
244 ;;; specified primitive Types. If the continuation has a type check, we
245 ;;; annotate for the number of values indicated by Types, but only use proven
246 ;;; type information.
247 (defun annotate-fixed-values-continuation (cont policy types)
248   (declare (type continuation cont) (type policies policy) (list types))
249   (unless (policy-safe-p policy) (flush-type-check cont))
250
251   (let ((res (make-ir2-continuation nil)))
252     (if (member (continuation-type-check cont) '(:deleted nil))
253         (setf (ir2-continuation-locs res) (mapcar #'make-normal-tn types))
254         (let* ((proven (mapcar #'(lambda (x)
255                                    (make-normal-tn (primitive-type x)))
256                                (values-types
257                                 (continuation-proven-type cont))))
258                (num-proven (length proven))
259                (num-types (length types)))
260           (setf (ir2-continuation-locs res)
261                 (cond
262                  ((< num-proven num-types)
263                   (append proven
264                           (make-n-tns (- num-types num-proven)
265                                       *backend-t-primitive-type*)))
266                  ((> num-proven num-types)
267                   (subseq proven 0 num-types))
268                  (t
269                   proven)))))
270     (setf (continuation-info cont) res))
271
272   (values))
273 \f
274 ;;;; node-specific analysis functions
275
276 ;;; Annotate the result continuation for a function. We use the Return-Info
277 ;;; computed by GTN to determine how to represent the return values within the
278 ;;; function:
279 ;;; -- If the tail-set has a fixed values count, then use that many values.
280 ;;; -- If the actual uses of the result continuation in this function have a
281 ;;;    fixed number of values (after intersection with the assertion), then use
282 ;;;    that number. We throw out TAIL-P :FULL and :LOCAL calls, since we know
283 ;;;    they will truly end up as TR calls. We can use the
284 ;;;    BASIC-COMBINATION-INFO even though it is assigned by this phase, since
285 ;;;    the initial value NIL doesn't look like a TR call.
286 ;;;
287 ;;;    If there are *no* non-tail-call uses, then it falls out that we annotate
288 ;;;    for one value (type is NIL), but the return will end up being deleted.
289 ;;;
290 ;;;    In non-perverse code, the DFO walk will reach all uses of the result
291 ;;;    continuation before it reaches the RETURN. In perverse code, we may
292 ;;;    annotate for unknown values when we didn't have to.
293 ;;; -- Otherwise, we must annotate the continuation for unknown values.
294 (defun ltn-analyze-return (node policy)
295   (declare (type creturn node) (type policies policy))
296   (let* ((cont (return-result node))
297          (fun (return-lambda node))
298          (returns (tail-set-info (lambda-tail-set fun)))
299          (types (return-info-types returns)))
300     (if (eq (return-info-count returns) :unknown)
301         (collect ((res *empty-type* values-type-union))
302           (do-uses (use (return-result node))
303             (unless (and (node-tail-p use)
304                          (basic-combination-p use)
305                          (member (basic-combination-info use) '(:local :full)))
306               (res (node-derived-type use))))
307
308           (let ((int (values-type-intersection
309                       (res)
310                       (continuation-asserted-type cont))))
311             (multiple-value-bind (types kind)
312                 (values-types (if (eq int *empty-type*) (res) int))
313               (if (eq kind :unknown)
314                   (annotate-unknown-values-continuation cont policy)
315                   (annotate-fixed-values-continuation
316                    cont policy
317                    (mapcar #'primitive-type types))))))
318         (annotate-fixed-values-continuation cont policy types)))
319
320   (values))
321
322 ;;; Annotate the single argument continuation as a fixed-values
323 ;;; continuation. We look at the called lambda to determine number and type of
324 ;;; return values desired. It is assumed that only a function that
325 ;;; Looks-Like-An-MV-Bind will be converted to a local call.
326 (defun ltn-analyze-mv-bind (call policy)
327   (declare (type mv-combination call)
328            (type policies policy))
329   (setf (basic-combination-kind call) :local)
330   (setf (node-tail-p call) nil)
331   (annotate-fixed-values-continuation
332    (first (basic-combination-args call)) policy
333    (mapcar #'(lambda (var)
334                (primitive-type (basic-var-type var)))
335            (lambda-vars
336             (ref-leaf
337              (continuation-use
338               (basic-combination-fun call))))))
339   (values))
340
341 ;;; We force all the argument continuations to use the unknown values
342 ;;; convention. The continuations are annotated in reverse order, since the
343 ;;; last argument is on top, thus must be popped first. We disallow delayed
344 ;;; evaluation of the function continuation to simplify IR2 conversion of MV
345 ;;; call.
346 ;;;
347 ;;; We could be cleverer when we know the number of values returned by the
348 ;;; continuations, but optimizations of MV-Call are probably unworthwhile.
349 ;;;
350 ;;; We are also responsible for handling THROW, which is represented in IR1
351 ;;; as an mv-call to the %THROW funny function. We annotate the tag
352 ;;; continuation for a single value and the values continuation for unknown
353 ;;; values.
354 (defun ltn-analyze-mv-call (call policy)
355   (declare (type mv-combination call))
356   (let ((fun (basic-combination-fun call))
357         (args (basic-combination-args call)))
358     (cond ((eq (continuation-function-name fun) '%throw)
359            (setf (basic-combination-info call) :funny)
360            (annotate-ordinary-continuation (first args) policy)
361            (annotate-unknown-values-continuation (second args) policy)
362            (setf (node-tail-p call) nil))
363           (t
364            (setf (basic-combination-info call) :full)
365            (annotate-function-continuation (basic-combination-fun call)
366                                            policy nil)
367            (dolist (arg (reverse args))
368              (annotate-unknown-values-continuation arg policy))
369            (flush-full-call-tail-transfer call))))
370
371   (values))
372
373 ;;; Annotate the arguments as ordinary single-value continuations. And check
374 ;;; the successor.
375 (defun ltn-analyze-local-call (call policy)
376   (declare (type combination call)
377            (type policies policy))
378   (setf (basic-combination-info call) :local)
379
380   (dolist (arg (basic-combination-args call))
381     (when arg
382       (annotate-ordinary-continuation arg policy)))
383
384   (when (node-tail-p call)
385     (set-tail-local-call-successor call))
386   (values))
387
388 ;;; Make sure that a tail local call is linked directly to the bind
389 ;;; node. Usually it will be, but calls from XEPs and calls that might have
390 ;;; needed a cleanup after them won't have been swung over yet, since we
391 ;;; weren't sure they would really be TR until now. Also called by byte
392 ;;; compiler.
393 (defun set-tail-local-call-successor (call)
394   (let ((caller (node-home-lambda call))
395         (callee (combination-lambda call)))
396     (assert (eq (lambda-tail-set caller)
397                 (lambda-tail-set (lambda-home callee))))
398     (node-ends-block call)
399     (let ((block (node-block call)))
400       (unlink-blocks block (first (block-succ block)))
401       (link-blocks block (node-block (lambda-bind callee)))))
402   (values))
403
404 ;;; Annotate the value continuation.
405 (defun ltn-analyze-set (node policy)
406   (declare (type cset node) (type policies policy))
407   (setf (node-tail-p node) nil)
408   (annotate-ordinary-continuation (set-value node) policy)
409   (values))
410
411 ;;; If the only use of the Test continuation is a combination annotated with
412 ;;; a conditional template, then don't annotate the continuation so that IR2
413 ;;; conversion knows not to emit any code, otherwise annotate as an ordinary
414 ;;; continuation. Since we only use a conditional template if the call
415 ;;; immediately precedes the IF node in the same block, we know that any
416 ;;; predicate will already be annotated.
417 (defun ltn-analyze-if (node policy)
418   (declare (type cif node) (type policies policy))
419   (setf (node-tail-p node) nil)
420   (let* ((test (if-test node))
421          (use (continuation-use test)))
422     (unless (and (combination-p use)
423                  (let ((info (basic-combination-info use)))
424                    (and (template-p info)
425                         (eq (template-result-types info) :conditional))))
426       (annotate-ordinary-continuation test policy)))
427   (values))
428
429 ;;; If there is a value continuation, then annotate it for unknown values.
430 ;;; In this case, the exit is non-local, since all other exits are deleted or
431 ;;; degenerate by this point.
432 (defun ltn-analyze-exit (node policy)
433   (setf (node-tail-p node) nil)
434   (let ((value (exit-value node)))
435     (when value
436       (annotate-unknown-values-continuation value policy)))
437   (values))
438
439 ;;; We need a special method for %Unwind-Protect that ignores the cleanup
440 ;;; function. We don't annotate either arg, since we don't need them at
441 ;;; run-time.
442 ;;;
443 ;;; [The default is o.k. for %Catch, since environment analysis converted the
444 ;;; reference to the escape function into a constant reference to the
445 ;;; NLX-Info.]
446 (defoptimizer (%unwind-protect ltn-annotate) ((escape cleanup) node policy)
447   policy ; Ignore...
448   (setf (basic-combination-info node) :funny)
449   (setf (node-tail-p node) nil))
450
451 ;;; Both of these functions need special LTN-annotate methods, since we only
452 ;;; want to clear the Type-Check in unsafe policies. If we allowed the call to
453 ;;; be annotated as a full call, then no type checking would be done.
454 ;;;
455 ;;; We also need a special LTN annotate method for %Slot-Setter so that the
456 ;;; function is ignored. This is because the reference to a SETF function
457 ;;; can't be delayed, so IR2 conversion would have already emitted a call to
458 ;;; FDEFINITION by the time the IR2 convert method got control.
459 (defoptimizer (%slot-accessor ltn-annotate) ((struct) node policy)
460   (setf (basic-combination-info node) :funny)
461   (setf (node-tail-p node) nil)
462   (annotate-ordinary-continuation struct policy))
463 (defoptimizer (%slot-setter ltn-annotate) ((struct value) node policy)
464   (setf (basic-combination-info node) :funny)
465   (setf (node-tail-p node) nil)
466   (annotate-ordinary-continuation struct policy)
467   (annotate-ordinary-continuation value policy))
468 \f
469 ;;;; known call annotation
470
471 ;;; Return true if Restr is satisfied by Type. If T-OK is true, then a T
472 ;;; restriction allows any operand type. This is also called by IR2tran when
473 ;;; it determines whether a result temporary needs to be made, and by
474 ;;; representation selection when it is deciding which move VOP to use.
475 ;;; Cont and TN are used to test for constant arguments.
476 #!-sb-fluid (declaim (inline operand-restriction-ok))
477 (defun operand-restriction-ok (restr type &key cont tn (t-ok t))
478   (declare (type (or (member *) cons) restr)
479            (type primitive-type type)
480            (type (or continuation null) cont)
481            (type (or tn null) tn))
482   (if (eq restr '*)
483       t
484       (ecase (first restr)
485         (:or
486          (dolist (mem (rest restr) nil)
487            (when (or (and t-ok (eq mem *backend-t-primitive-type*))
488                      (eq mem type))
489              (return t))))
490         (:constant
491          (cond (cont
492                 (and (constant-continuation-p cont)
493                      (funcall (second restr) (continuation-value cont))))
494                (tn
495                 (and (eq (tn-kind tn) :constant)
496                      (funcall (second restr) (tn-value tn))))
497                (t
498                 (error "Neither CONT nor TN supplied.")))))))
499
500 ;;; Check that the argument type restriction for Template are satisfied in
501 ;;; call. If an argument's TYPE-CHECK is :NO-CHECK and our policy is safe,
502 ;;; then only :SAFE templates are o.k.
503 (defun template-args-ok (template call safe-p)
504   (declare (type template template)
505            (type combination call))
506   (let ((mtype (template-more-args-type template)))
507     (do ((args (basic-combination-args call) (cdr args))
508          (types (template-arg-types template) (cdr types)))
509         ((null types)
510          (cond ((null args) t)
511                ((not mtype) nil)
512                (t
513                 (dolist (arg args t)
514                   (unless (operand-restriction-ok mtype
515                                                   (continuation-ptype arg))
516                     (return nil))))))
517       (when (null args) (return nil))
518       (let ((arg (car args))
519             (type (car types)))
520         (when (and (eq (continuation-type-check arg) :no-check)
521                    safe-p
522                    (not (eq (template-policy template) :safe)))
523           (return nil))
524         (unless (operand-restriction-ok type (continuation-ptype arg)
525                                         :cont arg)
526           (return nil))))))
527
528 ;;; Check that Template can be used with the specifed Result-Type. Result
529 ;;; type checking is pretty different from argument type checking due to the
530 ;;; relaxed rules for values count. We succeed if for each required result,
531 ;;; there is a positional restriction on the value that is at least as good.
532 ;;; If we run out of result types before we run out of restrictions, then we
533 ;;; only succeed if the leftover restrictions are *. If we run out of
534 ;;; restrictions before we run out of result types, then we always win.
535 (defun template-results-ok (template result-type)
536   (declare (type template template)
537            (type ctype result-type))
538   (when (template-more-results-type template)
539     (error "~S has :MORE results with :TRANSLATE." (template-name template)))
540   (let ((types (template-result-types template)))
541     (cond
542      ((values-type-p result-type)
543       (do ((ltypes (append (args-type-required result-type)
544                            (args-type-optional result-type))
545                    (rest ltypes))
546            (types types (rest types)))
547           ((null ltypes)
548            (dolist (type types t)
549              (unless (eq type '*)
550                (return nil))))
551         (when (null types) (return t))
552         (let ((type (first types)))
553           (unless (operand-restriction-ok type
554                                           (primitive-type (first ltypes)))
555             (return nil)))))
556      (types
557       (operand-restriction-ok (first types) (primitive-type result-type)))
558      (t t))))
559
560 ;;; Return true if Call is an ok use of Template according to Safe-P.
561 ;;; -- If the template has a Guard that isn't true, then we ignore the
562 ;;;    template, not even considering it to be rejected.
563 ;;; -- If the argument type restrictions aren't satisfied, then we reject the
564 ;;;    template.
565 ;;; -- If the template is :Conditional, then we accept it only when the
566 ;;;    destination of the value is an immediately following IF node.
567 ;;; -- If either the template is safe or the policy is unsafe (i.e. we can
568 ;;;    believe output assertions), then we test against the intersection of the
569 ;;;    node derived type and the continuation asserted type. Otherwise, we
570 ;;;    just use the node type. If TYPE-CHECK is null, there is no point in
571 ;;;    doing the intersection, since the node type must be a subtype of the
572 ;;;    assertion.
573 ;;;
574 ;;; If the template is *not* ok, then the second value is a keyword indicating
575 ;;; which aspect failed.
576 (defun is-ok-template-use (template call safe-p)
577   (declare (type template template) (type combination call))
578   (let* ((guard (template-guard template))
579          (cont (node-cont call))
580          (atype (continuation-asserted-type cont))
581          (dtype (node-derived-type call)))
582     (cond ((and guard (not (funcall guard)))
583            (values nil :guard))
584           ((not (template-args-ok template call safe-p))
585            (values nil
586                    (if (and safe-p (template-args-ok template call nil))
587                        :arg-check
588                        :arg-types)))
589           ((eq (template-result-types template) :conditional)
590            (let ((dest (continuation-dest cont)))
591              (if (and (if-p dest)
592                       (immediately-used-p (if-test dest) call))
593                  (values t nil)
594                  (values nil :conditional))))
595           ((template-results-ok
596             template
597             (if (and (or (eq (template-policy template) :safe)
598                          (not safe-p))
599                      (continuation-type-check cont))
600                 (values-type-intersection dtype atype)
601                 dtype))
602            (values t nil))
603           (t
604            (values nil :result-types)))))
605
606 ;;; Use operand type information to choose a template from the list
607 ;;; Templates for a known Call. We return three values:
608 ;;; 1. The template we found.
609 ;;; 2. Some template that we rejected due to unsatisfied type restrictions, or
610 ;;;    NIL if none.
611 ;;; 3. The tail of Templates for templates we haven't examined yet.
612 ;;;
613 ;;; We just call IS-OK-TEMPLATE-USE until it returns true.
614 (defun find-template (templates call safe-p)
615   (declare (list templates) (type combination call))
616   (do ((templates templates (rest templates))
617        (rejected nil))
618       ((null templates)
619        (values nil rejected nil))
620     (let ((template (first templates)))
621       (when (is-ok-template-use template call safe-p)
622         (return (values template rejected (rest templates))))
623       (setq rejected template))))
624
625 ;;; Given a partially annotated known call and a translation policy, return
626 ;;; the appropriate template, or NIL if none can be found. We scan the
627 ;;; templates (ordered by increasing cost) looking for a template whose
628 ;;; restrictions are satisfied and that has our policy.
629 ;;;
630 ;;; If we find a template that doesn't have our policy, but has a legal
631 ;;; alternate policy, then we also record that to return as a last resort. If
632 ;;; our policy is safe, then only safe policies are O.K., otherwise anything
633 ;;; goes.
634 ;;;
635 ;;; If we find a template with :SAFE policy, then we return it, or any cheaper
636 ;;; fallback template. The theory behind this is that if it is cheapest, small
637 ;;; and safe, we can't lose. If it is not cheapest, then we use the fallback,
638 ;;; which won't have the desired policy, but :SAFE isn't desired either, so we
639 ;;; might as well go with the cheaper one. The main reason for doing this is
640 ;;; to make sure that cheap safe templates are used when they apply and the
641 ;;; current policy is something else. This is useful because :SAFE has the
642 ;;; additional semantics of implicit argument type checking, so we may be
643 ;;; forced to define a template with :SAFE policy when it is really small and
644 ;;; fast as well.
645 (defun find-template-for-policy (call policy)
646   (declare (type combination call)
647            (type policies policy))
648   (let ((safe-p (policy-safe-p policy))
649         (current (function-info-templates (basic-combination-kind call)))
650         (fallback nil)
651         (rejected nil))
652     (loop
653      (multiple-value-bind (template this-reject more)
654          (find-template current call safe-p)
655        (unless rejected
656          (setq rejected this-reject))
657        (setq current more)
658        (unless template
659          (return (values fallback rejected)))
660
661        (let ((tpolicy (template-policy template)))
662          (cond ((eq tpolicy policy)
663                 (return (values template rejected)))
664                ((eq tpolicy :safe)
665                 (return (values (or fallback template) rejected)))
666                ((or (not safe-p) (eq tpolicy :fast-safe))
667                 (unless fallback
668                   (setq fallback template)))))))))
669
670 (defvar *efficiency-note-limit* 2
671   #!+sb-doc
672   "This is the maximum number of possible optimization alternatives will be
673   mentioned in a particular efficiency note. NIL means no limit.")
674 (declaim (type (or index null) *efficiency-note-limit*))
675
676 (defvar *efficiency-note-cost-threshold* 5
677   #!+sb-doc
678   "This is the minumum cost difference between the chosen implementation and
679   the next alternative that justifies an efficiency note.")
680 (declaim (type index *efficiency-note-cost-threshold*))
681
682 ;;;    This function is called by NOTE-REJECTED-TEMPLATES when it can't figure
683 ;;; out any reason why Template was rejected. Users should never see these
684 ;;; messages, but they can happen in situations where the VM definition is
685 ;;; messed up somehow.
686 (defun strange-template-failure (template call policy frob)
687   (declare (type template template) (type combination call)
688            (type policies policy) (type function frob))
689   (funcall frob "This shouldn't happen!  Bug?")
690   (multiple-value-bind (win why)
691       (is-ok-template-use template call (policy-safe-p policy))
692     (assert (not win))
693     (ecase why
694       (:guard
695        (funcall frob "template guard failed"))
696       (:arg-check
697        (funcall frob "The template isn't safe, yet we were counting on it."))
698       (:arg-types
699        (funcall frob "argument types invalid")
700        (funcall frob "argument primitive types:~%  ~S"
701                 (mapcar #'(lambda (x)
702                             (primitive-type-name
703                              (continuation-ptype x)))
704                         (combination-args call)))
705        (funcall frob "argument type assertions:~%  ~S"
706                 (mapcar #'(lambda (x)
707                             (if (atom x)
708                                 x
709                                 (ecase (car x)
710                                   (:or `(:or .,(mapcar #'primitive-type-name
711                                                        (cdr x))))
712                                   (:constant `(:constant ,(third x))))))
713                         (template-arg-types template))))
714       (:conditional
715        (funcall frob "conditional in a non-conditional context"))
716       (:result-types
717        (funcall frob "result types invalid")))))
718
719 ;;; This function emits efficiency notes describing all of the templates
720 ;;; better (faster) than Template that we might have been able to use if there
721 ;;; were better type declarations. Template is null when we didn't find any
722 ;;; template, and thus must do a full call.
723 ;;;
724 ;;; In order to be worth complaining about, a template must:
725 ;;; -- be allowed by its guard,
726 ;;; -- be safe if the current policy is safe,
727 ;;; -- have argument/result type restrictions consistent with the known type
728 ;;;    information, e.g. we don't consider float templates when an operand is
729 ;;;    known to be an integer,
730 ;;; -- be disallowed by the stricter operand subtype test (which resembles, but
731 ;;;    is not identical to the test done by Find-Template.)
732 ;;;
733 ;;; Note that there may not be any possibly applicable templates, since we are
734 ;;; called whenever any template is rejected. That template might have the
735 ;;; wrong policy or be inconsistent with the known type.
736 ;;;
737 ;;; We go to some trouble to make the whole multi-line output into a single
738 ;;; call to Compiler-Note so that repeat messages are suppressed, etc.
739 (defun note-rejected-templates (call policy template)
740   (declare (type combination call) (type policies policy)
741            (type (or template null) template))
742
743   (collect ((losers))
744     (let ((safe-p (policy-safe-p policy))
745           (verbose-p (policy call (= brevity 0)))
746           (max-cost (- (template-cost
747                         (or template
748                             (template-or-lose 'call-named)))
749                        *efficiency-note-cost-threshold*)))
750       (dolist (try (function-info-templates (basic-combination-kind call)))
751         (when (> (template-cost try) max-cost) (return))
752         (let ((guard (template-guard try)))
753           (when (and (or (not guard) (funcall guard))
754                      (or (not safe-p)
755                          (policy-safe-p (template-policy try)))
756                      (or verbose-p
757                          (and (template-note try)
758                               (valid-function-use
759                                call (template-type try)
760                                :argument-test #'types-intersect
761                                :result-test #'values-types-intersect))))
762             (losers try)))))
763
764     (when (losers)
765       (collect ((messages)
766                 (count 0 +))
767         (flet ((frob (string &rest stuff)
768                  (messages string)
769                  (messages stuff)))
770           (dolist (loser (losers))
771             (when (and *efficiency-note-limit*
772                        (>= (count) *efficiency-note-limit*))
773               (frob "etc.")
774               (return))
775             (let* ((type (template-type loser))
776                    (valid (valid-function-use call type))
777                    (strict-valid (valid-function-use call type
778                                                      :strict-result t)))
779               (frob "unable to do ~A (cost ~D) because:"
780                     (or (template-note loser) (template-name loser))
781                     (template-cost loser))
782               (cond
783                ((and valid strict-valid)
784                 (strange-template-failure loser call policy #'frob))
785                ((not valid)
786                 (assert (not (valid-function-use call type
787                                                  :error-function #'frob
788                                                  :warning-function #'frob))))
789                (t
790                 (assert (policy-safe-p policy))
791                 (frob "can't trust output type assertion under safe policy")))
792               (count 1))))
793
794         (let ((*compiler-error-context* call))
795           (compiler-note "~{~?~^~&~6T~}"
796                          (if template
797                              `("forced to do ~A (cost ~D)"
798                                (,(or (template-note template)
799                                      (template-name template))
800                                 ,(template-cost template))
801                                . ,(messages))
802                              `("forced to do full call"
803                                nil
804                                . ,(messages))))))))
805   (values))
806
807 ;;; Flush type checks according to policy. If the policy is
808 ;;; unsafe, then we never do any checks. If our policy is safe, and
809 ;;; we are using a safe template, then we can also flush arg and
810 ;;; result type checks. Result type checks are only flushed when the
811 ;;; continuation as a single use. Result type checks are not flush if
812 ;;; the policy is safe because the selection of template for results
813 ;;; readers assumes the type check is done (uses the derived type
814 ;;; which is the intersection of the proven and asserted types).
815 (defun flush-type-checks-according-to-policy (call policy template)
816   (declare (type combination call) (type policies policy)
817            (type template template))
818   (let ((safe-op (eq (template-policy template) :safe)))
819     (when (or (not (policy-safe-p policy)) safe-op)
820       (dolist (arg (basic-combination-args call))
821         (flush-type-check arg)))
822     (when safe-op
823       (let ((cont (node-cont call)))
824         (when (and (eq (continuation-use cont) call)
825                    (not (policy-safe-p policy)))
826           (flush-type-check cont)))))
827
828   (values))
829
830 ;;; If a function has a special-case annotation method use that, otherwise
831 ;;; annotate the argument continuations and try to find a template
832 ;;; corresponding to the type signature. If there is none, convert a full call.
833 (defun ltn-analyze-known-call (call policy)
834   (declare (type combination call)
835            (type policies policy))
836   (let ((method (function-info-ltn-annotate (basic-combination-kind call)))
837         (args (basic-combination-args call)))
838     (when method
839       (funcall method call policy)
840       (return-from ltn-analyze-known-call (values)))
841
842     (dolist (arg args)
843       (setf (continuation-info arg)
844             (make-ir2-continuation (primitive-type (continuation-type arg)))))
845
846     (multiple-value-bind (template rejected)
847         (find-template-for-policy call policy)
848       ;; If we are unable to use some templates due to unsatisfied operand type
849       ;; restrictions and our policy enables efficiency notes, then we call
850       ;; Note-Rejected-Templates.
851       (when (and rejected
852                  (policy call (> speed brevity)))
853         (note-rejected-templates call policy template))
854       ;; If we are forced to do a full call, we check to see whether the
855       ;; function called is the same as the current function. If so, we
856       ;; give a warning, as this is probably a botched interpreter stub.
857       (unless template
858         (when (and (eq (continuation-function-name (combination-fun call))
859                        (leaf-name
860                         (environment-function
861                          (node-environment call))))
862                    (let ((info (basic-combination-kind call)))
863                      (not (or (function-info-ir2-convert info)
864                               (ir1-attributep (function-info-attributes info)
865                                               recursive)))))
866           (let ((*compiler-error-context* call))
867             (compiler-warning "recursive known function definition")))
868         (ltn-default-call call policy)
869         (return-from ltn-analyze-known-call (values)))
870       (setf (basic-combination-info call) template)
871       (setf (node-tail-p call) nil)
872
873       (flush-type-checks-according-to-policy call policy template)
874
875       (dolist (arg args)
876         (annotate-1-value-continuation arg))))
877
878   (values))
879 \f
880 ;;;; interfaces
881
882 ;;;    We make the main per-block code in for LTN into a macro so that it can
883 ;;; be shared between LTN-Analyze and LTN-Analyze-Block, yet can cache policy
884 ;;; across blocks in the normal (full component) case.
885 ;;;
886 ;;;    This code computes the policy and then dispatches to the appropriate
887 ;;; node-specific function.
888 ;;;
889 ;;; Note: we deliberately don't use the DO-NODES macro, since the block can be
890 ;;; split out from underneath us, and DO-NODES would scan past the block end in that
891 ;;; case.
892 (macrolet ((frob ()
893              '(do* ((node (continuation-next (block-start block))
894                           (continuation-next cont))
895                     (cont (node-cont node) (node-cont node))
896                     ;; KLUDGE: Since LEXENV and POLICY seem to be only used
897                     ;; inside this FROB, why not define them in here instead of
898                     ;; requiring them to be defined externally both in
899                     ;; LTN-ANALYZE and LTN-ANALYZE-BLOCK? Or perhaps just
900                     ;; define this whole FROB as an inline function? (Right now
901                     ;; I don't want to make even a small unnecessary change
902                     ;; like this, but'd prefer to wait until the system runs so
903                     ;; that I can test it immediately after the change.)
904                     ;; -- WHN 19990808
905                     )
906                   (())
907                 (unless (eq (node-lexenv node) lexenv)
908                   (setq policy (translation-policy node))
909                   (setq lexenv (node-lexenv node)))
910
911                 (etypecase node
912                   (ref)
913                   (combination
914                    (case (basic-combination-kind node)
915                      (:local (ltn-analyze-local-call node policy))
916                      ((:full :error) (ltn-default-call node policy))
917                      (t
918                       (ltn-analyze-known-call node policy))))
919                   (cif
920                    (ltn-analyze-if node policy))
921                   (creturn
922                    (ltn-analyze-return node policy))
923                   ((or bind entry))
924                   (exit
925                    (ltn-analyze-exit node policy))
926                   (cset (ltn-analyze-set node policy))
927                   (mv-combination
928                    (ecase (basic-combination-kind node)
929                      (:local (ltn-analyze-mv-bind node policy))
930                      ((:full :error) (ltn-analyze-mv-call node policy)))))
931
932                 (when (eq node (block-last block))
933                   (return)))))
934
935 ;;; Loop over the blocks in Component, doing stuff to nodes that receive
936 ;;; values. In addition to the stuff done by FROB, we also see whether there
937 ;;; are any unknown values receivers, making notations in the components
938 ;;; Generators and Receivers as appropriate.
939 ;;;
940 ;;; If any unknown-values continations are received by this block (as
941 ;;; indicated by IR2-Block-Popped, then we add the block to the
942 ;;; IR2-Component-Values-Receivers.
943 ;;;
944 ;;; This is where we allocate IR2 blocks because it is the first place we
945 ;;; need them.
946 (defun ltn-analyze (component)
947   (declare (type component component))
948   (let ((2comp (component-info component))
949         (lexenv nil)
950         policy)
951     (do-blocks (block component)
952       (assert (not (block-info block)))
953       (let ((2block (make-ir2-block block)))
954         (setf (block-info block) 2block)
955         (frob)
956         (let ((popped (ir2-block-popped 2block)))
957           (when popped
958             (push block (ir2-component-values-receivers 2comp)))))))
959   (values))
960
961 ;;; This function is used to analyze blocks that must be added to the flow
962 ;;; graph after the normal LTN phase runs. Such code is constrained not to
963 ;;; use weird unknown values (and probably in lots of other ways).
964 (defun ltn-analyze-block (block)
965   (declare (type cblock block))
966   (let ((lexenv nil)
967         policy)
968     (frob))
969   (assert (not (ir2-block-popped (block-info block))))
970   (values))
971
972 ) ; MACROLET FROB