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