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