8d04f9405a4bacb9cf0b2f2788e1e2f28e172774
[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 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))))
31     (if info
32         (let ((templates (fun-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 (when (eq type *universal-type*)
47         0)
48       (when (eq type *empty-type*)
49         0)
50       (let ((check (type-check-template type)))
51         (if check
52             (template-cost check)
53             (let ((found (cdr (assoc type *backend-type-predicates*
54                                      :test #'type=))))
55               (if found
56                   (+ (fun-guessed-cost found) (fun-guessed-cost 'eq))
57                   nil))))
58       (typecase type
59         (compound-type
60          (reduce #'+ (compound-type-types type) :key 'type-test-cost))
61         (member-type
62          (* (length (member-type-members type))
63             (fun-guessed-cost 'eq)))
64         (numeric-type
65          (* (if (numeric-type-complexp type) 2 1)
66             (fun-guessed-cost
67              (if (csubtypep type (specifier-type 'fixnum)) 'fixnump 'numberp))
68             (+ 1
69                (if (numeric-type-low type) 1 0)
70                (if (numeric-type-high type) 1 0))))
71         (cons-type
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))))
77         (t
78          (fun-guessed-cost 'typep)))))
79
80 (defun-cached
81     (weaken-type :hash-bits 8
82                  :hash-function (lambda (x)
83                                   (logand (type-hash-value x) #xFF)))
84     ((type eq))
85   (declare (type ctype type))
86   (let ((min-cost (type-test-cost type))
87         (min-type type)
88         (found-super nil))
89     (dolist (x *backend-type-predicates*)
90       (let ((stype (car x)))
91         (when (and (csubtypep type stype)
92                    (not (union-type-p stype)))
93           (let ((stype-cost (type-test-cost stype)))
94             (when (or (< stype-cost min-cost)
95                       (type= stype type))
96               ;; If the supertype is equal in cost to the type, we
97               ;; prefer the supertype. This produces a closer
98               ;; approximation of the right thing in the presence of
99               ;; poor cost info.
100               (setq found-super t
101                     min-type stype
102                     min-cost stype-cost))))))
103     (if found-super
104         min-type
105         *universal-type*)))
106
107 (defun weaken-values-type (type)
108   (declare (type ctype type))
109   (cond ((eq type *wild-type*) type)
110         ((not (values-type-p type))
111          (weaken-type type))
112         (t
113          (make-values-type :required (mapcar #'weaken-type
114                                              (values-type-required type))
115                            :optional (mapcar #'weaken-type
116                                              (values-type-optional type))
117                            :rest (acond ((values-type-rest type)
118                                          (weaken-type it)))))))
119 \f
120 ;;;; checking strategy determination
121
122 ;;; Return the type we should test for when we really want to check
123 ;;; for TYPE. If type checking policy is "fast", then we return a
124 ;;; weaker type if it is easier to check. First we try the defined
125 ;;; type weakenings, then look for any predicate that is cheaper.
126 (defun maybe-weaken-check (type policy)
127   (declare (type ctype type))
128   (ecase (policy policy type-check)
129     (0 *wild-type*)
130     (2 (weaken-values-type type))
131     (3 type)))
132
133 ;;; This is like VALUES-TYPES, only we mash any complex function types
134 ;;; to FUNCTION.
135 (defun no-fun-values-types (type)
136   (declare (type ctype type))
137   (multiple-value-bind (res count) (values-types type)
138     (values (mapcar (lambda (type)
139                       (if (fun-type-p type)
140                           (specifier-type 'function)
141                           type))
142                     res)
143             count)))
144
145 ;;; Switch to disable check complementing, for evaluation.
146 (defvar *complement-type-checks* t)
147
148 ;;; LVAR is an lvar we are doing a type check on and TYPES is a list
149 ;;; of types that we are checking its values against. If we have
150 ;;; proven that LVAR generates a fixed number of values, then for each
151 ;;; value, we check whether it is cheaper to then difference between
152 ;;; the proven type and the corresponding type in TYPES. If so, we opt
153 ;;; for a :HAIRY check with that test negated. Otherwise, we try to do
154 ;;; a simple test, and if that is impossible, we do a hairy test with
155 ;;; non-negated types. If true, FORCE-HAIRY forces a hairy type check.
156 ;;;
157 ;;; When doing a non-negated check, we call MAYBE-WEAKEN-CHECK to
158 ;;; weaken the test to a convenient supertype (conditional on policy.)
159 ;;; If SPEED is 3, or DEBUG-INFO is not particularly important (DEBUG
160 ;;; <= 1), then we allow weakened checks to be simple, resulting in
161 ;;; less informative error messages, but saving space and possibly
162 ;;; time.
163 ;;;
164 ;;; FIXME: I don't quite understand this, but it looks as though
165 ;;; that means type checks are weakened when SPEED=3 regardless of
166 ;;; the SAFETY level, which is not the right thing to do.
167 (defun maybe-negate-check (lvar types original-types force-hairy n-required)
168   (declare (type lvar lvar) (list types original-types))
169   (let ((ptypes (values-type-out (lvar-derived-type lvar) (length types))))
170     (multiple-value-bind (hairy-res simple-res)
171         (loop for p in ptypes
172               and c in types
173               and a in original-types
174               and i from 0
175               for cc = (if (>= i n-required)
176                            (type-union c (specifier-type 'null))
177                            c)
178               for diff = (type-difference p cc)
179               collect (if (and diff
180                                (< (type-test-cost diff)
181                                   (type-test-cost cc))
182                                *complement-type-checks*)
183                           (list t diff a)
184                           (list nil cc a))
185               into hairy-res
186               collect cc into simple-res
187               finally (return (values hairy-res simple-res)))
188       (cond ((or force-hairy (find-if #'first hairy-res))
189              (values :hairy hairy-res))
190             ((every #'type-check-template simple-res)
191              (values :simple simple-res))
192             (t
193              (values :hairy hairy-res))))))
194
195 ;;; Determines whether CAST's assertion is:
196 ;;;  -- checkable by the back end (:SIMPLE), or
197 ;;;  -- not checkable by the back end, but checkable via an explicit 
198 ;;;     test in type check conversion (:HAIRY), or
199 ;;;  -- not reasonably checkable at all (:TOO-HAIRY).
200 ;;;
201 ;;; We may check only fixed number of values; in any case the number
202 ;;; of generated values is trusted. If we know the number of produced
203 ;;; values, all of them are checked; otherwise if we know the number
204 ;;; of consumed -- only they are checked; otherwise the check is not
205 ;;; performed.
206 ;;;
207 ;;; A type is simply checkable if all the type assertions have a
208 ;;; TYPE-CHECK-TEMPLATE. In this :SIMPLE case, the second value is a
209 ;;; list of the type restrictions specified for the leading positional
210 ;;; values.
211 ;;;
212 ;;; Old comment:
213 ;;;
214 ;;;    We force a check to be hairy even when there are fixed values
215 ;;;    if we are in a context where we may be forced to use the
216 ;;;    unknown values convention anyway. This is because IR2tran can't
217 ;;;    generate type checks for unknown values lvars but people could
218 ;;;    still be depending on the check being done. We only care about
219 ;;;    EXIT and RETURN (not MV-COMBINATION) since these are the only
220 ;;;    contexts where the ultimate values receiver
221 ;;;
222 ;;; In the :HAIRY case, the second value is a list of triples of
223 ;;; the form:
224 ;;;    (NOT-P TYPE ORIGINAL-TYPE)
225 ;;;
226 ;;; If true, the NOT-P flag indicates a test that the corresponding
227 ;;; value is *not* of the specified TYPE. ORIGINAL-TYPE is the type
228 ;;; asserted on this value in the lvar, for use in error
229 ;;; messages. When NOT-P is true, this will be different from TYPE.
230 ;;;
231 ;;; This allows us to take what has been proven about CAST's argument
232 ;;; type into consideration. If it is cheaper to test for the
233 ;;; difference between the derived type and the asserted type, then we
234 ;;; check for the negation of this type instead.
235 (defun cast-check-types (cast force-hairy)
236   (declare (type cast cast))
237   (let* ((ctype (coerce-to-values (cast-type-to-check cast)))
238          (atype (coerce-to-values (cast-asserted-type cast)))
239          (dtype (node-derived-type cast))
240          (value (cast-value cast))
241          (lvar (node-lvar cast))
242          (dest (and lvar (lvar-dest lvar)))
243          (n-consumed (cond ((not lvar)
244                             nil)
245                            ((lvar-single-value-p lvar)
246                             1)
247                            ((and (mv-combination-p dest)
248                                  (eq (mv-combination-kind dest) :local))
249                             (let ((fun-ref (lvar-use (mv-combination-fun dest))))
250                               (length (lambda-vars (ref-leaf fun-ref)))))))
251          (n-required (length (values-type-required dtype))))
252     (aver (not (eq ctype *wild-type*)))
253     (cond ((and (null (values-type-optional dtype))
254                 (not (values-type-rest dtype)))
255            ;; we [almost] know how many values are produced
256            (maybe-negate-check value
257                                (values-type-out ctype n-required)
258                                (values-type-out atype n-required)
259                                ;; backend checks only consumed values
260                                (not (eql n-required n-consumed))
261                                n-required))
262           ((lvar-single-value-p lvar)
263            ;; exactly one value is consumed
264            (principal-lvar-single-valuify lvar)
265            (let ((creq (car (args-type-required ctype))))
266              (multiple-value-setq (ctype atype)
267                (if creq
268                    (values creq (car (args-type-required atype)))
269                    (values (car (args-type-optional ctype))
270                            (car (args-type-optional atype)))))
271              (maybe-negate-check value
272                                  (list ctype) (list atype)
273                                  force-hairy
274                                  n-required)))
275           ((and (mv-combination-p dest)
276                 (eq (mv-combination-kind dest) :local))
277            ;; we know the number of consumed values
278            (maybe-negate-check value
279                                (adjust-list (values-type-types ctype)
280                                             n-consumed
281                                             *universal-type*)
282                                (adjust-list (values-type-types atype)
283                                             n-consumed
284                                             *universal-type*)
285                                force-hairy
286                                n-required))
287           (t
288            (values :too-hairy nil)))))
289
290 ;;; Do we want to do a type check?
291 (defun cast-externally-checkable-p (cast)
292   (declare (type cast cast))
293   (let* ((lvar (node-lvar cast))
294          (dest (and lvar (lvar-dest lvar))))
295     (and (combination-p dest)
296          ;; The theory is that the type assertion is from a
297          ;; declaration in (or on) the callee, so the callee should be
298          ;; able to do the check. We want to let the callee do the
299          ;; check, because it is possible that by the time of call
300          ;; that declaration will be changed and we do not want to
301          ;; make people recompile all calls to a function when they
302          ;; were originally compiled with a bad declaration. (See also
303          ;; bug 35.)
304          (or (immediately-used-p lvar cast)
305              (binding* ((ctran (node-next cast) :exit-if-null)
306                         (next (ctran-next ctran)))
307                (and (cast-p next)
308                     (eq (node-dest next) dest)
309                     (eq (cast-type-check next) :external))))
310          (values-subtypep (lvar-externally-checkable-type lvar)
311                           (cast-type-to-check cast)))))
312
313 ;;; Return true if CAST's value is an lvar whose type the back end is
314 ;;; likely to want to check. Since we don't know what template the
315 ;;; back end is going to choose to implement the continuation's DEST,
316 ;;; we use a heuristic. We always return T unless:
317 ;;;  -- nobody uses the value, or
318 ;;;  -- safety is totally unimportant, or
319 ;;;  -- the lvar is an argument to an unknown function, or
320 ;;;  -- the lvar is an argument to a known function that has
321 ;;;     no IR2-CONVERT method or :FAST-SAFE templates that are
322 ;;;     compatible with the call's type.
323 (defun probable-type-check-p (cast)
324   (declare (type cast cast))
325   (let* ((lvar (node-lvar cast))
326          (dest (and lvar (lvar-dest lvar))))
327     (cond ((not dest) nil)
328           (t t))
329     #+nil
330     (cond ((or (not dest)
331                (policy dest (zerop safety)))
332            nil)
333           ((basic-combination-p dest)
334            (let ((kind (basic-combination-kind dest)))
335              (cond
336                ((eq cont (basic-combination-fun dest)) t)
337                (t
338                 (ecase kind
339                   (:local t)
340                   (:full
341                    (and (combination-p dest)
342                         (not (values-subtypep ; explicit THE
343                               (continuation-externally-checkable-type cont)
344                               (continuation-type-to-check cont)))))
345                   ;; :ERROR means that we have an invalid syntax of
346                   ;; the call and the callee will detect it before
347                   ;; thinking about types.
348                   (:error nil)
349                   (:known
350                    (let ((info (basic-combination-fun-info dest)))
351                      (if (fun-info-ir2-convert info)
352                          t
353                          (dolist (template (fun-info-templates info) nil)
354                            (when (eq (template-ltn-policy template)
355                                      :fast-safe)
356                              (multiple-value-bind (val win)
357                                  (valid-fun-use dest (template-type template))
358                                (when (or val (not win)) (return t)))))))))))))
359           (t t))))
360
361 ;;; Return a lambda form that we can convert to do a hairy type check
362 ;;; of the specified TYPES. TYPES is a list of the format returned by
363 ;;; LVAR-CHECK-TYPES in the :HAIRY case.
364 ;;;
365 ;;; Note that we don't attempt to check for required values being
366 ;;; unsupplied. Such checking is impossible to efficiently do at the
367 ;;; source level because our fixed-values conventions are optimized
368 ;;; for the common MV-BIND case.
369 (defun make-type-check-form (types)
370   (let ((temps (make-gensym-list (length types))))
371     `(multiple-value-bind ,temps
372          'dummy
373        ,@(mapcar (lambda (temp type)
374                    (let* ((spec
375                            (let ((*unparse-fun-type-simplify* t))
376                              (type-specifier (second type))))
377                           (test (if (first type) `(not ,spec) spec)))
378                      `(unless (typep ,temp ',test)
379                         (%type-check-error
380                          ,temp
381                          ',(type-specifier (third type))))))
382                  temps
383                  types)
384        (values ,@temps))))
385
386 ;;; Splice in explicit type check code immediately before CAST. This
387 ;;; code receives the value(s) that were being passed to CAST-VALUE,
388 ;;; checks the type(s) of the value(s), then passes them further.
389 (defun convert-type-check (cast types)
390   (declare (type cast cast) (type list types))
391   (let ((value (cast-value cast))
392         (length (length types)))
393     (filter-lvar value (make-type-check-form types))
394     (reoptimize-lvar (cast-value cast))
395     (setf (cast-type-to-check cast) *wild-type*)
396     (setf (cast-%type-check cast) nil)
397     (let* ((atype (cast-asserted-type cast))
398            (atype (cond ((not (values-type-p atype))
399                          atype)
400                         ((= length 1)
401                          (single-value-type atype))
402                         (t
403                          (make-values-type
404                           :required (values-type-out atype length)))))
405            (dtype (node-derived-type cast))
406            (dtype (make-values-type
407                    :required (values-type-out dtype length))))
408       (setf (cast-asserted-type cast) atype)
409       (setf (node-derived-type cast) dtype)))
410
411   (values))
412
413 ;;; Check all possible arguments of CAST and emit type warnings for
414 ;;; those with type errors. If the value of USE is being used for a
415 ;;; variable binding, we figure out which one for source context. If
416 ;;; the value is a constant, we print it specially.
417 (defun cast-check-uses (cast)
418   (declare (type cast cast))
419   (let* ((lvar (node-lvar cast))
420          (dest (and lvar (lvar-dest lvar)))
421          (value (cast-value cast))
422          (atype (cast-asserted-type cast)))
423     (do-uses (use value)
424       (let ((dtype (node-derived-type use)))
425         (unless (values-types-equal-or-intersect dtype atype)
426           (let* ((*compiler-error-context* use)
427                  (atype-spec (type-specifier atype))
428                  (what (when (and (combination-p dest)
429                                   (eq (combination-kind dest) :local))
430                          (let ((lambda (combination-lambda dest))
431                                (pos (position-or-lose
432                                      lvar (combination-args dest))))
433                            (format nil "~:[A possible~;The~] binding of ~S"
434                                    (and (lvar-has-single-use-p lvar)
435                                         (eq (functional-kind lambda) :let))
436                                    (leaf-source-name (elt (lambda-vars lambda)
437                                                           pos)))))))
438             (cond ((and (ref-p use) (constant-p (ref-leaf use)))
439                    (compiler-warn "~:[This~;~:*~A~] is not a ~<~%~9T~:;~S:~>~%  ~S"
440                                   what atype-spec (constant-value (ref-leaf use))))
441                   (t
442                    (compiler-warn
443                     "~:[Result~;~:*~A~] is a ~S, ~<~%~9T~:;not a ~S.~>"
444                     what (type-specifier dtype) atype-spec))))))))
445   (values))
446
447 ;;; Loop over all blocks in COMPONENT that have TYPE-CHECK set,
448 ;;; looking for CASTs with TYPE-CHECK T. We do two mostly unrelated
449 ;;; things: detect compile-time type errors and determine if and how
450 ;;; to do run-time type checks.
451 ;;;
452 ;;; If there is a compile-time type error, then we mark the CAST and
453 ;;; emit a warning if appropriate. This part loops over all the uses
454 ;;; of the continuation, since after we convert the check, the
455 ;;; :DELETED kind will inhibit warnings about the types of other uses.
456 ;;;
457 ;;; If the cast is too complex to be checked by the back end, or is
458 ;;; better checked with explicit code, then convert to an explicit
459 ;;; test. Assertions that can checked by the back end are passed
460 ;;; through. Assertions that can't be tested are flamed about and
461 ;;; marked as not needing to be checked.
462 ;;;
463 ;;; If we determine that a type check won't be done, then we set
464 ;;; TYPE-CHECK to :NO-CHECK. In the non-hairy cases, this is just to
465 ;;; prevent us from wasting time coming to the same conclusion again
466 ;;; on a later iteration. In the hairy case, we must indicate to LTN
467 ;;; that it must choose a safe implementation, since IR2 conversion
468 ;;; will choke on the check.
469 ;;;
470 ;;; The generation of the type checks is delayed until all the type
471 ;;; check decisions have been made because the generation of the type
472 ;;; checks creates new nodes whose derived types aren't always updated
473 ;;; which may lead to inappropriate template choices due to the
474 ;;; modification of argument types.
475 (defun generate-type-checks (component)
476   (collect ((casts))
477     (do-blocks (block component)
478       (when (block-type-check block)
479         ;; CAST-EXTERNALLY-CHECKABLE-P wants the backward pass
480         (do-nodes-backwards (node nil block)
481           (when (and (cast-p node)
482                      (cast-type-check node))
483             (cast-check-uses node)
484             (cond ((cast-externally-checkable-p node)
485                    (setf (cast-%type-check node) :external))
486                   (t
487                    ;; it is possible that NODE was marked :EXTERNAL by
488                    ;; the previous pass
489                    (setf (cast-%type-check node) t)
490                    (casts (cons node (not (probable-type-check-p node))))))))
491         (setf (block-type-check block) nil)))
492     (dolist (cast (casts))
493       (destructuring-bind (cast . force-hairy) cast
494         (multiple-value-bind (check types)
495             (cast-check-types cast force-hairy)
496           (ecase check
497             (:simple)
498             (:hairy
499              (convert-type-check cast types))
500             (:too-hairy
501              (let ((*compiler-error-context* cast))
502                (when (policy cast (>= safety inhibit-warnings))
503                  (compiler-notify
504                   "type assertion too complex to check:~% ~S."
505                   (type-specifier (coerce-to-values (cast-asserted-type cast))))))
506              (setf (cast-type-to-check cast) *wild-type*)
507              (setf (cast-%type-check cast) nil)))))))
508   (values))