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.
6 ;;;; This software is part of the SBCL system. See the README file for
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.
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.)
25 ;;; We special-case NULL, since it does have a source tranform and is
26 ;;; interesting to us.
27 (defun fun-guessed-cost (name)
28 (declare (symbol name
))
29 (let ((info (info :function
:info name
))
30 (call-cost (template-cost (template-or-lose 'call-named
))))
32 (let ((templates (fun-info-templates info
)))
34 (template-cost (first templates
))
36 (null (template-cost (template-or-lose 'if-eq
)))
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 (when (eq type
*universal-type
*)
48 (when (eq type
*empty-type
*)
50 (let ((check (type-check-template type
)))
53 (let ((found (cdr (assoc type
*backend-type-predicates
*
56 (+ (fun-guessed-cost found
) (fun-guessed-cost 'eq
))
60 (reduce #'+ (compound-type-types type
) :key
'type-test-cost
))
62 (* (member-type-size type
)
63 (fun-guessed-cost 'eq
)))
65 (* (if (numeric-type-complexp type
) 2 1)
67 (if (csubtypep type
(specifier-type 'fixnum
)) 'fixnump
'numberp
))
69 (if (numeric-type-low type
) 1 0)
70 (if (numeric-type-high type
) 1 0))))
72 (+ (type-test-cost (specifier-type 'cons
))
73 (fun-guessed-cost 'car
)
74 (type-test-cost (cons-type-car-type type
))
75 (fun-guessed-cost 'cdr
)
76 (type-test-cost (cons-type-cdr-type type
))))
78 (fun-guessed-cost 'typep
)))))
80 (defun weaken-integer-type (type &key range-only
)
81 ;; FIXME: Our canonicalization isn't quite ideal for this. We get
84 ;; (OR (AND (SATISFIES FOO) (INTEGER -100 -50))
85 ;; (AND (SATISFIES FOO) (INTEGER 100 200)))
87 ;; here, and weakening that into
89 ;; (AND (SATISFIES FOO) (INTEGER -100 200))
91 ;; is too much work to do here ... but if we canonicalized things
92 ;; differently, we could get it for free with trivial changes here.
93 (labels ((weaken-integer-type-part (type base
)
94 (cond ((intersection-type-p type
)
95 (let ((new (specifier-type base
)))
96 (dolist (part (intersection-type-types type
))
99 (not (unknown-type-p part
)))
100 (setf new
(type-intersection
101 new
(weaken-integer-type-part part t
)))))
104 (let ((low t
) (high t
) (rest *empty-type
*))
105 (flet ((maximize (bound)
107 (setf high
(if (eq t high
)
113 (setf low
(if (eq t low
)
117 (dolist (part (union-type-types type
))
118 (let ((weak (weaken-integer-type-part part t
)))
119 (cond ((numeric-type-p weak
)
120 (minimize (numeric-type-low weak
))
121 (maximize (numeric-type-high weak
)))
123 (setf rest
(type-union rest weak
)))))))
128 `(integer ,(or low
'*) ,(or high
'*)))))))
131 (weaken-integer-type-part type
'integer
)))
134 (weaken-type :hash-bits
7 :hash-function
#'type-hash-value
)
136 (declare (type ctype type
))
137 (cond ((named-type-p type
)
139 ((csubtypep type
(specifier-type 'integer
))
140 ;; Simple range checks are not that expensive, and we *don't*
141 ;; want to accidentally lose eg. array bounds checks due to
142 ;; weakening, so for integer types we simply collapse all
144 (weaken-integer-type type
))
146 (let ((min-cost (type-test-cost type
))
149 (dolist (x *backend-type-predicates
*)
150 (let* ((stype (car x
))
151 (samep (type= stype type
)))
153 (and (csubtypep type stype
)
154 (not (union-type-p stype
))))
155 (let ((stype-cost (type-test-cost stype
)))
156 (when (or (< stype-cost min-cost
)
158 ;; If the supertype is equal in cost to the type, we
159 ;; prefer the supertype. This produces a closer
160 ;; approximation of the right thing in the presence of
164 min-cost stype-cost
))))))
165 ;; This used to return the *UNIVERSAL-TYPE* if no supertype was found,
166 ;; but that's too liberal: it's far too easy for the user to create
167 ;; a union type (which are excluded above), and then trick the compiler
168 ;; into trusting the union type... and finally ending up corrupting the
169 ;; heap once a bad object sneaks past the missing type check.
174 (defun weaken-values-type (type)
175 (declare (type ctype type
))
176 (cond ((eq type
*wild-type
*) type
)
177 ((not (values-type-p type
))
180 (make-values-type :required
(mapcar #'weaken-type
181 (values-type-required type
))
182 :optional
(mapcar #'weaken-type
183 (values-type-optional type
))
184 :rest
(acond ((values-type-rest type
)
185 (weaken-type it
)))))))
187 ;;;; checking strategy determination
189 ;;; Return the type we should test for when we really want to check
190 ;;; for TYPE. If type checking policy is "fast", then we return a
191 ;;; weaker type if it is easier to check. First we try the defined
192 ;;; type weakenings, then look for any predicate that is cheaper.
193 (defun maybe-weaken-check (type policy
)
194 (declare (type ctype type
))
195 (ecase (policy policy type-check
)
197 (2 (weaken-values-type type
))
200 ;;; This is like VALUES-TYPES, only we mash any complex function types
202 (defun no-fun-values-types (type)
203 (declare (type ctype type
))
204 (multiple-value-bind (res count
) (values-types type
)
205 (values (mapcar (lambda (type)
206 (if (fun-type-p type
)
207 (specifier-type 'function
)
212 ;;; Switch to disable check complementing, for evaluation.
213 (defvar *complement-type-checks
* t
)
215 ;;; LVAR is an lvar we are doing a type check on and TYPES is a list
216 ;;; of types that we are checking its values against. If we have
217 ;;; proven that LVAR generates a fixed number of values, then for each
218 ;;; value, we check whether it is cheaper to then difference between
219 ;;; the proven type and the corresponding type in TYPES. If so, we opt
220 ;;; for a :HAIRY check with that test negated. Otherwise, we try to do
221 ;;; a simple test, and if that is impossible, we do a hairy test with
222 ;;; non-negated types. If true, FORCE-HAIRY forces a hairy type check.
223 (defun maybe-negate-check (lvar types original-types force-hairy n-required
)
224 (declare (type lvar lvar
) (list types original-types
))
225 (let ((ptypes (values-type-out (lvar-derived-type lvar
) (length types
))))
226 (multiple-value-bind (hairy-res simple-res
)
227 (loop for p in ptypes
229 and a in original-types
231 for cc
= (if (>= i n-required
)
232 (type-union c
(specifier-type 'null
))
234 for diff
= (type-difference p cc
)
235 collect
(if (and diff
236 (< (type-test-cost diff
)
238 *complement-type-checks
*)
242 collect cc into simple-res
243 finally
(return (values hairy-res simple-res
)))
244 (cond ((or force-hairy
(find-if #'first hairy-res
))
245 (values :hairy hairy-res
))
246 ((every #'type-check-template simple-res
)
247 (values :simple simple-res
))
249 (values :hairy hairy-res
))))))
251 ;;; Determines whether CAST's assertion is:
252 ;;; -- checkable by the back end (:SIMPLE), or
253 ;;; -- not checkable by the back end, but checkable via an explicit
254 ;;; test in type check conversion (:HAIRY), or
255 ;;; -- not reasonably checkable at all (:TOO-HAIRY).
257 ;;; We may check only fixed number of values; in any case the number
258 ;;; of generated values is trusted. If we know the number of produced
259 ;;; values, all of them are checked; otherwise if we know the number
260 ;;; of consumed -- only they are checked; otherwise the check is not
263 ;;; A type is simply checkable if all the type assertions have a
264 ;;; TYPE-CHECK-TEMPLATE. In this :SIMPLE case, the second value is a
265 ;;; list of the type restrictions specified for the leading positional
270 ;;; We force a check to be hairy even when there are fixed values
271 ;;; if we are in a context where we may be forced to use the
272 ;;; unknown values convention anyway. This is because IR2tran can't
273 ;;; generate type checks for unknown values lvars but people could
274 ;;; still be depending on the check being done. We only care about
275 ;;; EXIT and RETURN (not MV-COMBINATION) since these are the only
276 ;;; contexts where the ultimate values receiver
278 ;;; In the :HAIRY case, the second value is a list of triples of
280 ;;; (NOT-P TYPE ORIGINAL-TYPE)
282 ;;; If true, the NOT-P flag indicates a test that the corresponding
283 ;;; value is *not* of the specified TYPE. ORIGINAL-TYPE is the type
284 ;;; asserted on this value in the lvar, for use in error
285 ;;; messages. When NOT-P is true, this will be different from TYPE.
287 ;;; This allows us to take what has been proven about CAST's argument
288 ;;; type into consideration. If it is cheaper to test for the
289 ;;; difference between the derived type and the asserted type, then we
290 ;;; check for the negation of this type instead.
291 (defun cast-check-types (cast force-hairy
)
292 (declare (type cast cast
))
293 (let* ((ctype (coerce-to-values (cast-type-to-check cast
)))
294 (atype (coerce-to-values (cast-asserted-type cast
)))
295 (dtype (node-derived-type cast
))
296 (value (cast-value cast
))
297 (lvar (node-lvar cast
))
298 (dest (and lvar
(lvar-dest lvar
)))
299 (n-consumed (cond ((not lvar
)
301 ((lvar-single-value-p lvar
)
303 ((and (mv-combination-p dest
)
304 (eq (mv-combination-kind dest
) :local
))
305 (let ((fun-ref (lvar-use (mv-combination-fun dest
))))
306 (length (lambda-vars (ref-leaf fun-ref
)))))))
307 (n-required (length (values-type-required dtype
))))
308 (aver (not (eq ctype
*wild-type
*)))
309 (cond ((and (null (values-type-optional dtype
))
310 (not (values-type-rest dtype
)))
311 ;; we [almost] know how many values are produced
312 (maybe-negate-check value
313 (values-type-out ctype n-required
)
314 (values-type-out atype n-required
)
315 ;; backend checks only consumed values
316 (not (eql n-required n-consumed
))
318 ((lvar-single-value-p lvar
)
319 ;; exactly one value is consumed
320 (principal-lvar-single-valuify lvar
)
321 (flet ((get-type (type)
322 (acond ((args-type-required type
)
324 ((args-type-optional type
)
326 (t (bug "type ~S is too hairy" type
)))))
327 (multiple-value-bind (ctype atype
)
328 (values (get-type ctype
) (get-type atype
))
329 (maybe-negate-check value
330 (list ctype
) (list atype
)
333 ((and (mv-combination-p dest
)
334 (eq (mv-combination-kind dest
) :local
))
335 ;; we know the number of consumed values
336 (maybe-negate-check value
337 (adjust-list (values-type-types ctype
)
340 (adjust-list (values-type-types atype
)
346 (values :too-hairy nil
)))))
348 ;;; Return T is the cast appears to be from the declaration of the callee,
349 ;;; and should be checked externally -- that is, by the callee and not the caller.
350 (defun cast-externally-checkable-p (cast)
351 (declare (type cast cast
))
352 (let* ((lvar (node-lvar cast
))
353 (dest (and lvar
(lvar-dest lvar
))))
354 (and (combination-p dest
)
355 ;; The theory is that the type assertion is from a declaration on the
356 ;; callee, so the callee should be able to do the check. We want to
357 ;; let the callee do the check, because it is possible that by the
358 ;; time of call that declaration will be changed and we do not want
359 ;; to make people recompile all calls to a function when they were
360 ;; originally compiled with a bad declaration.
362 ;; ALMOST-IMMEDIATELY-USED-P ensures that we don't delegate casts
363 ;; that occur before nodes that can cause observable side effects --
364 ;; most commonly other non-external casts: so the order in which
365 ;; possible type errors are signalled matches with the evaluation
368 ;; FIXME: We should let more cases be handled by the callee then we
369 ;; currently do, see: https://bugs.launchpad.net/sbcl/+bug/309104
370 ;; This is not fixable quite here, though, because flow-analysis has
371 ;; deleted the LVAR of the cast by the time we get here, so there is
372 ;; no destination. Perhaps we should mark cases inserted by
373 ;; ASSERT-CALL-TYPE explicitly, and delete those whose destination is
374 ;; deemed unreachable?
375 (almost-immediately-used-p lvar cast
)
376 (values (values-subtypep (lvar-externally-checkable-type lvar
)
377 (cast-type-to-check cast
))))))
379 ;;; Return true if CAST's value is an lvar whose type the back end is
380 ;;; likely to be able to check (see GENERATE-TYPE-CHECKS). Since we
381 ;;; don't know what template the back end is going to choose to
382 ;;; implement the continuation's DEST, we use a heuristic.
384 ;;; We always return T unless nobody uses the value (the backend
385 ;;; cannot check unused LVAR chains).
387 ;;; The logic used to be more complex, but most of the cases that used
388 ;;; to be checked here are now dealt with differently . FIXME: but
389 ;;; here's one we used to do, don't anymore, but could still benefit
390 ;;; from, if we reimplemented it (elsewhere):
392 ;;; -- If the lvar is an argument to a known function that has
393 ;;; no IR2-CONVERT method or :FAST-SAFE templates that are
394 ;;; compatible with the call's type: return NIL.
396 ;;; The code used to look like something like this:
399 ;;; (let ((info (basic-combination-fun-info dest)))
400 ;;; (if (fun-info-ir2-convert info)
402 ;;; (dolist (template (fun-info-templates info) nil)
403 ;;; (when (eq (template-ltn-policy template)
405 ;;; (multiple-value-bind (val win)
406 ;;; (valid-fun-use dest (template-type template))
407 ;;; (when (or val (not win)) (return t)))))))))))))
409 ;;; ADP says: It is still interesting. When we have a :SAFE template
410 ;;; and the type assertion is derived from the destination function
411 ;;; type, the check is unneccessary. We cannot return NIL here (the
412 ;;; whole function has changed its meaning, and here NIL *forces*
413 ;;; hairy check), but the functionality is interesting.
414 (defun probable-type-check-p (cast)
415 (declare (type cast cast
))
416 (let* ((lvar (node-lvar cast
))
417 (dest (and lvar
(lvar-dest lvar
))))
418 (cond ((not dest
) nil
)
421 ;; Type specifiers handled by the general-purpose MAKE-TYPE-CHECK-FORM are often
422 ;; trivial enough to have an internal error number assigned to them that can be
423 ;; used in lieu of OBJECT-NOT-TYPE-ERROR. On x86-64 this saves 16 bytes: 1 word
424 ;; for the symbol in the function's constant area, a MOV instruction to load it,
425 ;; and an sc-offset in the error trap.
426 (defglobal **type-spec-interr-symbols
**
428 ;; read-time-eval so that during cold-init we can recreate the
429 ;; table using the target's sxhash function, but without relying
430 ;; on readiness of the type system for parsing/unparsing specifiers.
433 (cons (type-specifier (specifier-type (car entry
)))
435 (remove-if #'stringp sb
!c
:+backend-internal-errors
+
437 ;; This is effectively a compact read-only binned hashtable.
438 (hashtable (make-array (logior (length entries
) 1)
439 :initial-element nil
)))
440 ;; Older architectures don't have a VOP that can emit an arbitrary
441 ;; primitive trap (see "compiler/generic/type-error" - and fix that)
442 #!-
(or alpha hppa mips
)
445 (let* ((canon-type (car entry
))
446 (bucket (mod (sxhash canon-type
) (length hashtable
))))
447 (push entry
(svref hashtable bucket
))))
450 (defun %interr-symbol-for-type-spec
(spec)
451 (let ((table **type-spec-interr-symbols
**))
452 (cdr (assoc spec
(svref table
(rem (sxhash spec
) (length table
)))
454 #+nil
; some meta-analysis to decide what types should be in "generic/interr"
456 (defvar *checkgen-used-types
* (make-hash-table :test
'equal
))
457 (defun interr-symbol-for-type-spec (spec)
458 (let ((answer (%interr-symbol-for-type-spec spec
))
459 (meta (gethash spec
*checkgen-used-types
*)))
460 ;; spec -> (count . primitive-p)
463 (setf (gethash spec
*checkgen-used-types
*) (cons 1 answer
)))
466 ;;; Return a lambda form that we can convert to do a hairy type check
467 ;;; of the specified TYPES. TYPES is a list of the format returned by
468 ;;; LVAR-CHECK-TYPES in the :HAIRY case.
470 ;;; Note that we don't attempt to check for required values being
471 ;;; unsupplied. Such checking is impossible to efficiently do at the
472 ;;; source level because our fixed-values conventions are optimized
473 ;;; for the common MV-BIND case.
474 (defun make-type-check-form (types)
475 (let ((temps (make-gensym-list (length types
))))
476 `(multiple-value-bind ,temps
478 ,@(mapcar (lambda (temp type
)
480 (let ((*unparse-fun-type-simplify
* t
))
481 (type-specifier (second type
))))
482 (test (if (first type
) `(not ,spec
) spec
))
483 (external-spec (type-specifier (third type
)))
485 (%interr-symbol-for-type-spec external-spec
)))
486 `(unless (typep ,temp
',test
)
488 `(%type-check-error
/c
,temp
',interr-symbol
)
489 `(%type-check-error
,temp
',external-spec
)))))
494 ;;; Splice in explicit type check code immediately before CAST. This
495 ;;; code receives the value(s) that were being passed to CAST-VALUE,
496 ;;; checks the type(s) of the value(s), then passes them further.
497 (defun convert-type-check (cast types
)
498 (declare (type cast cast
) (type list types
))
499 (let ((value (cast-value cast
))
500 (length (length types
)))
501 (filter-lvar value
(make-type-check-form types
))
502 (reoptimize-lvar (cast-value cast
))
503 (setf (cast-type-to-check cast
) *wild-type
*)
504 (setf (cast-%type-check cast
) nil
)
505 (let* ((atype (cast-asserted-type cast
))
506 (atype (cond ((not (values-type-p atype
))
509 (single-value-type atype
))
512 :required
(values-type-out atype length
)))))
513 (dtype (node-derived-type cast
))
514 (dtype (make-values-type
515 :required
(values-type-out dtype length
))))
516 (setf (cast-asserted-type cast
) atype
)
517 (setf (node-derived-type cast
) dtype
)))
521 ;;; Check all possible arguments of CAST and emit type warnings for
522 ;;; those with type errors. If the value of USE is being used for a
523 ;;; variable binding, we figure out which one for source context. If
524 ;;; the value is a constant, we print it specially.
525 (defun cast-check-uses (cast)
526 (declare (type cast cast
))
527 (let* ((lvar (node-lvar cast
))
528 (dest (and lvar
(lvar-dest lvar
)))
529 (value (cast-value cast
))
530 (atype (cast-asserted-type cast
))
531 (condition 'type-warning
)
534 (let ((dtype (node-derived-type use
)))
535 (if (values-types-equal-or-intersect dtype atype
)
536 (setf condition
'type-style-warning
)
537 (push use not-ok-uses
))))
538 (dolist (use (nreverse not-ok-uses
))
539 (let* ((*compiler-error-context
* use
)
540 (dtype (node-derived-type use
))
541 (atype-spec (type-specifier atype
))
542 (what (when (and (combination-p dest
)
543 (eq (combination-kind dest
) :local
))
544 (let ((lambda (combination-lambda dest
))
545 (pos (position-or-lose
546 lvar
(combination-args dest
))))
547 (format nil
"~:[A possible~;The~] binding of ~S"
548 (and (lvar-has-single-use-p lvar
)
549 (eq (functional-kind lambda
) :let
))
550 (leaf-source-name (elt (lambda-vars lambda
)
552 (cond ((and (ref-p use
) (constant-p (ref-leaf use
)))
555 "~:[This~;~:*~A~] is not a ~<~%~9T~:;~S:~>~% ~S"
557 (list what atype-spec
558 (constant-value (ref-leaf use
)))))
562 "~:[Result~;~:*~A~] is a ~S, ~<~%~9T~:;not a ~S.~>"
564 (list what
(type-specifier dtype
) atype-spec
)))))))
567 ;;; Loop over all blocks in COMPONENT that have TYPE-CHECK set,
568 ;;; looking for CASTs with TYPE-CHECK T. We do two mostly unrelated
569 ;;; things: detect compile-time type errors and determine if and how
570 ;;; to do run-time type checks.
572 ;;; If there is a compile-time type error, then we mark the CAST and
573 ;;; emit a warning if appropriate. This part loops over all the uses
574 ;;; of the continuation, since after we convert the check, the
575 ;;; :DELETED kind will inhibit warnings about the types of other uses.
577 ;;; If the cast is too complex to be checked by the back end, or is
578 ;;; better checked with explicit code, then convert to an explicit
579 ;;; test. Assertions that can checked by the back end are passed
580 ;;; through. Assertions that can't be tested are flamed about and
581 ;;; marked as not needing to be checked.
583 ;;; If we determine that a type check won't be done, then we set
584 ;;; TYPE-CHECK to :NO-CHECK. In the non-hairy cases, this is just to
585 ;;; prevent us from wasting time coming to the same conclusion again
586 ;;; on a later iteration. In the hairy case, we must indicate to LTN
587 ;;; that it must choose a safe implementation, since IR2 conversion
588 ;;; will choke on the check.
590 ;;; The generation of the type checks is delayed until all the type
591 ;;; check decisions have been made because the generation of the type
592 ;;; checks creates new nodes whose derived types aren't always updated
593 ;;; which may lead to inappropriate template choices due to the
594 ;;; modification of argument types.
595 (defun generate-type-checks (component)
597 (do-blocks (block component
)
598 (when (block-type-check block
)
599 ;; CAST-EXTERNALLY-CHECKABLE-P wants the backward pass
600 (do-nodes-backwards (node nil block
)
601 (when (and (cast-p node
)
602 (cast-type-check node
))
603 (cast-check-uses node
)
604 (cond ((cast-externally-checkable-p node
)
605 (setf (cast-%type-check node
) :external
))
607 ;; it is possible that NODE was marked :EXTERNAL by
609 (setf (cast-%type-check node
) t
)
610 (casts (cons node
(not (probable-type-check-p node
))))))))
611 (setf (block-type-check block
) nil
)))
612 (dolist (cast (casts))
613 (destructuring-bind (cast . force-hairy
) cast
614 (multiple-value-bind (check types
)
615 (cast-check-types cast force-hairy
)
619 (convert-type-check cast types
))
621 (let ((*compiler-error-context
* cast
))
622 (when (policy cast
(>= safety inhibit-warnings
))
624 "type assertion too complex to check:~% ~S."
625 (type-specifier (coerce-to-values (cast-asserted-type cast
))))))
626 (setf (cast-type-to-check cast
) *wild-type
*)
627 (setf (cast-%type-check cast
) nil
)))))))