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