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