teach IR1-TRANSFORM-TYPE-PREDICATE about alien types
[sbcl.git] / src / compiler / typetran.lisp
1 ;;;; This file contains stuff that implements the portable IR1
2 ;;;; semantics of type tests and coercion. The main thing we do is
3 ;;;; convert complex type operations into simpler code that can be
4 ;;;; compiled inline.
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 ;;;; type predicate translation
18 ;;;;
19 ;;;; We maintain a bidirectional association between type predicates
20 ;;;; and the tested type. The presence of a predicate in this
21 ;;;; association implies that it is desirable to implement tests of
22 ;;;; this type using the predicate. These are either predicates that
23 ;;;; the back end is likely to have special knowledge about, or
24 ;;;; predicates so complex that the only reasonable implentation is
25 ;;;; via function call.
26 ;;;;
27 ;;;; Some standard types (such as ATOM) are best tested by letting the
28 ;;;; TYPEP source transform do its thing with the expansion. These
29 ;;;; types (and corresponding predicates) are not maintained in this
30 ;;;; association. In this case, there need not be any predicate
31 ;;;; function unless it is required by the Common Lisp specification.
32 ;;;;
33 ;;;; The mapping between predicates and type structures is considered
34 ;;;; part of the backend; different backends can support different
35 ;;;; sets of predicates.
36
37 ;;; Establish an association between the type predicate NAME and the
38 ;;; corresponding TYPE. This causes the type predicate to be
39 ;;; recognized for purposes of optimization.
40 (defmacro define-type-predicate (name type)
41   `(%define-type-predicate ',name ',type))
42 (defun %define-type-predicate (name specifier)
43   (let ((type (specifier-type specifier)))
44     (setf (gethash name *backend-predicate-types*) type)
45     (setf *backend-type-predicates*
46           (cons (cons type name)
47                 (remove name *backend-type-predicates*
48                         :key #'cdr)))
49     (%deftransform name '(function (t) *) #'fold-type-predicate)
50     name))
51 \f
52 ;;;; IR1 transforms
53
54 ;;; If we discover the type argument is constant during IR1
55 ;;; optimization, then give the source transform another chance. The
56 ;;; source transform can't pass, since we give it an explicit
57 ;;; constant. At worst, it will convert to %TYPEP, which will prevent
58 ;;; spurious attempts at transformation (and possible repeated
59 ;;; warnings.)
60 (deftransform typep ((object type &optional env) * * :node node)
61   (unless (constant-lvar-p type)
62     (give-up-ir1-transform "can't open-code test of non-constant type"))
63   (unless (and (constant-lvar-p env) (null (lvar-value env)))
64     (give-up-ir1-transform "environment argument present and not null"))
65   (multiple-value-bind (expansion fail-p)
66       (source-transform-typep 'object (lvar-value type))
67     (if fail-p
68         (abort-ir1-transform)
69         expansion)))
70
71 ;;; If the lvar OBJECT definitely is or isn't of the specified
72 ;;; type, then return T or NIL as appropriate. Otherwise quietly
73 ;;; GIVE-UP-IR1-TRANSFORM.
74 (defun ir1-transform-type-predicate (object type node)
75   (declare (type lvar object) (type ctype type))
76   (let ((otype (lvar-type object)))
77     (flet ((tricky ()
78              (cond ((typep type 'alien-type-type)
79                     ;; We don't transform alien type tests until here, because
80                     ;; once we do that the rest of the type system can no longer
81                     ;; reason about them properly -- so we'd miss out on type
82                     ;; derivation, etc.
83                     (delay-ir1-transform node :optimize)
84                     (let ((alien-type (alien-type-type-alien-type type)))
85                       ;; If it's a lisp-rep-type, the CTYPE should be one already.
86                       (aver (not (compute-lisp-rep-type alien-type)))
87                       `(sb!alien::alien-value-typep object ',alien-type)))
88                    (t
89                     (give-up-ir1-transform)))))
90       (cond ((not (types-equal-or-intersect otype type))
91             nil)
92            ((csubtypep otype type)
93             t)
94            ((eq type *empty-type*)
95             nil)
96            (t
97             (let ((intersect (type-intersection2 type otype)))
98               (unless intersect
99                 (tricky))
100               (multiple-value-bind (constantp value)
101                   (type-singleton-p intersect)
102                 (if constantp
103                     `(eql object ',value)
104                     (tricky)))))))))
105
106 ;;; Flush %TYPEP tests whose result is known at compile time.
107 (deftransform %typep ((object type) * * :node node)
108   (unless (constant-lvar-p type)
109     (give-up-ir1-transform))
110   (ir1-transform-type-predicate
111    object
112    (ir1-transform-specifier-type (lvar-value type))
113    node))
114
115 ;;; This is the IR1 transform for simple type predicates. It checks
116 ;;; whether the single argument is known to (not) be of the
117 ;;; appropriate type, expanding to T or NIL as appropriate.
118 (deftransform fold-type-predicate ((object) * * :node node :defun-only t)
119   (let ((ctype (gethash (leaf-source-name
120                          (ref-leaf
121                           (lvar-uses
122                            (basic-combination-fun node))))
123                         *backend-predicate-types*)))
124     (aver ctype)
125     (ir1-transform-type-predicate object ctype node)))
126
127 ;;; If FIND-CLASSOID is called on a constant class, locate the
128 ;;; CLASSOID-CELL at load time.
129 (deftransform find-classoid ((name) ((constant-arg symbol)) *)
130   (let* ((name (lvar-value name))
131          (cell (find-classoid-cell name :create t)))
132     `(or (classoid-cell-classoid ',cell)
133          (error "class not yet defined: ~S" name))))
134 \f
135 ;;;; standard type predicates, i.e. those defined in package COMMON-LISP,
136 ;;;; plus at least one oddball (%INSTANCEP)
137 ;;;;
138 ;;;; Various other type predicates (e.g. low-level representation
139 ;;;; stuff like SIMPLE-ARRAY-SINGLE-FLOAT-P) are defined elsewhere.
140
141 ;;; FIXME: This function is only called once, at top level. Why not
142 ;;; just expand all its operations into toplevel code?
143 (defun !define-standard-type-predicates ()
144   (define-type-predicate arrayp array)
145   ; (The ATOM predicate is handled separately as (NOT CONS).)
146   (define-type-predicate bit-vector-p bit-vector)
147   (define-type-predicate characterp character)
148   (define-type-predicate compiled-function-p compiled-function)
149   (define-type-predicate complexp complex)
150   (define-type-predicate complex-rational-p (complex rational))
151   (define-type-predicate complex-float-p (complex float))
152   (define-type-predicate consp cons)
153   (define-type-predicate floatp float)
154   (define-type-predicate functionp function)
155   (define-type-predicate integerp integer)
156   (define-type-predicate keywordp keyword)
157   (define-type-predicate listp list)
158   (define-type-predicate null null)
159   (define-type-predicate numberp number)
160   (define-type-predicate rationalp rational)
161   (define-type-predicate realp real)
162   (define-type-predicate sequencep sequence)
163   (define-type-predicate extended-sequence-p extended-sequence)
164   (define-type-predicate simple-bit-vector-p simple-bit-vector)
165   (define-type-predicate simple-string-p simple-string)
166   (define-type-predicate simple-vector-p simple-vector)
167   (define-type-predicate stringp string)
168   (define-type-predicate %instancep instance)
169   (define-type-predicate funcallable-instance-p funcallable-instance)
170   (define-type-predicate symbolp symbol)
171   (define-type-predicate vectorp vector))
172 (!define-standard-type-predicates)
173 \f
174 ;;;; transforms for type predicates not implemented primitively
175 ;;;;
176 ;;;; See also VM dependent transforms.
177
178 (define-source-transform atom (x)
179   `(not (consp ,x)))
180 #!+sb-unicode
181 (define-source-transform base-char-p (x)
182   `(typep ,x 'base-char))
183 \f
184 ;;;; TYPEP source transform
185
186 ;;; Return a form that tests the variable N-OBJECT for being in the
187 ;;; binds specified by TYPE. BASE is the name of the base type, for
188 ;;; declaration. We make SAFETY locally 0 to inhibit any checking of
189 ;;; this assertion.
190 (defun transform-numeric-bound-test (n-object type base)
191   (declare (type numeric-type type))
192   (let ((low (numeric-type-low type))
193         (high (numeric-type-high type)))
194     `(locally
195        (declare (optimize (safety 0)))
196        (and ,@(when low
197                 (if (consp low)
198                     `((> (truly-the ,base ,n-object) ,(car low)))
199                     `((>= (truly-the ,base ,n-object) ,low))))
200             ,@(when high
201                 (if (consp high)
202                     `((< (truly-the ,base ,n-object) ,(car high)))
203                     `((<= (truly-the ,base ,n-object) ,high))))))))
204
205 ;;; Do source transformation of a test of a known numeric type. We can
206 ;;; assume that the type doesn't have a corresponding predicate, since
207 ;;; those types have already been picked off. In particular, CLASS
208 ;;; must be specified, since it is unspecified only in NUMBER and
209 ;;; COMPLEX. Similarly, we assume that COMPLEXP is always specified.
210 ;;;
211 ;;; For non-complex types, we just test that the number belongs to the
212 ;;; base type, and then test that it is in bounds. When CLASS is
213 ;;; INTEGER, we check to see whether the range is no bigger than
214 ;;; FIXNUM. If so, we check for FIXNUM instead of INTEGER. This allows
215 ;;; us to use fixnum comparison to test the bounds.
216 ;;;
217 ;;; For complex types, we must test for complex, then do the above on
218 ;;; both the real and imaginary parts. When CLASS is float, we need
219 ;;; only check the type of the realpart, since the format of the
220 ;;; realpart and the imagpart must be the same.
221 (defun source-transform-numeric-typep (object type)
222   (let* ((class (numeric-type-class type))
223          (base (ecase class
224                  (integer (containing-integer-type
225                            (if (numeric-type-complexp type)
226                                (modified-numeric-type type
227                                                       :complexp :real)
228                                type)))
229                  (rational 'rational)
230                  (float (or (numeric-type-format type) 'float))
231                  ((nil) 'real))))
232     (once-only ((n-object object))
233       (ecase (numeric-type-complexp type)
234         (:real
235          `(and (typep ,n-object ',base)
236                ,(transform-numeric-bound-test n-object type base)))
237         (:complex
238          `(and (complexp ,n-object)
239                ,(once-only ((n-real `(realpart (truly-the complex ,n-object)))
240                             (n-imag `(imagpart (truly-the complex ,n-object))))
241                   `(progn
242                      ,n-imag ; ignorable
243                      (and (typep ,n-real ',base)
244                           ,@(when (eq class 'integer)
245                               `((typep ,n-imag ',base)))
246                           ,(transform-numeric-bound-test n-real type base)
247                           ,(transform-numeric-bound-test n-imag type
248                                                          base))))))))))
249
250 ;;; Do the source transformation for a test of a hairy type. AND,
251 ;;; SATISFIES and NOT are converted into the obvious code. We convert
252 ;;; unknown types to %TYPEP, emitting an efficiency note if
253 ;;; appropriate.
254 (defun source-transform-hairy-typep (object type)
255   (declare (type hairy-type type))
256   (let ((spec (hairy-type-specifier type)))
257     (cond ((unknown-type-p type)
258            (when (policy *lexenv* (> speed inhibit-warnings))
259              (compiler-notify "can't open-code test of unknown type ~S"
260                               (type-specifier type)))
261            `(%typep ,object ',spec))
262           (t
263            (ecase (first spec)
264              (satisfies
265               `(if (funcall (global-function ,(second spec)) ,object) t nil))
266              ((not and)
267               (once-only ((n-obj object))
268                 `(,(first spec) ,@(mapcar (lambda (x)
269                                             `(typep ,n-obj ',x))
270                                           (rest spec))))))))))
271
272 (defun source-transform-negation-typep (object type)
273   (declare (type negation-type type))
274   (let ((spec (type-specifier (negation-type-type type))))
275     `(not (typep ,object ',spec))))
276
277 ;;; Do source transformation for TYPEP of a known union type. If a
278 ;;; union type contains LIST, then we pull that out and make it into a
279 ;;; single LISTP call.  Note that if SYMBOL is in the union, then LIST
280 ;;; will be a subtype even without there being any (member NIL).  We
281 ;;; currently just drop through to the general code in this case,
282 ;;; rather than trying to optimize it (but FIXME CSR 2004-04-05: it
283 ;;; wouldn't be hard to optimize it after all).
284 (defun source-transform-union-typep (object type)
285   (let* ((types (union-type-types type))
286          (type-cons (specifier-type 'cons))
287          (mtype (find-if #'member-type-p types))
288          (members (when mtype (member-type-members mtype))))
289     (if (and mtype
290              (memq nil members)
291              (memq type-cons types))
292         (once-only ((n-obj object))
293           `(or (listp ,n-obj)
294                (typep ,n-obj
295                       '(or ,@(mapcar #'type-specifier
296                                      (remove type-cons
297                                              (remove mtype types)))
298                         (member ,@(remove nil members))))))
299         (once-only ((n-obj object))
300           `(or ,@(mapcar (lambda (x)
301                            `(typep ,n-obj ',(type-specifier x)))
302                          types))))))
303
304 ;;; Do source transformation for TYPEP of a known intersection type.
305 (defun source-transform-intersection-typep (object type)
306   (once-only ((n-obj object))
307     `(and ,@(mapcar (lambda (x)
308                       `(typep ,n-obj ',(type-specifier x)))
309                     (intersection-type-types type)))))
310
311 ;;; If necessary recurse to check the cons type.
312 (defun source-transform-cons-typep (object type)
313   (let* ((car-type (cons-type-car-type type))
314          (cdr-type (cons-type-cdr-type type)))
315     (let ((car-test-p (not (type= car-type *universal-type*)))
316           (cdr-test-p (not (type= cdr-type *universal-type*))))
317       (if (and (not car-test-p) (not cdr-test-p))
318           `(consp ,object)
319           (once-only ((n-obj object))
320             `(and (consp ,n-obj)
321                   ,@(if car-test-p
322                         `((typep (car ,n-obj)
323                                  ',(type-specifier car-type))))
324                   ,@(if cdr-test-p
325                         `((typep (cdr ,n-obj)
326                                  ',(type-specifier cdr-type))))))))))
327
328 (defun source-transform-character-set-typep (object type)
329   (let ((pairs (character-set-type-pairs type)))
330     (if (and (= (length pairs) 1)
331             (= (caar pairs) 0)
332             (= (cdar pairs) (1- sb!xc:char-code-limit)))
333        `(characterp ,object)
334        (once-only ((n-obj object))
335          (let ((n-code (gensym "CODE")))
336            `(and (characterp ,n-obj)
337                  (let ((,n-code (sb!xc:char-code ,n-obj)))
338                    (or
339                     ,@(loop for pair in pairs
340                             collect
341                             `(<= ,(car pair) ,n-code ,(cdr pair)))))))))))
342
343 ;;; Return the predicate and type from the most specific entry in
344 ;;; *TYPE-PREDICATES* that is a supertype of TYPE.
345 (defun find-supertype-predicate (type)
346   (declare (type ctype type))
347   (let ((res nil)
348         (res-type nil))
349     (dolist (x *backend-type-predicates*)
350       (let ((stype (car x)))
351         (when (and (csubtypep type stype)
352                    (or (not res-type)
353                        (csubtypep stype res-type)))
354           (setq res-type stype)
355           (setq res (cdr x)))))
356     (values res res-type)))
357
358 ;;; Return forms to test that OBJ has the rank and dimensions
359 ;;; specified by TYPE, where STYPE is the type we have checked against
360 ;;; (which is the same but for dimensions and element type).
361 ;;;
362 ;;; Secondary return value is true if passing the generated tests implies that
363 ;;; the array has a header.
364 (defun test-array-dimensions (obj type stype)
365   (declare (type array-type type stype))
366   (let ((obj `(truly-the ,(type-specifier stype) ,obj))
367         (dims (array-type-dimensions type)))
368     (unless (or (eq dims '*)
369                 (equal dims (array-type-dimensions stype)))
370       (cond ((cdr dims)
371              (values `((array-header-p ,obj)
372                        ,@(when (eq (array-type-dimensions stype) '*)
373                                `((= (%array-rank ,obj) ,(length dims))))
374                        ,@(loop for d in dims
375                                for i from 0
376                                unless (eq '* d)
377                                collect `(= (%array-dimension ,obj ,i) ,d)))
378                      t))
379             ((not dims)
380              (values `((array-header-p ,obj)
381                        (= (%array-rank ,obj) 0))
382                      t))
383             ((not (array-type-complexp type))
384              (if (csubtypep stype (specifier-type 'vector))
385                  (values (unless (eq '* (car dims))
386                            `((= (vector-length ,obj) ,@dims)))
387                          nil)
388                  (values (if (eq '* (car dims))
389                              `((not (array-header-p ,obj)))
390                              `((not (array-header-p ,obj))
391                                (= (vector-length ,obj) ,@dims)))
392                          nil)))
393             (t
394              (values (unless (eq '* (car dims))
395                        `((if (array-header-p ,obj)
396                              (= (%array-dimension ,obj 0) ,@dims)
397                              (= (vector-length ,obj) ,@dims))))
398                      nil))))))
399
400 ;;; Return forms to test that OBJ has the element-type specified by type
401 ;;; specified by TYPE, where STYPE is the type we have checked against (which
402 ;;; is the same but for dimensions and element type). If HEADERP is true, OBJ
403 ;;; is guaranteed to be an array-header.
404 (defun test-array-element-type (obj type stype headerp)
405   (declare (type array-type type stype))
406   (let ((obj `(truly-the ,(type-specifier stype) ,obj))
407         (eltype (array-type-specialized-element-type type)))
408     (unless (or (type= eltype (array-type-specialized-element-type stype))
409                 (eq eltype *wild-type*))
410       (let ((typecode (sb!vm:saetp-typecode (find-saetp-by-ctype eltype))))
411         (with-unique-names (data)
412          (if (and headerp (not (array-type-complexp stype)))
413              ;; If we know OBJ is an array header, and that the array is
414              ;; simple, we also know there is exactly one indirection to
415              ;; follow.
416              `((eq (%other-pointer-widetag (%array-data-vector ,obj)) ,typecode))
417              `((do ((,data ,(if headerp `(%array-data-vector ,obj) obj)
418                            (%array-data-vector ,data)))
419                    ((not (array-header-p ,data))
420                     (eq (%other-pointer-widetag ,data) ,typecode))))))))))
421
422 ;;; If we can find a type predicate that tests for the type without
423 ;;; dimensions, then use that predicate and test for dimensions.
424 ;;; Otherwise, just do %TYPEP.
425 (defun source-transform-array-typep (obj type)
426   (multiple-value-bind (pred stype) (find-supertype-predicate type)
427     (if (and (array-type-p stype)
428              ;; (If the element type hasn't been defined yet, it's
429              ;; not safe to assume here that it will eventually
430              ;; have (UPGRADED-ARRAY-ELEMENT-TYPE type)=T, so punt.)
431              (not (unknown-type-p (array-type-element-type type)))
432              (or (eq (array-type-complexp stype) (array-type-complexp type))
433                  (and (eql (array-type-complexp stype) :maybe)
434                       (eql (array-type-complexp type) t))))
435         (once-only ((n-obj obj))
436           (multiple-value-bind (tests headerp)
437               (test-array-dimensions n-obj type stype)
438             `(and (,pred ,n-obj)
439                   ,@(when (and (eql (array-type-complexp stype) :maybe)
440                                (eql (array-type-complexp type) t))
441                       ;; KLUDGE: this is a bit lame; if we get here,
442                       ;; we already know that N-OBJ is an array, but
443                       ;; (NOT SIMPLE-ARRAY) doesn't know that.  On the
444                       ;; other hand, this should get compiled down to
445                       ;; two widetag tests, so it's only a bit lame.
446                       `((typep ,n-obj '(not simple-array))))
447                   ,@tests
448                   ,@(test-array-element-type n-obj type stype headerp))))
449         `(%typep ,obj ',(type-specifier type)))))
450
451 ;;; Transform a type test against some instance type. The type test is
452 ;;; flushed if the result is known at compile time. If not properly
453 ;;; named, error. If sealed and has no subclasses, just test for
454 ;;; layout-EQ. If a structure then test for layout-EQ and then a
455 ;;; general test based on layout-inherits. If safety is important,
456 ;;; then we also check whether the layout for the object is invalid
457 ;;; and signal an error if so. Otherwise, look up the indirect
458 ;;; class-cell and call CLASS-CELL-TYPEP at runtime.
459 (deftransform %instance-typep ((object spec) (* *) * :node node)
460   (aver (constant-lvar-p spec))
461   (let* ((spec (lvar-value spec))
462          (class (specifier-type spec))
463          (name (classoid-name class))
464          (otype (lvar-type object))
465          (layout (let ((res (info :type :compiler-layout name)))
466                    (if (and res (not (layout-invalid res)))
467                        res
468                        nil))))
469     (cond
470       ;; Flush tests whose result is known at compile time.
471       ((not (types-equal-or-intersect otype class))
472        nil)
473       ((csubtypep otype class)
474        t)
475       ;; If not properly named, error.
476       ((not (and name (eq (find-classoid name) class)))
477        (compiler-error "can't compile TYPEP of anonymous or undefined ~
478                         class:~%  ~S"
479                        class))
480       (t
481        ;; Delay the type transform to give type propagation a chance.
482        (delay-ir1-transform node :constraint)
483
484        ;; Otherwise transform the type test.
485        (multiple-value-bind (pred get-layout)
486            (cond
487              ((csubtypep class (specifier-type 'funcallable-instance))
488               (values 'funcallable-instance-p '%funcallable-instance-layout))
489              ((csubtypep class (specifier-type 'instance))
490               (values '%instancep '%instance-layout))
491              (t
492               (values '(lambda (x) (declare (ignore x)) t) 'layout-of)))
493          (cond
494            ((and (eq (classoid-state class) :sealed) layout
495                  (not (classoid-subclasses class)))
496             ;; Sealed and has no subclasses.
497             (let ((n-layout (gensym)))
498               `(and (,pred object)
499                     (let ((,n-layout (,get-layout object)))
500                       ,@(when (policy *lexenv* (>= safety speed))
501                               `((when (layout-invalid ,n-layout)
502                                   (%layout-invalid-error object ',layout))))
503                       (eq ,n-layout ',layout)))))
504            ((and (typep class 'structure-classoid) layout)
505             ;; structure type tests; hierarchical layout depths
506             (let ((depthoid (layout-depthoid layout))
507                   (n-layout (gensym)))
508               `(and (,pred object)
509                     (let ((,n-layout (,get-layout object)))
510                       ;; we used to check for invalid layouts here,
511                       ;; but in fact that's both unnecessary and
512                       ;; wrong; it's unnecessary because structure
513                       ;; classes can't be redefined, and it's wrong
514                       ;; because it is quite legitimate to pass an
515                       ;; object with an invalid layout to a structure
516                       ;; type test.
517                       (if (eq ,n-layout ',layout)
518                           t
519                           (and (> (layout-depthoid ,n-layout)
520                                   ,depthoid)
521                                (locally (declare (optimize (safety 0)))
522                                  ;; Use DATA-VECTOR-REF directly,
523                                  ;; since that's what SVREF in a
524                                  ;; SAFETY 0 lexenv will eventually be
525                                  ;; transformed to. This can give a
526                                  ;; large compilation speedup, since
527                                  ;; %INSTANCE-TYPEPs are frequently
528                                  ;; created during GENERATE-TYPE-CHECKS,
529                                  ;; and the normal aref transformation path
530                                  ;; is pretty heavy.
531                                  (eq (data-vector-ref (layout-inherits ,n-layout)
532                                                       ,depthoid)
533                                      ',layout))))))))
534            ((and layout (>= (layout-depthoid layout) 0))
535             ;; hierarchical layout depths for other things (e.g.
536             ;; CONDITION, STREAM)
537             (let ((depthoid (layout-depthoid layout))
538                   (n-layout (gensym))
539                   (n-inherits (gensym)))
540               `(and (,pred object)
541                     (let ((,n-layout (,get-layout object)))
542                       (when (layout-invalid ,n-layout)
543                         (setq ,n-layout (update-object-layout-or-invalid
544                                          object ',layout)))
545                       (if (eq ,n-layout ',layout)
546                           t
547                           (let ((,n-inherits (layout-inherits ,n-layout)))
548                             (declare (optimize (safety 0)))
549                             (and (> (length ,n-inherits) ,depthoid)
550                                  ;; See above.
551                                  (eq (data-vector-ref ,n-inherits ,depthoid)
552                                      ',layout))))))))
553            (t
554             (/noshow "default case -- ,PRED and CLASS-CELL-TYPEP")
555             `(and (,pred object)
556                   (classoid-cell-typep (,get-layout object)
557                                        ',(find-classoid-cell name :create t)
558                                        object)))))))))
559
560 ;;; If the specifier argument is a quoted constant, then we consider
561 ;;; converting into a simple predicate or other stuff. If the type is
562 ;;; constant, but we can't transform the call, then we convert to
563 ;;; %TYPEP. We only pass when the type is non-constant. This allows us
564 ;;; to recognize between calls that might later be transformed
565 ;;; successfully when a constant type is discovered. We don't give an
566 ;;; efficiency note when we pass, since the IR1 transform will give
567 ;;; one if necessary and appropriate.
568 ;;;
569 ;;; If the type is TYPE= to a type that has a predicate, then expand
570 ;;; to that predicate. Otherwise, we dispatch off of the type's type.
571 ;;; These transformations can increase space, but it is hard to tell
572 ;;; when, so we ignore policy and always do them.
573 (defun source-transform-typep (object type)
574   (let ((ctype (careful-specifier-type type)))
575     (or (when (not ctype)
576           (compiler-warn "illegal type specifier for TYPEP: ~S" type)
577           (return-from source-transform-typep (values nil t)))
578         (multiple-value-bind (constantp value) (type-singleton-p ctype)
579           (and constantp
580                `(eql ,object ',value)))
581         (let ((pred (cdr (assoc ctype *backend-type-predicates*
582                                 :test #'type=))))
583           (when pred `(,pred ,object)))
584         (typecase ctype
585           (hairy-type
586            (source-transform-hairy-typep object ctype))
587           (negation-type
588            (source-transform-negation-typep object ctype))
589           (union-type
590            (source-transform-union-typep object ctype))
591           (intersection-type
592            (source-transform-intersection-typep object ctype))
593           (member-type
594            `(if (member ,object ',(member-type-members ctype)) t))
595           (args-type
596            (compiler-warn "illegal type specifier for TYPEP: ~S" type)
597            (return-from source-transform-typep (values nil t)))
598           (t nil))
599         (typecase ctype
600           (numeric-type
601            (source-transform-numeric-typep object ctype))
602           (classoid
603            `(%instance-typep ,object ',type))
604           (array-type
605            (source-transform-array-typep object ctype))
606           (cons-type
607            (source-transform-cons-typep object ctype))
608           (character-set-type
609            (source-transform-character-set-typep object ctype))
610           (t nil))
611         `(%typep ,object ',type))))
612
613 (define-source-transform typep (object spec &optional env)
614   ;; KLUDGE: It looks bad to only do this on explicitly quoted forms,
615   ;; since that would overlook other kinds of constants. But it turns
616   ;; out that the DEFTRANSFORM for TYPEP detects any constant
617   ;; lvar, transforms it into a quoted form, and gives this
618   ;; source transform another chance, so it all works out OK, in a
619   ;; weird roundabout way. -- WHN 2001-03-18
620   (if (and (not env)
621            (consp spec)
622            (eq (car spec) 'quote)
623            (or (not *allow-instrumenting*)
624                (policy *lexenv* (= store-coverage-data 0))))
625       (source-transform-typep object (cadr spec))
626       (values nil t)))
627 \f
628 ;;;; coercion
629
630 ;;; Constant-folding.
631 ;;;
632 #-sb-xc-host
633 (defoptimizer (coerce optimizer) ((x type) node)
634   (when (and (constant-lvar-p x) (constant-lvar-p type))
635     (let ((value (lvar-value x)))
636       (when (or (numberp value) (characterp value))
637         (constant-fold-call node)
638         t))))
639
640 ;;; Drops dimension information from vector types.
641 (defun simplify-vector-type (type)
642   (aver (csubtypep type (specifier-type '(array * (*)))))
643   (let* ((array-type
644           (if (csubtypep type (specifier-type 'simple-array))
645               'simple-array
646               'array))
647          (complexp
648           (not
649            (or (eq 'simple-array array-type)
650                (neq *empty-type*
651                     (type-intersection type (specifier-type 'simple-array)))))))
652     (dolist (etype
653               #+sb-xc-host '(t bit character)
654               #-sb-xc-host sb!kernel::*specialized-array-element-types*
655               #+sb-xc-host (values nil nil nil)
656               #-sb-xc-host (values `(,array-type * (*)) t complexp))
657       (when etype
658         (let ((simplified (specifier-type `(,array-type ,etype (*)))))
659           (when (csubtypep type simplified)
660             (return (values (type-specifier simplified)
661                             etype
662                             complexp))))))))
663
664 (deftransform coerce ((x type) (* *) * :node node)
665   (unless (constant-lvar-p type)
666     (give-up-ir1-transform))
667   (let* ((tval (lvar-value type))
668          (tspec (ir1-transform-specifier-type tval)))
669     (if (csubtypep (lvar-type x) tspec)
670         'x
671         ;; Note: The THE forms we use to wrap the results make sure that
672         ;; specifiers like (SINGLE-FLOAT 0.0 1.0) can raise a TYPE-ERROR.
673         (cond
674           ((csubtypep tspec (specifier-type 'double-float))
675            `(the ,tval (%double-float x)))
676           ;; FIXME: #!+long-float (t ,(error "LONG-FLOAT case needed"))
677           ((csubtypep tspec (specifier-type 'float))
678            `(the ,tval (%single-float x)))
679            ;; Special case STRING and SIMPLE-STRING as they are union types
680            ;; in SBCL.
681            ((member tval '(string simple-string))
682             `(the ,tval
683                (if (typep x ',tval)
684                    x
685                    (replace (make-array (length x) :element-type 'character) x))))
686            ;; Special case VECTOR
687            ((eq tval 'vector)
688             `(the ,tval
689                (if (vectorp x)
690                    x
691                    (replace (make-array (length x)) x))))
692            ;; Handle specialized element types for 1D arrays.
693            ((csubtypep tspec (specifier-type '(array * (*))))
694             ;; Can we avoid checking for dimension issues like (COERCE FOO
695             ;; '(SIMPLE-VECTOR 5)) returning a vector of length 6?
696             ;;
697             ;; CLHS actually allows this for all code with SAFETY < 3,
698             ;; but we're a conservative bunch.
699             (if (or (policy node (zerop safety)) ; no need in unsafe code
700                     (and (array-type-p tspec)    ; no need when no dimensions
701                          (equal (array-type-dimensions tspec) '(*))))
702                 ;; We can!
703                 (multiple-value-bind (vtype etype complexp) (simplify-vector-type tspec)
704                   (unless vtype
705                     (give-up-ir1-transform))
706                   `(the ,vtype
707                      (if (typep x ',vtype)
708                          x
709                          (replace
710                           (make-array (length x) :element-type ',etype
711                                       ,@(when complexp
712                                               (list :fill-pointer t
713                                                     :adjustable t)))
714                           x))))
715                 ;; No, duh. Dimension checking required.
716                 (give-up-ir1-transform
717                  "~@<~S specifies dimensions other than (*) in safe code.~:@>"
718                  tval)))
719            (t
720             (give-up-ir1-transform
721              "~@<open coding coercion to ~S not implemented.~:@>"
722              tval))))))