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