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