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