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