0.6.11.23:
[sbcl.git] / src / compiler / checkgen.lisp
1 ;;;; This file implements type check generation. This is a phase that
2 ;;;; runs at the very end of IR1. If a type check is too complex for
3 ;;;; the back end to directly emit in-line, then we transform the check
4 ;;;; into an explicit conditional using TYPEP.
5
6 ;;;; This software is part of the SBCL system. See the README file for
7 ;;;; more information.
8 ;;;;
9 ;;;; This software is derived from the CMU CL system, which was
10 ;;;; written at Carnegie Mellon University and released into the
11 ;;;; public domain. The software is in the public domain and is
12 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
13 ;;;; files for more information.
14
15 (in-package "SB!C")
16 \f
17 ;;;; cost estimation
18
19 ;;; Return some sort of guess about the cost of a call to a function.
20 ;;; If the function has some templates, we return the cost of the
21 ;;; cheapest one, otherwise we return the cost of CALL-NAMED. Calling
22 ;;; this with functions that have transforms can result in relatively
23 ;;; meaningless results (exaggerated costs.)
24 ;;;
25 ;;; We special-case NULL, since it does have a source tranform and is
26 ;;; interesting to us.
27 (defun function-cost (name)
28   (declare (symbol name))
29   (let ((info (info :function :info name))
30         (call-cost (template-cost (template-or-lose 'call-named))))
31     (if info
32         (let ((templates (function-info-templates info)))
33           (if templates
34               (template-cost (first templates))
35               (case name
36                 (null (template-cost (template-or-lose 'if-eq)))
37                 (t call-cost))))
38         call-cost)))
39
40 ;;; Return some sort of guess for the cost of doing a test against
41 ;;; TYPE. The result need not be precise as long as it isn't way out
42 ;;; in space. The units are based on the costs specified for various
43 ;;; templates in the VM definition.
44 (defun type-test-cost (type)
45   (declare (type ctype type))
46   (or (let ((check (type-check-template type)))
47         (if check
48             (template-cost check)
49             (let ((found (cdr (assoc type *backend-type-predicates*
50                                      :test #'type=))))
51               (if found
52                   (+ (function-cost found) (function-cost 'eq))
53                   nil))))
54       (typecase type
55         (compound-type
56          (reduce #'+ (compound-type-types type) :key 'type-test-cost))
57         (member-type
58          (* (length (member-type-members type))
59             (function-cost 'eq)))
60         (numeric-type
61          (* (if (numeric-type-complexp type) 2 1)
62             (function-cost
63              (if (csubtypep type (specifier-type 'fixnum)) 'fixnump 'numberp))
64             (+ 1
65                (if (numeric-type-low type) 1 0)
66                (if (numeric-type-high type) 1 0))))
67         (cons-type
68          (+ (type-test-cost (specifier-type 'cons))
69             (function-cost 'car)
70             (type-test-cost (cons-type-car-type type))
71             (function-cost 'cdr)
72             (type-test-cost (cons-type-cdr-type type))))
73         (t
74          (function-cost 'typep)))))
75 \f
76 ;;;; checking strategy determination
77
78 ;;; Return the type we should test for when we really want to check
79 ;;; for TYPE. If speed, space or compilation speed is more important
80 ;;; than safety, then we return a weaker type if it is easier to
81 ;;; check. First we try the defined type weakenings, then look for any
82 ;;; predicate that is cheaper.
83 ;;;
84 ;;; If the supertype is equal in cost to the type, we prefer the
85 ;;; supertype. This produces a closer approximation of the right thing
86 ;;; in the presence of poor cost info.
87 (defun maybe-weaken-check (type cont)
88   (declare (type ctype type) (type continuation cont))
89   (cond ((policy (continuation-dest cont)
90                  (and (<= speed safety)
91                       (<= space safety)
92                       (<= compilation-speed safety)))
93          type)
94         (t
95          (let ((min-cost (type-test-cost type))
96                (min-type type)
97                (found-super nil))
98            (dolist (x *backend-type-predicates*)
99              (let ((stype (car x)))
100                (when (and (csubtypep type stype)
101                           (not (union-type-p stype)))
102                  (let ((stype-cost (type-test-cost stype)))
103                    (when (or (< stype-cost min-cost)
104                              (type= stype type))
105                      (setq found-super t
106                            min-type stype
107                            min-cost stype-cost))))))
108            (if found-super
109                min-type
110                *universal-type*)))))
111
112 ;;; Like VALUES-TYPES, only mash any complex function types to FUNCTION.
113 (defun no-function-values-types (type)
114   (declare (type ctype type))
115   (multiple-value-bind (res count) (values-types type)
116     (values (mapcar #'(lambda (type)
117                         (if (function-type-p type)
118                             (specifier-type 'function)
119                             type))
120                     res)
121             count)))
122
123 ;;; Switch to disable check complementing, for evaluation.
124 (defvar *complement-type-checks* t)
125
126 ;;; CONT is a continuation we are doing a type check on and TYPES is a
127 ;;; list of types that we are checking its values against. If we have
128 ;;; proven that CONT generates a fixed number of values, then for each
129 ;;; value, we check whether it is cheaper to then difference between
130 ;;; the proven type and the corresponding type in TYPES. If so, we opt
131 ;;; for a :HAIRY check with that test negated. Otherwise, we try to do
132 ;;; a simple test, and if that is impossible, we do a hairy test with
133 ;;; non-negated types. If true, Force-Hairy forces a hairy type check.
134 ;;;
135 ;;; When doing a non-negated check, we call MAYBE-WEAKEN-CHECK to
136 ;;; weaken the test to a convenient supertype (conditional on policy.)
137 ;;; If SPEED is 3, or DEBUG-INFO is not particularly important (DEBUG
138 ;;; <= 1), then we allow weakened checks to be simple, resulting in
139 ;;; less informative error messages, but saving space and possibly
140 ;;; time.
141 ;;;
142 ;;; FIXME: I don't quite understand this, but it looks as though
143 ;;; that means type checks are weakened when SPEED=3 regardless of
144 ;;; the SAFETY level, which is not the right thing to do.
145 (defun maybe-negate-check (cont types force-hairy)
146   (declare (type continuation cont) (list types))
147   (multiple-value-bind (ptypes count)
148       (no-function-values-types (continuation-proven-type cont))
149     (if (eq count :unknown)
150         (if (and (every #'type-check-template types) (not force-hairy))
151             (values :simple types)
152             (values :hairy
153                     (mapcar #'(lambda (x)
154                                 (list nil (maybe-weaken-check x cont) x))
155                             types)))
156         (let ((res (mapcar #'(lambda (p c)
157                                (let ((diff (type-difference p c))
158                                      (weak (maybe-weaken-check c cont)))
159                                  (if (and diff
160                                           (< (type-test-cost diff)
161                                              (type-test-cost weak))
162                                           *complement-type-checks*)
163                                      (list t diff c)
164                                      (list nil weak c))))
165                            ptypes types)))
166           (cond ((or force-hairy (find-if #'first res))
167                  (values :hairy res))
168                 ((every #'type-check-template types)
169                  (values :simple types))
170                 ((policy (continuation-dest cont)
171                          (or (<= debug 1) (and (= speed 3) (/= debug 3))))
172                  (let ((weakened (mapcar #'second res)))
173                    (if (every #'type-check-template weakened)
174                        (values :simple weakened)
175                        (values :hairy res))))
176                 (t
177                  (values :hairy res)))))))
178
179 ;;; Determines whether CONT's assertion is:
180 ;;;  -- checkable by the back end (:SIMPLE), or
181 ;;;  -- not checkable by the back end, but checkable via an explicit 
182 ;;;     test in type check conversion (:HAIRY), or
183 ;;;  -- not reasonably checkable at all (:TOO-HAIRY).
184 ;;;
185 ;;; A type is checkable if it either represents a fixed number of
186 ;;; values (as determined by VALUES-TYPES), or it is the assertion for
187 ;;; an MV-Bind. A type is simply checkable if all the type assertions
188 ;;; have a TYPE-CHECK-TEMPLATE. In this :SIMPLE case, the second value
189 ;;; is a list of the type restrictions specified for the leading
190 ;;; positional values.
191 ;;;
192 ;;; We force a check to be hairy even when there are fixed values if
193 ;;; we are in a context where we may be forced to use the unknown
194 ;;; values convention anyway. This is because IR2tran can't generate
195 ;;; type checks for unknown values continuations but people could
196 ;;; still be depending on the check being done. We only care about
197 ;;; EXIT and RETURN (not MV-COMBINATION) since these are the only
198 ;;; contexts where the ultimate values receiver
199 ;;;
200 ;;; In the :HAIRY case, the second value is a list of triples of
201 ;;; the form:
202 ;;;    (NOT-P TYPE ORIGINAL-TYPE)
203 ;;;
204 ;;; If true, the NOT-P flag indicates a test that the corresponding
205 ;;; value is *not* of the specified TYPE. ORIGINAL-TYPE is the type
206 ;;; asserted on this value in the continuation, for use in error
207 ;;; messages. When NOT-P is true, this will be different from TYPE.
208 ;;;
209 ;;; This allows us to take what has been proven about CONT's type into
210 ;;; consideration. If it is cheaper to test for the difference between
211 ;;; the derived type and the asserted type, then we check for the
212 ;;; negation of this type instead.
213 (defun continuation-check-types (cont)
214   (declare (type continuation cont))
215   (let ((type (continuation-asserted-type cont))
216         (dest (continuation-dest cont)))
217     (aver (not (eq type *wild-type*)))
218     (multiple-value-bind (types count) (no-function-values-types type)
219       (cond ((not (eq count :unknown))
220              (if (or (exit-p dest)
221                      (and (return-p dest)
222                           (multiple-value-bind (ignore count)
223                               (values-types (return-result-type dest))
224                             (declare (ignore ignore))
225                             (eq count :unknown))))
226                  (maybe-negate-check cont types t)
227                  (maybe-negate-check cont types nil)))
228             ((and (mv-combination-p dest)
229                   (eq (basic-combination-kind dest) :local))
230              (aver (values-type-p type))
231              (maybe-negate-check cont (args-type-optional type) nil))
232             (t
233              (values :too-hairy nil))))))
234
235 ;;; Return true if CONT is a continuation whose type the back end is
236 ;;; likely to want to check. Since we don't know what template the
237 ;;; back end is going to choose to implement the continuation's DEST,
238 ;;; we use a heuristic. We always return T unless:
239 ;;;  -- nobody uses the value, or
240 ;;;  -- safety is totally unimportant, or
241 ;;;  -- the continuation is an argument to an unknown function, or
242 ;;;  -- the continuation is an argument to a known function that has 
243 ;;;     no IR2-Convert method or :FAST-SAFE templates that are
244 ;;;     compatible with the call's type.
245 ;;;
246 ;;; We must only return NIL when it is *certain* that a check will not
247 ;;; be done, since if we pass up this chance to do the check, it will
248 ;;; be too late. The penalty for being too conservative is duplicated
249 ;;; type checks. The penalty for erring by being too speculative is
250 ;;; much nastier, e.g. falling through without ever being able to find
251 ;;; an appropriate VOP.
252 ;;;
253 ;;; If there is a compile-time type error, then we always return true
254 ;;; unless the DEST is a full call. With a full call, the theory is
255 ;;; that the type error is probably from a declaration in (or on) the
256 ;;; callee, so the callee should be able to do the check. We want to
257 ;;; let the callee do the check, because it is possible that the error
258 ;;; is really in the callee, not the caller. We don't want to make
259 ;;; people recompile all calls to a function when they were originally
260 ;;; compiled with a bad declaration (or an old type assertion derived
261 ;;; from a definition appearing after the call.)
262 (defun probable-type-check-p (cont)
263   (declare (type continuation cont))
264   (let ((dest (continuation-dest cont)))
265     (cond ((eq (continuation-type-check cont) :error)
266            (if (and (combination-p dest) (eq (combination-kind dest) :error))
267                nil
268                t))
269           ((or (not dest)
270                (policy dest (zerop safety)))
271            nil)
272           ((basic-combination-p dest)
273            (let ((kind (basic-combination-kind dest)))
274              (cond ((eq cont (basic-combination-fun dest)) t)
275                    ((eq kind :local) t)
276                    ((member kind '(:full :error)) nil)
277                    ((function-info-ir2-convert kind) t)
278                    (t
279                     (dolist (template (function-info-templates kind) nil)
280                       (when (eq (template-ltn-policy template) :fast-safe)
281                         (multiple-value-bind (val win)
282                             (valid-function-use dest (template-type template))
283                           (when (or val (not win)) (return t)))))))))
284           (t t))))
285
286 ;;; Return a form that we can convert to do a hairy type check of the
287 ;;; specified TYPES. TYPES is a list of the format returned by
288 ;;; CONTINUATION-CHECK-TYPES in the :HAIRY case. In place of the
289 ;;; actual value(s) we are to check, we use 'DUMMY. This constant
290 ;;; reference is later replaced with the actual values continuation.
291 ;;;
292 ;;; Note that we don't attempt to check for required values being
293 ;;; unsupplied. Such checking is impossible to efficiently do at the
294 ;;; source level because our fixed-values conventions are optimized
295 ;;; for the common MV-BIND case.
296 ;;;
297 ;;; We can always use MULTIPLE-VALUE-BIND, since the macro is clever
298 ;;; about binding a single variable.
299 (defun make-type-check-form (types)
300   (let ((temps (make-gensym-list (length types))))
301     `(multiple-value-bind ,temps 'dummy
302        ,@(mapcar #'(lambda (temp type)
303                      (let* ((spec
304                              (let ((*unparse-function-type-simplify* t))
305                                (type-specifier (second type))))
306                             (test (if (first type) `(not ,spec) spec)))
307                        `(unless (typep ,temp ',test)
308                           (%type-check-error
309                            ,temp
310                            ',(type-specifier (third type))))))
311                  temps
312                  types)
313        (values ,@temps))))
314
315 ;;; Splice in explicit type check code immediately before the node
316 ;;; which is CONT's DEST. This code receives the value(s) that were
317 ;;; being passed to CONT, checks the type(s) of the value(s), then
318 ;;; passes them on to CONT.
319 (defun convert-type-check (cont types)
320   (declare (type continuation cont) (type list types))
321   (with-ir1-environment (continuation-dest cont)
322
323     ;; Ensuring that CONT starts a block lets us freely manipulate its uses.
324     (ensure-block-start cont)
325
326     ;; Make a new continuation and move CONT's uses to it.
327     (let* ((new-start (make-continuation))
328            (dest (continuation-dest cont))
329            (prev (node-prev dest)))
330       (continuation-starts-block new-start)
331       (substitute-continuation-uses new-start cont)
332
333       ;; Setting TYPE-CHECK in CONT to :DELETED indicates that the
334       ;; check has been done.
335       (setf (continuation-%type-check cont) :deleted)
336
337       ;; Make the DEST node start its block so that we can splice in
338       ;; the type check code.
339       (when (continuation-use prev)
340         (node-ends-block (continuation-use prev)))
341
342       (let* ((prev-block (continuation-block prev))
343              (new-block (continuation-block new-start))
344              (dummy (make-continuation)))
345
346         ;; Splice in the new block before DEST, giving the new block
347         ;; all of DEST's predecessors.
348         (dolist (block (block-pred prev-block))
349           (change-block-successor block prev-block new-block))
350
351         ;; Convert the check form, using the new block start as START
352         ;; and a dummy continuation as CONT.
353         (ir1-convert new-start dummy (make-type-check-form types))
354
355         ;; TO DO: Why should this be true? -- WHN 19990601
356         (aver (eq (continuation-block dummy) new-block))
357
358         ;; KLUDGE: Comments at the head of this function in CMU CL
359         ;; said that somewhere in here we
360         ;;   Set the new block's start and end cleanups to the *start*
361         ;;   cleanup of PREV's block. This overrides the incorrect
362         ;;   default from WITH-IR1-ENVIRONMENT.
363         ;; Unfortunately I can't find any code which corresponds to this.
364         ;; Perhaps it was a stale comment? Or perhaps I just don't
365         ;; understand.. -- WHN 19990521
366
367         (let ((node (continuation-use dummy)))
368           (setf (block-last new-block) node)
369           ;; Change the use to a use of CONT. (We need to use the
370           ;; dummy continuation to get the control transfer right,
371           ;; because we want to go to PREV's block, not CONT's.)
372           (delete-continuation-use node)
373           (add-continuation-use node cont))
374         ;; Link the new block to PREV's block.
375         (link-blocks new-block prev-block))
376
377       ;; MAKE-TYPE-CHECK-FORM generated a form which checked the type
378       ;; of 'DUMMY, not a real form. At this point we convert to the
379       ;; real form by finding 'DUMMY and overwriting it with the new
380       ;; continuation. (We can find 'DUMMY because no LET conversion
381       ;; has been done yet.) The [mv-]combination code from the
382       ;; mv-bind in the check form will be the use of the new check
383       ;; continuation. We substitute for the first argument of this
384       ;; node.
385       (let* ((node (continuation-use cont))
386              (args (basic-combination-args node))
387              (victim (first args)))
388         (aver (and (= (length args) 1)
389                      (eq (constant-value
390                           (ref-leaf
391                            (continuation-use victim)))
392                          'dummy)))
393         (substitute-continuation new-start victim)))
394
395     ;; Invoking local call analysis converts this call to a LET.
396     (local-call-analyze *current-component*))
397
398   (values))
399
400 ;;; Emit a type warning for NODE. If the value of NODE is being used
401 ;;; for a variable binding, we figure out which one for source
402 ;;; context. If the value is a constant, we print it specially. We
403 ;;; ignore nodes whose type is NIL, since they are supposed to never
404 ;;; return.
405 (defun do-type-warning (node)
406   (declare (type node node))
407   (let* ((*compiler-error-context* node)
408          (cont (node-cont node))
409          (atype-spec (type-specifier (continuation-asserted-type cont)))
410          (dtype (node-derived-type node))
411          (dest (continuation-dest cont))
412          (what (when (and (combination-p dest)
413                           (eq (combination-kind dest) :local))
414                  (let ((lambda (combination-lambda dest))
415                        (pos (position-or-lose cont (combination-args dest))))
416                    (format nil "~:[A possible~;The~] binding of ~S"
417                            (and (continuation-use cont)
418                                 (eq (functional-kind lambda) :let))
419                            (leaf-name (elt (lambda-vars lambda) pos)))))))
420     (cond ((eq dtype *empty-type*))
421           ((and (ref-p node) (constant-p (ref-leaf node)))
422            (compiler-warning "~:[This~;~:*~A~] is not a ~<~%~9T~:;~S:~>~%  ~S"
423                              what atype-spec (constant-value (ref-leaf node))))
424           (t
425            (compiler-warning
426             "~:[Result~;~:*~A~] is a ~S, ~<~%~9T~:;not a ~S.~>"
427             what (type-specifier dtype) atype-spec))))
428   (values))
429
430 ;;; Mark CONT as being a continuation with a manifest type error. We
431 ;;; set the kind to :ERROR, and clear any FUNCTION-INFO if the
432 ;;; continuation is an argument to a known call. The last is done so
433 ;;; that the back end doesn't have to worry about type errors in
434 ;;; arguments to known functions. This clearing is inhibited for
435 ;;; things with IR2-CONVERT methods, since we can't do a full call to
436 ;;; funny functions.
437 (defun mark-error-continuation (cont)
438   (declare (type continuation cont))
439   (setf (continuation-%type-check cont) :error)
440   (let ((dest (continuation-dest cont)))
441     (when (and (combination-p dest)
442                (let ((kind (basic-combination-kind dest)))
443                  (or (eq kind :full)
444                      (and (function-info-p kind)
445                           (not (function-info-ir2-convert kind))))))
446       (setf (basic-combination-kind dest) :error)))
447   (values))
448
449 ;;; Loop over all blocks in Component that have TYPE-CHECK set,
450 ;;; looking for continuations with TYPE-CHECK T. We do two mostly
451 ;;; unrelated things: detect compile-time type errors and determine if
452 ;;; and how to do run-time type checks.
453 ;;;
454 ;;; If there is a compile-time type error, then we mark the
455 ;;; continuation and emit a warning if appropriate. This part loops
456 ;;; over all the uses of the continuation, since after we convert the
457 ;;; check, the :DELETED kind will inhibit warnings about the types of
458 ;;; other uses.
459 ;;;
460 ;;; If a continuation is too complex to be checked by the back end, or
461 ;;; is better checked with explicit code, then convert to an explicit
462 ;;; test. Assertions that can checked by the back end are passed
463 ;;; through. Assertions that can't be tested are flamed about and
464 ;;; marked as not needing to be checked.
465 ;;;
466 ;;; If we determine that a type check won't be done, then we set
467 ;;; TYPE-CHECK to :NO-CHECK. In the non-hairy cases, this is just to
468 ;;; prevent us from wasting time coming to the same conclusion again
469 ;;; on a later iteration. In the hairy case, we must indicate to LTN
470 ;;; that it must choose a safe implementation, since IR2 conversion
471 ;;; will choke on the check.
472 ;;;
473 ;;; The generation of the type checks is delayed until all the type
474 ;;; check decisions have been made because the generation of the type
475 ;;; checks creates new nodes whose derived types aren't always updated
476 ;;; which may lead to inappropriate template choices due to the
477 ;;; modification of argument types.
478 (defun generate-type-checks (component)
479   (collect ((conts))
480     (do-blocks (block component)
481       (when (block-type-check block)
482         (do-nodes (node cont block)
483           (let ((type-check (continuation-type-check cont)))
484             (unless (member type-check '(nil :error :deleted))
485               (let ((atype (continuation-asserted-type cont)))
486                 (do-uses (use cont)
487                   (unless (values-types-intersect (node-derived-type use)
488                                                   atype)
489                     (mark-error-continuation cont)
490                     (unless (policy node (= inhibit-warnings 3))
491                       (do-type-warning use))))))
492             (when (and (eq type-check t)
493                        (not *byte-compiling*))
494               (cond ((probable-type-check-p cont)
495                      (conts cont))
496                     (t
497                      (setf (continuation-%type-check cont) :no-check))))))
498         (setf (block-type-check block) nil)))
499     (dolist (cont (conts))
500       (multiple-value-bind (check types) (continuation-check-types cont)
501         (ecase check
502           (:simple)
503           (:hairy
504            (convert-type-check cont types))
505           (:too-hairy
506            (let* ((context (continuation-dest cont))
507                   (*compiler-error-context* context))
508              (when (policy context (>= safety inhibit-warnings))
509                (compiler-note
510                 "type assertion too complex to check:~% ~S."
511                 (type-specifier (continuation-asserted-type cont)))))
512            (setf (continuation-%type-check cont) :deleted))))))
513   (values))