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