Back end work for short vector SIMD packs
[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 #!+sb-simd-pack
344 (defun source-transform-simd-pack-typep (object type)
345   (if (type= type (specifier-type 'simd-pack))
346       `(simd-pack-p ,object)
347       (once-only ((n-obj object))
348         (let ((n-tag (gensym "TAG")))
349           `(and
350             (simd-pack-p ,n-obj)
351             (let ((,n-tag (%simd-pack-tag ,n-obj)))
352               (or ,@(loop
353                       for type in (simd-pack-type-element-type type)
354                       for index = (position type *simd-pack-element-types*)
355                       collect `(eql ,n-tag ,index)))))))))
356
357 ;;; Return the predicate and type from the most specific entry in
358 ;;; *TYPE-PREDICATES* that is a supertype of TYPE.
359 (defun find-supertype-predicate (type)
360   (declare (type ctype type))
361   (let ((res nil)
362         (res-type nil))
363     (dolist (x *backend-type-predicates*)
364       (let ((stype (car x)))
365         (when (and (csubtypep type stype)
366                    (or (not res-type)
367                        (csubtypep stype res-type)))
368           (setq res-type stype)
369           (setq res (cdr x)))))
370     (values res res-type)))
371
372 ;;; Return forms to test that OBJ has the rank and dimensions
373 ;;; specified by TYPE, where STYPE is the type we have checked against
374 ;;; (which is the same but for dimensions and element type).
375 ;;;
376 ;;; Secondary return value is true if passing the generated tests implies that
377 ;;; the array has a header.
378 (defun test-array-dimensions (obj type stype)
379   (declare (type array-type type stype))
380   (let ((obj `(truly-the ,(type-specifier stype) ,obj))
381         (dims (array-type-dimensions type)))
382     (unless (or (eq dims '*)
383                 (equal dims (array-type-dimensions stype)))
384       (cond ((cdr dims)
385              (values `((array-header-p ,obj)
386                        ,@(when (eq (array-type-dimensions stype) '*)
387                                `((= (%array-rank ,obj) ,(length dims))))
388                        ,@(loop for d in dims
389                                for i from 0
390                                unless (eq '* d)
391                                collect `(= (%array-dimension ,obj ,i) ,d)))
392                      t))
393             ((not dims)
394              (values `((array-header-p ,obj)
395                        (= (%array-rank ,obj) 0))
396                      t))
397             ((not (array-type-complexp type))
398              (if (csubtypep stype (specifier-type 'vector))
399                  (values (unless (eq '* (car dims))
400                            `((= (vector-length ,obj) ,@dims)))
401                          nil)
402                  (values (if (eq '* (car dims))
403                              `((not (array-header-p ,obj)))
404                              `((not (array-header-p ,obj))
405                                (= (vector-length ,obj) ,@dims)))
406                          nil)))
407             (t
408              (values (unless (eq '* (car dims))
409                        `((if (array-header-p ,obj)
410                              (= (%array-dimension ,obj 0) ,@dims)
411                              (= (vector-length ,obj) ,@dims))))
412                      nil))))))
413
414 ;;; Return forms to test that OBJ has the element-type specified by type
415 ;;; specified by TYPE, where STYPE is the type we have checked against (which
416 ;;; is the same but for dimensions and element type). If HEADERP is true, OBJ
417 ;;; is guaranteed to be an array-header.
418 (defun test-array-element-type (obj type stype headerp)
419   (declare (type array-type type stype))
420   (let ((obj `(truly-the ,(type-specifier stype) ,obj))
421         (eltype (array-type-specialized-element-type type)))
422     (unless (or (type= eltype (array-type-specialized-element-type stype))
423                 (eq eltype *wild-type*))
424       (let ((typecode (sb!vm:saetp-typecode (find-saetp-by-ctype eltype))))
425         (with-unique-names (data)
426          (if (and headerp (not (array-type-complexp stype)))
427              ;; If we know OBJ is an array header, and that the array is
428              ;; simple, we also know there is exactly one indirection to
429              ;; follow.
430              `((eq (%other-pointer-widetag (%array-data-vector ,obj)) ,typecode))
431              `((do ((,data ,(if headerp `(%array-data-vector ,obj) obj)
432                            (%array-data-vector ,data)))
433                    ((not (array-header-p ,data))
434                     (eq (%other-pointer-widetag ,data) ,typecode))))))))))
435
436 ;;; If we can find a type predicate that tests for the type without
437 ;;; dimensions, then use that predicate and test for dimensions.
438 ;;; Otherwise, just do %TYPEP.
439 (defun source-transform-array-typep (obj type)
440   (multiple-value-bind (pred stype) (find-supertype-predicate type)
441     (if (and (array-type-p stype)
442              ;; (If the element type hasn't been defined yet, it's
443              ;; not safe to assume here that it will eventually
444              ;; have (UPGRADED-ARRAY-ELEMENT-TYPE type)=T, so punt.)
445              (not (unknown-type-p (array-type-element-type type)))
446              (or (eq (array-type-complexp stype) (array-type-complexp type))
447                  (and (eql (array-type-complexp stype) :maybe)
448                       (eql (array-type-complexp type) t))))
449         (once-only ((n-obj obj))
450           (multiple-value-bind (tests headerp)
451               (test-array-dimensions n-obj type stype)
452             `(and (,pred ,n-obj)
453                   ,@(when (and (eql (array-type-complexp stype) :maybe)
454                                (eql (array-type-complexp type) t))
455                       ;; KLUDGE: this is a bit lame; if we get here,
456                       ;; we already know that N-OBJ is an array, but
457                       ;; (NOT SIMPLE-ARRAY) doesn't know that.  On the
458                       ;; other hand, this should get compiled down to
459                       ;; two widetag tests, so it's only a bit lame.
460                       `((typep ,n-obj '(not simple-array))))
461                   ,@tests
462                   ,@(test-array-element-type n-obj type stype headerp))))
463         `(%typep ,obj ',(type-specifier type)))))
464
465 ;;; Transform a type test against some instance type. The type test is
466 ;;; flushed if the result is known at compile time. If not properly
467 ;;; named, error. If sealed and has no subclasses, just test for
468 ;;; layout-EQ. If a structure then test for layout-EQ and then a
469 ;;; general test based on layout-inherits. If safety is important,
470 ;;; then we also check whether the layout for the object is invalid
471 ;;; and signal an error if so. Otherwise, look up the indirect
472 ;;; class-cell and call CLASS-CELL-TYPEP at runtime.
473 (deftransform %instance-typep ((object spec) (* *) * :node node)
474   (aver (constant-lvar-p spec))
475   (let* ((spec (lvar-value spec))
476          (class (specifier-type spec))
477          (name (classoid-name class))
478          (otype (lvar-type object))
479          (layout (let ((res (info :type :compiler-layout name)))
480                    (if (and res (not (layout-invalid res)))
481                        res
482                        nil))))
483     (cond
484       ;; Flush tests whose result is known at compile time.
485       ((not (types-equal-or-intersect otype class))
486        nil)
487       ((csubtypep otype class)
488        t)
489       ;; If not properly named, error.
490       ((not (and name (eq (find-classoid name) class)))
491        (compiler-error "can't compile TYPEP of anonymous or undefined ~
492                         class:~%  ~S"
493                        class))
494       (t
495        ;; Delay the type transform to give type propagation a chance.
496        (delay-ir1-transform node :constraint)
497
498        ;; Otherwise transform the type test.
499        (multiple-value-bind (pred get-layout)
500            (cond
501              ((csubtypep class (specifier-type 'funcallable-instance))
502               (values 'funcallable-instance-p '%funcallable-instance-layout))
503              ((csubtypep class (specifier-type 'instance))
504               (values '%instancep '%instance-layout))
505              (t
506               (values '(lambda (x) (declare (ignore x)) t) 'layout-of)))
507          (cond
508            ((and (eq (classoid-state class) :sealed) layout
509                  (not (classoid-subclasses class)))
510             ;; Sealed and has no subclasses.
511             (let ((n-layout (gensym)))
512               `(and (,pred object)
513                     (let ((,n-layout (,get-layout object)))
514                       ,@(when (policy *lexenv* (>= safety speed))
515                               `((when (layout-invalid ,n-layout)
516                                   (%layout-invalid-error object ',layout))))
517                       (eq ,n-layout ',layout)))))
518            ((and (typep class 'structure-classoid) layout)
519             ;; structure type tests; hierarchical layout depths
520             (let ((depthoid (layout-depthoid layout))
521                   (n-layout (gensym)))
522               `(and (,pred object)
523                     (let ((,n-layout (,get-layout object)))
524                       ;; we used to check for invalid layouts here,
525                       ;; but in fact that's both unnecessary and
526                       ;; wrong; it's unnecessary because structure
527                       ;; classes can't be redefined, and it's wrong
528                       ;; because it is quite legitimate to pass an
529                       ;; object with an invalid layout to a structure
530                       ;; type test.
531                       (if (eq ,n-layout ',layout)
532                           t
533                           (and (> (layout-depthoid ,n-layout)
534                                   ,depthoid)
535                                (locally (declare (optimize (safety 0)))
536                                  ;; Use DATA-VECTOR-REF directly,
537                                  ;; since that's what SVREF in a
538                                  ;; SAFETY 0 lexenv will eventually be
539                                  ;; transformed to. This can give a
540                                  ;; large compilation speedup, since
541                                  ;; %INSTANCE-TYPEPs are frequently
542                                  ;; created during GENERATE-TYPE-CHECKS,
543                                  ;; and the normal aref transformation path
544                                  ;; is pretty heavy.
545                                  (eq (data-vector-ref (layout-inherits ,n-layout)
546                                                       ,depthoid)
547                                      ',layout))))))))
548            ((and layout (>= (layout-depthoid layout) 0))
549             ;; hierarchical layout depths for other things (e.g.
550             ;; CONDITION, STREAM)
551             (let ((depthoid (layout-depthoid layout))
552                   (n-layout (gensym))
553                   (n-inherits (gensym)))
554               `(and (,pred object)
555                     (let ((,n-layout (,get-layout object)))
556                       (when (layout-invalid ,n-layout)
557                         (setq ,n-layout (update-object-layout-or-invalid
558                                          object ',layout)))
559                       (if (eq ,n-layout ',layout)
560                           t
561                           (let ((,n-inherits (layout-inherits ,n-layout)))
562                             (declare (optimize (safety 0)))
563                             (and (> (length ,n-inherits) ,depthoid)
564                                  ;; See above.
565                                  (eq (data-vector-ref ,n-inherits ,depthoid)
566                                      ',layout))))))))
567            (t
568             (/noshow "default case -- ,PRED and CLASS-CELL-TYPEP")
569             `(and (,pred object)
570                   (classoid-cell-typep (,get-layout object)
571                                        ',(find-classoid-cell name :create t)
572                                        object)))))))))
573
574 ;;; If the specifier argument is a quoted constant, then we consider
575 ;;; converting into a simple predicate or other stuff. If the type is
576 ;;; constant, but we can't transform the call, then we convert to
577 ;;; %TYPEP. We only pass when the type is non-constant. This allows us
578 ;;; to recognize between calls that might later be transformed
579 ;;; successfully when a constant type is discovered. We don't give an
580 ;;; efficiency note when we pass, since the IR1 transform will give
581 ;;; one if necessary and appropriate.
582 ;;;
583 ;;; If the type is TYPE= to a type that has a predicate, then expand
584 ;;; to that predicate. Otherwise, we dispatch off of the type's type.
585 ;;; These transformations can increase space, but it is hard to tell
586 ;;; when, so we ignore policy and always do them.
587 (defun source-transform-typep (object type)
588   (let ((ctype (careful-specifier-type type)))
589     (or (when (not ctype)
590           (compiler-warn "illegal type specifier for TYPEP: ~S" type)
591           (return-from source-transform-typep (values nil t)))
592         (multiple-value-bind (constantp value) (type-singleton-p ctype)
593           (and constantp
594                `(eql ,object ',value)))
595         (let ((pred (cdr (assoc ctype *backend-type-predicates*
596                                 :test #'type=))))
597           (when pred `(,pred ,object)))
598         (typecase ctype
599           (hairy-type
600            (source-transform-hairy-typep object ctype))
601           (negation-type
602            (source-transform-negation-typep object ctype))
603           (union-type
604            (source-transform-union-typep object ctype))
605           (intersection-type
606            (source-transform-intersection-typep object ctype))
607           (member-type
608            `(if (member ,object ',(member-type-members ctype)) t))
609           (args-type
610            (compiler-warn "illegal type specifier for TYPEP: ~S" type)
611            (return-from source-transform-typep (values nil t)))
612           (t nil))
613         (typecase ctype
614           (numeric-type
615            (source-transform-numeric-typep object ctype))
616           (classoid
617            `(%instance-typep ,object ',type))
618           (array-type
619            (source-transform-array-typep object ctype))
620           (cons-type
621            (source-transform-cons-typep object ctype))
622           (character-set-type
623            (source-transform-character-set-typep object ctype))
624           #!+sb-simd-pack
625           (simd-pack-type
626            (source-transform-simd-pack-typep object ctype))
627           (t nil))
628         `(%typep ,object ',type))))
629
630 (define-source-transform typep (object spec &optional env)
631   ;; KLUDGE: It looks bad to only do this on explicitly quoted forms,
632   ;; since that would overlook other kinds of constants. But it turns
633   ;; out that the DEFTRANSFORM for TYPEP detects any constant
634   ;; lvar, transforms it into a quoted form, and gives this
635   ;; source transform another chance, so it all works out OK, in a
636   ;; weird roundabout way. -- WHN 2001-03-18
637   (if (and (not env)
638            (consp spec)
639            (eq (car spec) 'quote)
640            (or (not *allow-instrumenting*)
641                (policy *lexenv* (= store-coverage-data 0))))
642       (source-transform-typep object (cadr spec))
643       (values nil t)))
644 \f
645 ;;;; coercion
646
647 ;;; Constant-folding.
648 ;;;
649 #-sb-xc-host
650 (defoptimizer (coerce optimizer) ((x type) node)
651   (when (and (constant-lvar-p x) (constant-lvar-p type))
652     (let ((value (lvar-value x)))
653       (when (or (numberp value) (characterp value))
654         (constant-fold-call node)
655         t))))
656
657 ;;; Drops dimension information from vector types.
658 (defun simplify-vector-type (type)
659   (aver (csubtypep type (specifier-type '(array * (*)))))
660   (let* ((array-type
661           (if (csubtypep type (specifier-type 'simple-array))
662               'simple-array
663               'array))
664          (complexp
665           (not
666            (or (eq 'simple-array array-type)
667                (neq *empty-type*
668                     (type-intersection type (specifier-type 'simple-array)))))))
669     (dolist (etype
670               #+sb-xc-host '(t bit character)
671               #-sb-xc-host sb!kernel::*specialized-array-element-types*
672               #+sb-xc-host (values nil nil nil)
673               #-sb-xc-host (values `(,array-type * (*)) t complexp))
674       (when etype
675         (let ((simplified (specifier-type `(,array-type ,etype (*)))))
676           (when (csubtypep type simplified)
677             (return (values (type-specifier simplified)
678                             etype
679                             complexp))))))))
680
681 (deftransform coerce ((x type) (* *) * :node node)
682   (unless (constant-lvar-p type)
683     (give-up-ir1-transform))
684   (let* ((tval (lvar-value type))
685          (tspec (ir1-transform-specifier-type tval)))
686     (if (csubtypep (lvar-type x) tspec)
687         'x
688         ;; Note: The THE forms we use to wrap the results make sure that
689         ;; specifiers like (SINGLE-FLOAT 0.0 1.0) can raise a TYPE-ERROR.
690         (cond
691           ((csubtypep tspec (specifier-type 'double-float))
692            `(the ,tval (%double-float x)))
693           ;; FIXME: #!+long-float (t ,(error "LONG-FLOAT case needed"))
694           ((csubtypep tspec (specifier-type 'float))
695            `(the ,tval (%single-float x)))
696            ;; Special case STRING and SIMPLE-STRING as they are union types
697            ;; in SBCL.
698            ((member tval '(string simple-string))
699             `(the ,tval
700                (if (typep x ',tval)
701                    x
702                    (replace (make-array (length x) :element-type 'character) x))))
703            ;; Special case VECTOR
704            ((eq tval 'vector)
705             `(the ,tval
706                (if (vectorp x)
707                    x
708                    (replace (make-array (length x)) x))))
709            ;; Handle specialized element types for 1D arrays.
710            ((csubtypep tspec (specifier-type '(array * (*))))
711             ;; Can we avoid checking for dimension issues like (COERCE FOO
712             ;; '(SIMPLE-VECTOR 5)) returning a vector of length 6?
713             ;;
714             ;; CLHS actually allows this for all code with SAFETY < 3,
715             ;; but we're a conservative bunch.
716             (if (or (policy node (zerop safety)) ; no need in unsafe code
717                     (and (array-type-p tspec)    ; no need when no dimensions
718                          (equal (array-type-dimensions tspec) '(*))))
719                 ;; We can!
720                 (multiple-value-bind (vtype etype complexp) (simplify-vector-type tspec)
721                   (unless vtype
722                     (give-up-ir1-transform))
723                   `(the ,vtype
724                      (if (typep x ',vtype)
725                          x
726                          (replace
727                           (make-array (length x) :element-type ',etype
728                                       ,@(when complexp
729                                               (list :fill-pointer t
730                                                     :adjustable t)))
731                           x))))
732                 ;; No, duh. Dimension checking required.
733                 (give-up-ir1-transform
734                  "~@<~S specifies dimensions other than (*) in safe code.~:@>"
735                  tval)))
736            (t
737             (give-up-ir1-transform
738              "~@<open coding coercion to ~S not implemented.~:@>"
739              tval))))))