e398b70fdc353476206fe2c58563ece863724f64
[sbcl.git] / src / code / typecheckfuns.lisp
1 ;;;; Out-of-line structure slot accessor functions need to do type
2 ;;;; tests. These accessor functions aren't called very often, so it's
3 ;;;; unreasonable to implement them all as different compiled
4 ;;;; functions, because that's too much bloat. But when they are
5 ;;;; called, it's unreasonable to just punt to interpreted TYPEP,
6 ;;;; because that's unreasonably slow. The system implemented here 
7 ;;;; tries to be a reasonable compromise solution to this problem.
8 ;;;;
9 ;;;; Structure accessor functions are still implemented as closures,
10 ;;;; but now one of the closed-over variables is a function which does
11 ;;;; the type test, i.e. a typecheckfun. When a type can be expanded
12 ;;;; fully into known types at compile time, we compile a LAMBDA which
13 ;;;; does TYPEP on it, and use that. If the function can't be expanded
14 ;;;; at compile time, then it can't be compiled efficiently anyway, so
15 ;;;; we just emit a note.
16 ;;;;
17 ;;;; As a further wrinkle on this, we reuse the typecheckfuns, so that
18 ;;;; the dozens of slot accessors which have e.g. :TYPE SYMBOL can all
19 ;;;; share the same typecheckfun instead of having to keep dozens of
20 ;;;; equivalent typecheckfun copies floating around. We can also pull
21 ;;;; a few other tricks to reduce bloat, like implementing all
22 ;;;; typecheckfuns for structure classes as a closure over structure
23 ;;;; LAYOUTs.
24
25 ;;;; This software is part of the SBCL system. See the README file for
26 ;;;; more information.
27 ;;;;
28 ;;;; This software is derived from the CMU CL system, which was
29 ;;;; written at Carnegie Mellon University and released into the
30 ;;;; public domain. The software is in the public domain and is
31 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
32 ;;;; files for more information.
33
34 (in-package "SB!KERNEL")
35 \f
36 ;;;; setting up to precompile code for common types once and for all
37
38 ;;; initialization value for *COMMON-TYPESPECS*
39 (eval-when (:compile-toplevel)
40   (defvar *compile-time-common-typespecs*
41     (let (;; When we generate collections of common specialized
42           ;; array types, what should their element types be?
43           (common-element-typespecs
44            ;; Note: This table is pretty arbitrary, just things I use a lot
45            ;; or see used a lot. If someone has ideas for better values,
46            ;; lemme know. -- WHN 2001-10-15
47            #(t
48              character
49              bit fixnum (unsigned-byte 32) (signed-byte 32)
50              single-float double-float)))
51       (coerce (remove-duplicates
52                (mapcar (lambda (typespec)
53                          (type-specifier (specifier-type typespec)))
54                        ;; Note: This collection of input values is
55                        ;; pretty arbitrary, just inspired by things I
56                        ;; use a lot or see being used a lot in the
57                        ;; system. If someone has ideas for better
58                        ;; values, lemme know. -- WHN 2001-10-15
59                        (concatenate
60                         'list
61                         ;; non-array types
62                         '(bit
63                           boolean
64                           character
65                           cons
66                           double-float
67                           fixnum
68                           hash-table
69                           index
70                           integer
71                           list
72                           package
73                           signed-byte
74                           (signed-byte 8)
75                           single-float
76                           structure-object
77                           symbol
78                           unsigned-byte
79                           (unsigned-byte 8)
80                           (unsigned-byte 32))
81                         ;; systematic names for array types
82                         (map 'list
83                              (lambda (element-type)
84                                `(simple-array ,element-type 1))
85                              common-element-typespecs)
86                         (map 'list
87                              (lambda (element-type)
88                                `(vector ,element-type))
89                              common-element-typespecs)
90                         ;; idiosyncratic names for array types
91                         '(simple-vector
92                           bit-vector simple-bit-vector
93                           string simple-string)))
94                :test #'equal)
95               'simple-vector))))
96
97 ;;; What are the common testable types? (If a slot accessor looks up
98 ;;; one of these types, it doesn't need to supply a compiled TYPEP
99 ;;; function to initialize the possibly-empty entry: instead it's
100 ;;; guaranteed that the entry is there. Hopefully this will reduce
101 ;;; compile time and object file bloat.)
102 (declaim (type simple-vector *common-typespecs*))
103 (defvar *common-typespecs*)
104 #-sb-xc (eval-when (:compile-toplevel :load-toplevel :execute)
105           (setf *common-typespecs*
106                 #.*compile-time-common-typespecs*))
107 ;; (#+SB-XC initialization is handled elsewhere, at cold init time.)
108
109 (defun ctype-is-common-typecheckfun-type-p (ctype)
110   (position (type-specifier ctype) *common-typespecs*
111             :test #'equal))
112
113 (defun typecheck-failure (arg typespec)
114   (error 'type-error :datum arg :expected-type typespec))
115
116 ;;; memoization cache for typecheckfuns: a map from fully-expanded type
117 ;;; specifiers to functions which test the type of their argument
118 (defvar *typecheckfuns*
119   #-sb-xc (make-hash-table :test 'equal)
120   ;; (#+SB-XC initialization is handled elsewhere, at cold init time.)
121   )
122
123 ;;; Memoize the FORM which returns a typecheckfun for TYPESPEC.
124 (defmacro memoized-typecheckfun-form (form typespec)
125   (let ((n-typespec (gensym "TYPESPEC")))
126     `(let ((,n-typespec ,typespec))
127        (or (gethash ,n-typespec *typecheckfuns*)
128            (setf (gethash ,n-typespec *typecheckfuns*)
129                  ,form)))))
130
131 #+sb-xc
132 (defun !typecheckfuns-cold-init ()
133   (setf *typecheckfuns* (make-hash-table :test 'equal))
134   ;; Initialize the table of common typespecs.
135   (setf *common-typespecs* #.*compile-time-common-typespecs*)
136   ;; Initialize *TYPECHECKFUNS* with typecheckfuns for common typespecs.
137   (macrolet ((macro ()
138                `(progn
139                   ,@(map 'list
140                          (lambda (typespec)
141                            `(setf (gethash ',typespec *typecheckfuns*)
142                                   (lambda (arg)
143                                     (unless (typep arg ',typespec)
144                                       (typecheck-failure arg ',typespec))
145                                     (values))))
146                          *common-typespecs*))))
147     (macro))
148   (values))
149
150 ;;; Return a trivial best-you-can-expect-when-you-don't-predefine-the-type
151 ;;; implementation of a function which checks the type of its argument.
152 (defun interpreted-typecheckfun (typespec)
153   ;; Note that we don't and shouldn't memoize this, since otherwise the
154   ;; user could do 
155   ;;   (DEFSTRUCT FOO (X NIL :TYPE XYTYPE))
156   ;;   (DEFTYPE XYTYPE () (OR SYMBOL CHARACTER))
157   ;;   (DEFSTRUCT BAR (Y NIL :TYPE XYTYPE))
158   ;; and be unpleasantly surprised when the memoized old interpreted
159   ;; type check from the FOO-X slot setter interfered with the
160   ;; construction of a shiny new compiled type check for the BAR-Y
161   ;; slot setter.
162   (lambda (arg)
163     (unless (typep arg typespec)
164       (typecheck-failure arg typespec))
165     (values)))
166
167 ;;; Type checks for structure objects are all implemented the same
168 ;;; way, with only the LAYOUT varying, so they're practically begging
169 ;;; to be implemented as closures over the layout.
170 (defun %structure-object-typecheckfun (typespec)
171   (let ((layout (compiler-layout-or-lose typespec)))
172     (lambda (arg)
173       (unless (typep-to-layout arg layout)
174         (typecheck-failure arg typespec))
175       (values))))
176 (defun structure-object-typecheckfun (typespec)
177   (memoized-typecheckfun-form (%structure-object-typecheckfun typespec)
178                               typespec))
179
180 ;;; General type checks need the full compiler, not just stereotyped
181 ;;; closures. We arrange for UNMEMOIZED-TYPECHECKFUN to be produced
182 ;;; for us at compile time (or it can be skipped if the compiler knows
183 ;;; that the memoization lookup can't fail).
184 (defun general-typecheckfun (typespec &optional unmemoized-typecheckfun)
185   (or (gethash typespec *typecheckfuns*)
186       (setf (gethash typespec *typecheckfuns*) unmemoized-typecheckfun)
187       ;; UNMEMOIZED-TYPECHECKFUN shouldn't be NIL unless the compiler
188       ;; knew that the memo would exist, so we shouldn't be here.
189       (error "internal error: no typecheckfun memo for ~%  ~S" typespec)))
190
191 (defun ctype-needs-to-be-interpreted-p (ctype)
192   ;; What we should really do is factor out the code in
193   ;; (DEF-SOURCE-TRANSFORM TYPEP ..) so that it can be shared here.
194   ;; Until then this toy version should be good enough for some testing.
195   (warn "FIXME: This is just a toy stub CTYPE-NEEDS-TO-BE-INTERPRETED-P.")
196   (not (or (position (type-specifier ctype)
197                      *common-typespecs*
198                      :test #'equal)
199            (member-type-p ctype)
200            (numeric-type-p ctype)
201            (array-type-p ctype)
202            (cons-type-p ctype))))
203
204 ;;; Evaluate (at load/execute time) to a function which checks that
205 ;;; its argument is of the specified type.
206 ;;;
207 ;;; The name is slightly misleading, since some cases are memoized, so
208 ;;; we might reuse a value which was made earlier instead of creating
209 ;;; a new one from scratch.
210 (declaim (ftype (function (t) function) typespec-typecheckfun))
211 (defun typespec-typecheckfun (typespec)
212   ;; a general-purpose default case, hopefully overridden by the
213   ;; DEFINE-COMPILER-MACRO implementation
214   (interpreted-typecheckfun typespec))
215
216 ;;; If we know the value of the typespec at compile time, we might
217 ;;; well be able to avoid interpreting it at runtime.
218 (define-compiler-macro typespec-typecheckfun (&whole whole typespec-form)
219   (if (and (consp typespec-form)
220            (eql (first typespec-form) 'quote))
221       (let* ((typespec (second typespec-form))
222              (ctype (specifier-type typespec)))
223         (aver (= 2 (length typespec-form)))
224         (cond ((structure-class-p ctype)
225                `(structure-object-typecheckfun ,typespec-form))
226               ((ctype-needs-to-be-interpreted-p ctype)
227                whole) ; i.e. give up compiler macro
228               (t
229                `(let ((typespec ,typespec-form))
230                   (general-typecheckfun
231                    typespec
232                    ;; Unless we know that the function is already in the
233                    ;; memoization cache
234                    ,@(unless (ctype-is-common-typecheckfun-type-p ctype)
235                        ;; Note that we're arranging for the
236                        ;; UNMEMOIZED-TYPECHECKFUN argument value to be
237                        ;; constructed at compile time. This means the
238                        ;; compiler does the work of compiling the function,
239                        ;; and the loader does the work of loading the
240                        ;; function, regardless of whether the runtime check
241                        ;; for "is it in the memoization cache?" succeeds.
242                        ;; (Then if the memoization check succeeds, the
243                        ;; compiled and loaded function is eventually GCed.)
244                        ;; The wasted motion in the case of a successful
245                        ;; memoization check is unfortunate, but it avoids
246                        ;; having to invoke the compiler at load time when
247                        ;; memoization fails, which is probably more
248                        ;; important.
249                        `((lambda (arg)
250                            (unless (typep arg typespec)
251                              (typecheck-failure arg typespec))))))))))
252       whole)) ; i.e. give up compiler macro