5b44d181b6ccb99cd2b39c5ffd63a70a37dea3f4
[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         ((values-type-p type)
107          (make-values-type :required (mapcar #'weaken-type
108                                              (values-type-required type))
109                            :optional (mapcar #'weaken-type
110                                              (values-type-optional type))
111                            :rest (acond ((values-type-rest type)
112                                          (weaken-type it))
113                                         ((values-type-keyp type)
114                                          *universal-type*))))
115         (t (weaken-type type))))
116 \f
117 ;;;; checking strategy determination
118
119 (define-optimization-quality type-check
120     (cond ((= safety 0) 0)
121           ;; FIXME: It is duplicated in PROBABLE-TYPE-CHECK-P and in
122           ;; some other places.
123
124           ((and (<= speed safety)
125                 (<= space safety)
126                 (<= compilation-speed safety))
127            3)
128           (t 2))
129   ("no" "maybe" "fast" "full"))
130
131 ;;; Return the type we should test for when we really want to check
132 ;;; for TYPE. If type checking policy is "fast", then we return a
133 ;;; weaker type if it is easier to check. First we try the defined
134 ;;; type weakenings, then look for any predicate that is cheaper.
135 (defun maybe-weaken-check (type policy)
136   (declare (type ctype type))
137   (ecase (policy policy type-check)
138     (0 *wild-type*)
139     (2 (weaken-values-type type))
140     (3 type)))
141
142 ;;; This is like VALUES-TYPES, only we mash any complex function types
143 ;;; to FUNCTION.
144 (defun no-fun-values-types (type)
145   (declare (type ctype type))
146   (multiple-value-bind (res count) (values-types type)
147     (values (mapcar (lambda (type)
148                       (if (fun-type-p type)
149                           (specifier-type 'function)
150                           type))
151                     res)
152             count)))
153
154 ;;; Switch to disable check complementing, for evaluation.
155 (defvar *complement-type-checks* t)
156
157 ;;; CONT is a continuation we are doing a type check on and TYPES is a
158 ;;; list of types that we are checking its values against. If we have
159 ;;; proven that CONT generates a fixed number of values, then for each
160 ;;; value, we check whether it is cheaper to then difference between
161 ;;; the proven type and the corresponding type in TYPES. If so, we opt
162 ;;; for a :HAIRY check with that test negated. Otherwise, we try to do
163 ;;; a simple test, and if that is impossible, we do a hairy test with
164 ;;; non-negated types. If true, FORCE-HAIRY forces a hairy type check.
165 ;;;
166 ;;; When doing a non-negated check, we call MAYBE-WEAKEN-CHECK to
167 ;;; weaken the test to a convenient supertype (conditional on policy.)
168 ;;; If SPEED is 3, or DEBUG-INFO is not particularly important (DEBUG
169 ;;; <= 1), then we allow weakened checks to be simple, resulting in
170 ;;; less informative error messages, but saving space and possibly
171 ;;; time.
172 ;;;
173 ;;; FIXME: I don't quite understand this, but it looks as though
174 ;;; that means type checks are weakened when SPEED=3 regardless of
175 ;;; the SAFETY level, which is not the right thing to do.
176 (defun maybe-negate-check (cont types original-types force-hairy)
177   (declare (type continuation cont) (list types))
178   (multiple-value-bind (ptypes count)
179       (no-fun-values-types (continuation-proven-type cont))
180     (if (eq count :unknown)
181         (if (and (every #'type-check-template types) (not force-hairy))
182             (values :simple types)
183             (values :hairy (mapcar (lambda (x) (list nil x x)) types)))
184         (let ((res (mapcar (lambda (p c a)
185                              (let ((diff (type-difference p c)))
186                                (if (and diff
187                                         (< (type-test-cost diff)
188                                            (type-test-cost c))
189                                         *complement-type-checks*)
190                                    (list t diff a)
191                                    (list nil c a))))
192                            ptypes types original-types)))
193           (cond ((or force-hairy (find-if #'first res))
194                  (values :hairy res))
195                 ((every #'type-check-template types)
196                  (values :simple types))
197                 (t
198                  (values :hairy res)))))))
199
200 ;;; Determines whether CONT's assertion is:
201 ;;;  -- checkable by the back end (:SIMPLE), or
202 ;;;  -- not checkable by the back end, but checkable via an explicit 
203 ;;;     test in type check conversion (:HAIRY), or
204 ;;;  -- not reasonably checkable at all (:TOO-HAIRY).
205 ;;;
206 ;;; A type is checkable if it either represents a fixed number of
207 ;;; values (as determined by VALUES-TYPES), or it is the assertion for
208 ;;; an MV-BIND. A type is simply checkable if all the type assertions
209 ;;; have a TYPE-CHECK-TEMPLATE. In this :SIMPLE case, the second value
210 ;;; is a list of the type restrictions specified for the leading
211 ;;; positional values.
212 ;;;
213 ;;; We force a check to be hairy even when there are fixed values if
214 ;;; we are in a context where we may be forced to use the unknown
215 ;;; values convention anyway. This is because IR2tran can't generate
216 ;;; type checks for unknown values continuations but people could
217 ;;; still be depending on the check being done. We only care about
218 ;;; EXIT and RETURN (not MV-COMBINATION) since these are the only
219 ;;; contexts where the ultimate values receiver
220 ;;;
221 ;;; In the :HAIRY case, the second value is a list of triples of
222 ;;; the form:
223 ;;;    (NOT-P TYPE ORIGINAL-TYPE)
224 ;;;
225 ;;; If true, the NOT-P flag indicates a test that the corresponding
226 ;;; value is *not* of the specified TYPE. ORIGINAL-TYPE is the type
227 ;;; asserted on this value in the continuation, for use in error
228 ;;; messages. When NOT-P is true, this will be different from TYPE.
229 ;;;
230 ;;; This allows us to take what has been proven about CONT's type into
231 ;;; consideration. If it is cheaper to test for the difference between
232 ;;; the derived type and the asserted type, then we check for the
233 ;;; negation of this type instead.
234 (defun continuation-check-types (cont force-hairy)
235   (declare (type continuation cont))
236   (let ((ctype (continuation-type-to-check cont))
237         (atype (continuation-asserted-type cont))
238         (dest (continuation-dest cont)))
239     (aver (not (eq ctype *wild-type*)))
240     (multiple-value-bind (ctypes count) (no-fun-values-types ctype)
241       (multiple-value-bind (atypes acount) (no-fun-values-types ctype)
242         (aver (eq count acount))
243         (cond ((not (eq count :unknown))
244                (if (or (exit-p dest)
245                        (and (return-p dest)
246                             (multiple-value-bind (ignore count)
247                                 (values-types (return-result-type dest))
248                               (declare (ignore ignore))
249                               (eq count :unknown))))
250                    (maybe-negate-check cont ctypes atypes t)
251                    (maybe-negate-check cont ctypes atypes force-hairy)))
252               ((and (mv-combination-p dest)
253                     (eq (basic-combination-kind dest) :local))
254                (aver (values-type-p ctype))
255                (maybe-negate-check cont
256                                    (args-type-optional ctype)
257                                    (args-type-optional atype)
258                                    force-hairy))
259               (t
260                (values :too-hairy nil)))))))
261
262 ;;; Do we want to do a type check?
263 (defun worth-type-check-p (cont)
264   (let ((dest (continuation-dest cont)))
265     (not (or (values-subtypep (continuation-proven-type cont)
266                               (continuation-type-to-check cont))
267              (and (combination-p dest)
268                   (eq (combination-kind dest) :full)
269                   ;; The theory is that the type assertion is from a
270                   ;; declaration in (or on) the callee, so the callee
271                   ;; should be able to do the check. We want to let
272                   ;; the callee do the check, because it is possible
273                   ;; that by the time of call that declaration will be
274                   ;; changed and we do not want to make people
275                   ;; recompile all calls to a function when they were
276                   ;; originally compiled with a bad declaration. (See
277                   ;; also bug 35.)
278                   (values-subtypep (continuation-externally-checkable-type cont)
279                                    (continuation-type-to-check cont)))
280              (and (mv-combination-p dest) ; bug 220
281                   (eq (mv-combination-kind dest) :full))))))
282
283 ;;; Return true if CONT is a continuation whose type the back end is
284 ;;; likely to want to check. Since we don't know what template the
285 ;;; back end is going to choose to implement the continuation's DEST,
286 ;;; we use a heuristic. We always return T unless:
287 ;;;  -- nobody uses the value, or
288 ;;;  -- safety is totally unimportant, or
289 ;;;  -- the continuation is an argument to an unknown function, or
290 ;;;  -- the continuation is an argument to a known function that has
291 ;;;     no IR2-CONVERT method or :FAST-SAFE templates that are
292 ;;;     compatible with the call's type.
293 ;;;
294 ;;; We must only return NIL when it is *certain* that a check will not
295 ;;; be done, since if we pass up this chance to do the check, it will
296 ;;; be too late. The penalty for being too conservative is duplicated
297 ;;; type checks. The penalty for erring by being too speculative is
298 ;;; much nastier, e.g. falling through without ever being able to find
299 ;;; an appropriate VOP.
300 (defun probable-type-check-p (cont)
301   (declare (type continuation cont))
302   (let ((dest (continuation-dest cont)))
303     (cond ((or (not dest)
304                (policy dest (zerop safety)))
305            nil)
306           ((basic-combination-p dest)
307            (let ((kind (basic-combination-kind dest)))
308              (cond ((eq cont (basic-combination-fun dest)) t)
309                    ((eq kind :local) t)
310                    ((eq kind :full)
311                     (and (combination-p dest)
312                          (not (values-subtypep ; explicit THE
313                                (continuation-externally-checkable-type cont)
314                                (continuation-type-to-check cont)))))
315
316                    ((eq kind :error) nil)
317                    ;; :ERROR means that we have an invalid syntax of
318                    ;; the call and the callee will detect it before
319                    ;; thinking about types.
320
321                    ((fun-info-ir2-convert kind) t)
322                    (t
323                     (dolist (template (fun-info-templates kind) nil)
324                       (when (eq (template-ltn-policy template) :fast-safe)
325                         (multiple-value-bind (val win)
326                             (valid-fun-use dest (template-type template))
327                           (when (or val (not win)) (return t)))))))))
328           (t t))))
329
330 ;;; Return a form that we can convert to do a hairy type check of the
331 ;;; specified TYPES. TYPES is a list of the format returned by
332 ;;; CONTINUATION-CHECK-TYPES in the :HAIRY case. In place of the
333 ;;; actual value(s) we are to check, we use 'DUMMY. This constant
334 ;;; reference is later replaced with the actual values continuation.
335 ;;;
336 ;;; Note that we don't attempt to check for required values being
337 ;;; unsupplied. Such checking is impossible to efficiently do at the
338 ;;; source level because our fixed-values conventions are optimized
339 ;;; for the common MV-BIND case.
340 ;;;
341 ;;; We can always use MULTIPLE-VALUE-BIND, since the macro is clever
342 ;;; about binding a single variable.
343 (defun make-type-check-form (types)
344   (let ((temps (make-gensym-list (length types))))
345     `(multiple-value-bind ,temps 'dummy
346        ,@(mapcar (lambda (temp type)
347                    (let* ((spec
348                            (let ((*unparse-fun-type-simplify* t))
349                              (type-specifier (second type))))
350                           (test (if (first type) `(not ,spec) spec)))
351                      `(unless (typep ,temp ',test)
352                         (%type-check-error
353                          ,temp
354                          ',(type-specifier (third type))))))
355                  temps
356                  types)
357        (values ,@temps))))
358
359 ;;; Splice in explicit type check code immediately before the node
360 ;;; which is CONT's DEST. This code receives the value(s) that were
361 ;;; being passed to CONT, checks the type(s) of the value(s), then
362 ;;; passes them on to CONT.
363 (defun convert-type-check (cont types)
364   (declare (type continuation cont) (type list types))
365   (with-ir1-environment-from-node (continuation-dest cont)
366
367     ;; Ensuring that CONT starts a block lets us freely manipulate its uses.
368     (ensure-block-start cont)
369
370     ;; Make a new continuation and move CONT's uses to it.
371     (let* ((new-start (make-continuation))
372            (dest (continuation-dest cont))
373            (prev (node-prev dest)))
374       (continuation-starts-block new-start)
375       (substitute-continuation-uses new-start cont)
376
377       ;; Setting TYPE-CHECK in CONT to :DELETED indicates that the
378       ;; check has been done.
379       (setf (continuation-%type-check cont) :deleted)
380
381       ;; Make the DEST node start its block so that we can splice in
382       ;; the type check code.
383       (when (continuation-use prev)
384         (node-ends-block (continuation-use prev)))
385
386       (let* ((prev-block (continuation-block prev))
387              (new-block (continuation-block new-start))
388              (dummy (make-continuation)))
389
390         ;; Splice in the new block before DEST, giving the new block
391         ;; all of DEST's predecessors.
392         (dolist (block (block-pred prev-block))
393           (change-block-successor block prev-block new-block))
394
395         ;; Convert the check form, using the new block start as START
396         ;; and a dummy continuation as CONT.
397         (ir1-convert new-start dummy (make-type-check-form types))
398
399         ;; TO DO: Why should this be true? -- WHN 19990601
400         (aver (eq (continuation-block dummy) new-block))
401
402         ;; KLUDGE: Comments at the head of this function in CMU CL
403         ;; said that somewhere in here we
404         ;;   Set the new block's start and end cleanups to the *start*
405         ;;   cleanup of PREV's block. This overrides the incorrect
406         ;;   default from WITH-IR1-ENVIRONMENT-FROM-NODE.
407         ;; Unfortunately I can't find any code which corresponds to this.
408         ;; Perhaps it was a stale comment? Or perhaps I just don't
409         ;; understand.. -- WHN 19990521
410
411         (let ((node (continuation-use dummy)))
412           (setf (block-last new-block) node)
413           ;; Change the use to a use of CONT. (We need to use the
414           ;; dummy continuation to get the control transfer right,
415           ;; because we want to go to PREV's block, not CONT's.)
416           (delete-continuation-use node)
417           (add-continuation-use node cont))
418         ;; Link the new block to PREV's block.
419         (link-blocks new-block prev-block))
420
421       ;; MAKE-TYPE-CHECK-FORM generated a form which checked the type
422       ;; of 'DUMMY, not a real form. At this point we convert to the
423       ;; real form by finding 'DUMMY and overwriting it with the new
424       ;; continuation. (We can find 'DUMMY because no LET conversion
425       ;; has been done yet.) The [mv-]combination code from the
426       ;; mv-bind in the check form will be the use of the new check
427       ;; continuation. We substitute for the first argument of this
428       ;; node.
429       (let* ((node (continuation-use cont))
430              (args (basic-combination-args node))
431              (victim (first args)))
432         (aver (and (= (length args) 1)
433                      (eq (constant-value
434                           (ref-leaf
435                            (continuation-use victim)))
436                          'dummy)))
437         (substitute-continuation new-start victim)))
438
439     ;; Invoking local call analysis converts this call to a LET.
440     (locall-analyze-component *current-component*))
441
442   (values))
443
444 ;;; Emit a type warning for NODE. If the value of NODE is being used
445 ;;; for a variable binding, we figure out which one for source
446 ;;; context. If the value is a constant, we print it specially. We
447 ;;; ignore nodes whose type is NIL, since they are supposed to never
448 ;;; return.
449 (defun emit-type-warning (node)
450   (declare (type node node))
451   (let* ((*compiler-error-context* node)
452          (cont (node-cont node))
453          (atype-spec (type-specifier (continuation-asserted-type cont)))
454          (dtype (node-derived-type node))
455          (dest (continuation-dest cont))
456          (what (when (and (combination-p dest)
457                           (eq (combination-kind dest) :local))
458                  (let ((lambda (combination-lambda dest))
459                        (pos (position-or-lose cont (combination-args dest))))
460                    (format nil "~:[A possible~;The~] binding of ~S"
461                            (and (continuation-use cont)
462                                 (eq (functional-kind lambda) :let))
463                            (leaf-source-name (elt (lambda-vars lambda)
464                                                   pos)))))))
465     (cond ((eq dtype *empty-type*))
466           ((and (ref-p node) (constant-p (ref-leaf node)))
467            (compiler-warn "~:[This~;~:*~A~] is not a ~<~%~9T~:;~S:~>~%  ~S"
468                           what atype-spec (constant-value (ref-leaf node))))
469           (t
470            (compiler-warn
471             "~:[Result~;~:*~A~] is a ~S, ~<~%~9T~:;not a ~S.~>"
472             what (type-specifier dtype) atype-spec))))
473   (values))
474
475 ;;; Loop over all blocks in COMPONENT that have TYPE-CHECK set,
476 ;;; looking for continuations with TYPE-CHECK T. We do two mostly
477 ;;; unrelated things: detect compile-time type errors and determine if
478 ;;; and how to do run-time type checks.
479 ;;;
480 ;;; If there is a compile-time type error, then we mark the
481 ;;; continuation and emit a warning if appropriate. This part loops
482 ;;; over all the uses of the continuation, since after we convert the
483 ;;; check, the :DELETED kind will inhibit warnings about the types of
484 ;;; other uses.
485 ;;;
486 ;;; If a continuation is too complex to be checked by the back end, or
487 ;;; is better checked with explicit code, then convert to an explicit
488 ;;; test. Assertions that can checked by the back end are passed
489 ;;; through. Assertions that can't be tested are flamed about and
490 ;;; marked as not needing to be checked.
491 ;;;
492 ;;; If we determine that a type check won't be done, then we set
493 ;;; TYPE-CHECK to :NO-CHECK. In the non-hairy cases, this is just to
494 ;;; prevent us from wasting time coming to the same conclusion again
495 ;;; on a later iteration. In the hairy case, we must indicate to LTN
496 ;;; that it must choose a safe implementation, since IR2 conversion
497 ;;; will choke on the check.
498 ;;;
499 ;;; The generation of the type checks is delayed until all the type
500 ;;; check decisions have been made because the generation of the type
501 ;;; checks creates new nodes whose derived types aren't always updated
502 ;;; which may lead to inappropriate template choices due to the
503 ;;; modification of argument types.
504 (defun generate-type-checks (component)
505   (collect ((conts))
506     (do-blocks (block component)
507       (when (block-type-check block)
508         (do-nodes (node cont block)
509           (let ((type-check (continuation-type-check cont)))
510             (unless (member type-check '(nil :deleted))
511               (let ((atype (continuation-asserted-type cont)))
512                 (do-uses (use cont)
513                   (unless (values-types-equal-or-intersect
514                            (node-derived-type use) atype)
515                     (unless (policy node (= inhibit-warnings 3))
516                       (emit-type-warning use))))))
517             (when (eq type-check t)
518               (cond ((worth-type-check-p cont)
519                      (conts (cons cont (not (probable-type-check-p cont)))))
520                     ((probable-type-check-p cont)
521                      (setf (continuation-%type-check cont) :deleted))
522                     (t
523                      (setf (continuation-%type-check cont) :no-check))))))
524         (setf (block-type-check block) nil)))
525     (dolist (cont (conts))
526       (destructuring-bind (cont . force-hairy) cont
527         (multiple-value-bind (check types)
528             (continuation-check-types cont force-hairy)
529           (ecase check
530             (:simple)
531             (:hairy
532              (convert-type-check cont types))
533             (:too-hairy
534              (let* ((context (continuation-dest cont))
535                     (*compiler-error-context* context))
536                (when (policy context (>= safety inhibit-warnings))
537                  (compiler-note
538                   "type assertion too complex to check:~% ~S."
539                   (type-specifier (continuation-asserted-type cont)))))
540              (setf (continuation-%type-check cont) :deleted)))))))
541   (values))