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