1 ;;;; array-specific optimizers and transforms
3 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
14 ;;;; utilities for optimizing array operations
16 ;;; Return UPGRADED-ARRAY-ELEMENT-TYPE for LVAR, or do
17 ;;; GIVE-UP-IR1-TRANSFORM if the upgraded element type can't be
19 (defun upgraded-element-type-specifier-or-give-up (lvar)
20 (let ((element-type-specifier (upgraded-element-type-specifier lvar)))
21 (if (eq element-type-specifier '*)
22 (give-up-ir1-transform
23 "upgraded array element type not known at compile time")
24 element-type-specifier)))
26 (defun upgraded-element-type-specifier (lvar)
27 (type-specifier (array-type-upgraded-element-type (lvar-type lvar))))
29 ;;; Array access functions return an object from the array, hence its type is
30 ;;; going to be the array upgraded element type. Secondary return value is the
31 ;;; known supertype of the upgraded-array-element-type, if if the exact
32 ;;; U-A-E-T is not known. (If it is NIL, the primary return value is as good
34 (defun array-type-upgraded-element-type (type)
36 ;; Note that this IF mightn't be satisfied even if the runtime
37 ;; value is known to be a subtype of some specialized ARRAY, because
38 ;; we can have values declared e.g. (AND SIMPLE-VECTOR UNKNOWN-TYPE),
39 ;; which are represented in the compiler as INTERSECTION-TYPE, not
42 (values (array-type-specialized-element-type type) nil))
43 ;; Deal with intersection types (bug #316078)
45 (let ((intersection-types (intersection-type-types type))
46 (element-type *wild-type*)
47 (element-supertypes nil))
48 (dolist (intersection-type intersection-types)
49 (multiple-value-bind (cur-type cur-supertype)
50 (array-type-upgraded-element-type intersection-type)
51 ;; According to ANSI, an array may have only one specialized
52 ;; element type - e.g. '(and (array foo) (array bar))
53 ;; is not a valid type unless foo and bar upgrade to the
56 ((eq cur-type *wild-type*)
58 ((eq element-type *wild-type*)
59 (setf element-type cur-type))
60 ((or (not (csubtypep cur-type element-type))
61 (not (csubtypep element-type cur-type)))
62 ;; At least two different element types where given, the array
63 ;; is valid iff they represent the same type.
65 ;; FIXME: TYPE-INTERSECTION already takes care of disjoint array
66 ;; types, so I believe this code should be unreachable. Maybe
67 ;; signal a warning / error instead?
68 (setf element-type *empty-type*)))
69 (push (or cur-supertype (type-*-to-t cur-type))
72 (when (and (eq *wild-type* element-type) element-supertypes)
73 (apply #'type-intersection element-supertypes)))))
75 (let ((union-types (union-type-types type))
77 (element-supertypes nil))
78 (dolist (union-type union-types)
79 (multiple-value-bind (cur-type cur-supertype)
80 (array-type-upgraded-element-type union-type)
82 ((eq element-type *wild-type*)
84 ((eq element-type nil)
85 (setf element-type cur-type))
86 ((or (eq cur-type *wild-type*)
87 ;; If each of the two following tests fail, it is not
88 ;; possible to determine the element-type of the array
89 ;; because more than one kind of element-type was provided
90 ;; like in '(or (array foo) (array bar)) although a
91 ;; supertype (or foo bar) may be provided as the second
92 ;; returned value returned. See also the KLUDGE below.
93 (not (csubtypep cur-type element-type))
94 (not (csubtypep element-type cur-type)))
95 (setf element-type *wild-type*)))
96 (push (or cur-supertype (type-*-to-t cur-type))
99 (when (eq *wild-type* element-type)
100 (apply #'type-union element-supertypes)))))
102 ;; Convert member-type to an union-type.
103 (array-type-upgraded-element-type
104 (apply #'type-union (mapcar #'ctype-of (member-type-members type)))))
106 ;; KLUDGE: there is no good answer here, but at least
107 ;; *wild-type* won't cause HAIRY-DATA-VECTOR-{REF,SET} to be
108 ;; erroneously optimized (see generic/vm-tran.lisp) -- CSR,
110 (values *wild-type* nil))))
112 (defun array-type-declared-element-type (type)
113 (if (array-type-p type)
114 (array-type-element-type type)
117 ;;; The ``new-value'' for array setters must fit in the array, and the
118 ;;; return type is going to be the same as the new-value for SETF
120 (defun assert-new-value-type (new-value array)
121 (let ((type (lvar-type array)))
122 (when (array-type-p type)
125 (array-type-specialized-element-type type)
126 (lexenv-policy (node-lexenv (lvar-dest new-value))))))
127 (lvar-type new-value))
129 ;;; Return true if ARG is NIL, or is a constant-lvar whose
130 ;;; value is NIL, false otherwise.
131 (defun unsupplied-or-nil (arg)
132 (declare (type (or lvar null) arg))
134 (and (constant-lvar-p arg)
135 (not (lvar-value arg)))))
137 (defun supplied-and-true (arg)
139 (constant-lvar-p arg)
143 ;;;; DERIVE-TYPE optimizers
145 ;;; Array operations that use a specific number of indices implicitly
146 ;;; assert that the array is of that rank.
147 (defun assert-array-rank (array rank)
150 (specifier-type `(array * ,(make-list rank :initial-element '*)))
151 (lexenv-policy (node-lexenv (lvar-dest array)))))
153 (defun derive-aref-type (array)
154 (multiple-value-bind (uaet other)
155 (array-type-upgraded-element-type (lvar-type array))
158 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
159 (assert-array-rank array (length indices))
162 (deftransform array-in-bounds-p ((array &rest subscripts))
164 (give-up-ir1-transform
165 "~@<lower array bounds unknown or negative and upper bounds not ~
168 (integerp x))) ; might be NIL or *
170 (let ((dimensions (array-type-dimensions-or-give-up
171 (lvar-conservative-type array))))
172 ;; shortcut for zero dimensions
173 (when (some (lambda (dim)
174 (and (bound-known-p dim) (zerop dim)))
177 ;; we first collect the subscripts LVARs' bounds and see whether
178 ;; we can already decide on the result of the optimization without
179 ;; even taking a look at the dimensions.
180 (flet ((subscript-bounds (subscript)
181 (let* ((type1 (lvar-type subscript))
182 (type2 (if (csubtypep type1 (specifier-type 'integer))
183 (weaken-integer-type type1 :range-only t)
185 (low (if (integer-type-p type2)
186 (numeric-type-low type2)
188 (high (numeric-type-high type2)))
190 ((and (or (not (bound-known-p low)) (minusp low))
191 (or (not (bound-known-p high)) (not (minusp high))))
192 ;; can't be sure about the lower bound and the upper bound
193 ;; does not give us a definite clue either.
195 ((and (bound-known-p high) (minusp high))
196 (return nil)) ; definitely below lower bound (zero).
199 (let* ((subscripts-bounds (mapcar #'subscript-bounds subscripts))
200 (subscripts-lower-bound (mapcar #'car subscripts-bounds))
201 (subscripts-upper-bound (mapcar #'cdr subscripts-bounds))
203 (mapcar (lambda (low high dim)
205 ;; first deal with infinite bounds
206 ((some (complement #'bound-known-p) (list low high dim))
207 (when (and (bound-known-p dim) (bound-known-p low) (<= dim low))
209 ;; now we know all bounds
213 (aver (not (minusp low)))
217 subscripts-lower-bound
218 subscripts-upper-bound
220 (if (eql in-bounds (length dimensions))
224 (defoptimizer (aref derive-type) ((array &rest indices) node)
225 (assert-array-rank array (length indices))
226 (derive-aref-type array))
228 (defoptimizer (%aset derive-type) ((array &rest stuff))
229 (assert-array-rank array (1- (length stuff)))
230 (assert-new-value-type (car (last stuff)) array))
232 (macrolet ((define (name)
233 `(defoptimizer (,name derive-type) ((array index))
234 (derive-aref-type array))))
235 (define hairy-data-vector-ref)
236 (define hairy-data-vector-ref/check-bounds)
237 (define data-vector-ref))
240 (defoptimizer (data-vector-ref-with-offset derive-type) ((array index offset))
241 (derive-aref-type array))
243 (macrolet ((define (name)
244 `(defoptimizer (,name derive-type) ((array index new-value))
245 (assert-new-value-type new-value array))))
246 (define hairy-data-vector-set)
247 (define hairy-data-vector-set/check-bounds)
248 (define data-vector-set))
251 (defoptimizer (data-vector-set-with-offset derive-type) ((array index offset new-value))
252 (assert-new-value-type new-value array))
254 ;;; Figure out the type of the data vector if we know the argument
256 (defun derive-%with-array-data/mumble-type (array)
257 (let ((atype (lvar-type array)))
258 (when (array-type-p atype)
260 `(simple-array ,(type-specifier
261 (array-type-specialized-element-type atype))
263 (defoptimizer (%with-array-data derive-type) ((array start end))
264 (derive-%with-array-data/mumble-type array))
265 (defoptimizer (%with-array-data/fp derive-type) ((array start end))
266 (derive-%with-array-data/mumble-type array))
268 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
269 (assert-array-rank array (length indices))
272 (defoptimizer (row-major-aref derive-type) ((array index))
273 (derive-aref-type array))
275 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
276 (assert-new-value-type new-value array))
278 (defoptimizer (make-array derive-type)
279 ((dims &key initial-element element-type initial-contents
280 adjustable fill-pointer displaced-index-offset displaced-to))
281 (let* ((simple (and (unsupplied-or-nil adjustable)
282 (unsupplied-or-nil displaced-to)
283 (unsupplied-or-nil fill-pointer)))
285 (or `(,(if simple 'simple-array 'array)
286 ,(cond ((not element-type) t)
287 ((constant-lvar-p element-type)
288 (let ((ctype (careful-specifier-type
289 (lvar-value element-type))))
291 ((or (null ctype) (unknown-type-p ctype)) '*)
292 (t (sb!xc:upgraded-array-element-type
293 (lvar-value element-type))))))
296 ,(cond ((constant-lvar-p dims)
297 (let* ((val (lvar-value dims))
298 (cdims (if (listp val) val (list val))))
302 ((csubtypep (lvar-type dims)
303 (specifier-type 'integer))
308 (if (and (not simple)
309 (or (supplied-and-true adjustable)
310 (supplied-and-true displaced-to)
311 (supplied-and-true fill-pointer)))
312 (careful-specifier-type `(and ,spec (not simple-array)))
313 (careful-specifier-type spec))))
317 ;;; Convert VECTOR into a MAKE-ARRAY.
318 (define-source-transform vector (&rest elements)
319 `(make-array ,(length elements) :initial-contents (list ,@elements)))
321 ;;; Just convert it into a MAKE-ARRAY.
322 (deftransform make-string ((length &key
323 (element-type 'character)
325 #.*default-init-char-form*)))
326 `(the simple-string (make-array (the index length)
327 :element-type element-type
328 ,@(when initial-element
329 '(:initial-element initial-element)))))
331 (defun rewrite-initial-contents (rank initial-contents env)
333 (if (and (consp initial-contents)
334 (member (car initial-contents) '(list vector sb!impl::backq-list)))
335 `(list ,@(mapcar (lambda (dim)
336 (rewrite-initial-contents (1- rank) dim env))
337 (cdr initial-contents)))
339 ;; This is the important bit: once we are past the level of
340 ;; :INITIAL-CONTENTS that relates to the array structure, reinline LIST
341 ;; and VECTOR so that nested DX isn't screwed up.
342 `(locally (declare (inline list vector))
345 ;;; Prevent open coding DIMENSION and :INITIAL-CONTENTS arguments, so that we
346 ;;; can pick them apart in the DEFTRANSFORMS, and transform '(3) style
347 ;;; dimensions to integer args directly.
348 (define-source-transform make-array (dimensions &rest keyargs &environment env)
349 (if (or (and (fun-lexically-notinline-p 'list)
350 (fun-lexically-notinline-p 'vector))
351 (oddp (length keyargs)))
353 (multiple-value-bind (new-dimensions rank)
354 (flet ((constant-dims (dimensions)
355 (let* ((dims (constant-form-value dimensions env))
356 (canon (if (listp dims) dims (list dims)))
357 (rank (length canon)))
358 (values (if (= rank 1)
359 (list 'quote (car canon))
362 (cond ((sb!xc:constantp dimensions env)
363 (constant-dims dimensions))
364 ((and (consp dimensions) (eq 'list dimensions))
365 (values dimensions (length (cdr dimensions))))
367 (values dimensions nil))))
368 (let ((initial-contents (getf keyargs :initial-contents)))
369 (when (and initial-contents rank)
370 (setf (getf keyargs :initial-contents)
371 (rewrite-initial-contents rank initial-contents env))))
372 `(locally (declare (notinline list vector))
373 (make-array ,new-dimensions ,@keyargs)))))
375 ;;; This baby is a bit of a monster, but it takes care of any MAKE-ARRAY
376 ;;; call which creates a vector with a known element type -- and tries
377 ;;; to do a good job with all the different ways it can happen.
378 (defun transform-make-array-vector (length element-type initial-element
379 initial-contents call)
380 (aver (or (not element-type) (constant-lvar-p element-type)))
381 (let* ((c-length (when (constant-lvar-p length)
382 (lvar-value length)))
383 (elt-spec (if element-type
384 (lvar-value element-type)
386 (elt-ctype (ir1-transform-specifier-type elt-spec))
387 (saetp (if (unknown-type-p elt-ctype)
388 (give-up-ir1-transform "~S is an unknown type: ~S"
389 :element-type elt-spec)
390 (find-saetp-by-ctype elt-ctype)))
391 (default-initial-element (sb!vm:saetp-initial-element-default saetp))
392 (n-bits (sb!vm:saetp-n-bits saetp))
393 (typecode (sb!vm:saetp-typecode saetp))
394 (n-pad-elements (sb!vm:saetp-n-pad-elements saetp))
397 (ceiling (* (+ c-length n-pad-elements) n-bits)
399 (let ((padded-length-form (if (zerop n-pad-elements)
401 `(+ length ,n-pad-elements))))
404 ((>= n-bits sb!vm:n-word-bits)
405 `(* ,padded-length-form
407 ,(the fixnum (/ n-bits sb!vm:n-word-bits))))
409 (let ((n-elements-per-word (/ sb!vm:n-word-bits n-bits)))
410 (declare (type index n-elements-per-word)) ; i.e., not RATIO
411 `(ceiling ,padded-length-form ,n-elements-per-word)))))))
413 `(simple-array ,(sb!vm:saetp-specifier saetp) (,(or c-length '*))))
415 `(truly-the ,result-spec
416 (allocate-vector ,typecode (the index length) ,n-words-form))))
417 (cond ((and initial-element initial-contents)
418 (abort-ir1-transform "Both ~S and ~S specified."
419 :initial-contents :initial-element))
420 ;; :INITIAL-CONTENTS (LIST ...), (VECTOR ...) and `(1 1 ,x) with a
422 ((and initial-contents c-length
423 (lvar-matches initial-contents
424 :fun-names '(list vector sb!impl::backq-list)
425 :arg-count c-length))
426 (let ((parameters (eliminate-keyword-args
427 call 1 '((:element-type element-type)
428 (:initial-contents initial-contents))))
429 (elt-vars (make-gensym-list c-length))
430 (lambda-list '(length)))
431 (splice-fun-args initial-contents :any c-length)
432 (dolist (p parameters)
435 (if (eq p 'initial-contents)
438 `(lambda ,lambda-list
439 (declare (type ,elt-spec ,@elt-vars)
440 (ignorable ,@lambda-list))
441 (truly-the ,result-spec
442 (initialize-vector ,alloc-form ,@elt-vars)))))
443 ;; constant :INITIAL-CONTENTS and LENGTH
444 ((and initial-contents c-length (constant-lvar-p initial-contents))
445 (let ((contents (lvar-value initial-contents)))
446 (unless (= c-length (length contents))
447 (abort-ir1-transform "~S has ~S elements, vector length is ~S."
448 :initial-contents (length contents) c-length))
449 (let ((parameters (eliminate-keyword-args
450 call 1 '((:element-type element-type)
451 (:initial-contents initial-contents)))))
452 `(lambda (length ,@parameters)
453 (declare (ignorable ,@parameters))
454 (truly-the ,result-spec
455 (initialize-vector ,alloc-form
456 ,@(map 'list (lambda (elt)
457 `(the ,elt-spec ',elt))
459 ;; any other :INITIAL-CONTENTS
461 (let ((parameters (eliminate-keyword-args
462 call 1 '((:element-type element-type)
463 (:initial-contents initial-contents)))))
464 `(lambda (length ,@parameters)
465 (declare (ignorable ,@parameters))
466 (unless (= length (length initial-contents))
467 (error "~S has ~S elements, vector length is ~S."
468 :initial-contents (length initial-contents) length))
469 (truly-the ,result-spec
470 (replace ,alloc-form initial-contents)))))
471 ;; :INITIAL-ELEMENT, not EQL to the default
472 ((and initial-element
473 (or (not (constant-lvar-p initial-element))
474 (not (eql default-initial-element (lvar-value initial-element)))))
475 (let ((parameters (eliminate-keyword-args
476 call 1 '((:element-type element-type)
477 (:initial-element initial-element))))
478 (init (if (constant-lvar-p initial-element)
479 (list 'quote (lvar-value initial-element))
481 `(lambda (length ,@parameters)
482 (declare (ignorable ,@parameters))
483 (truly-the ,result-spec
484 (fill ,alloc-form (the ,elt-spec ,init))))))
485 ;; just :ELEMENT-TYPE, or maybe with :INITIAL-ELEMENT EQL to the
489 (unless (ctypep default-initial-element elt-ctype)
490 ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
491 ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
492 ;; INITIAL-ELEMENT is not supplied, the consequences of later
493 ;; reading an uninitialized element of new-array are undefined,"
494 ;; so this could be legal code as long as the user plans to
495 ;; write before he reads, and if he doesn't we're free to do
496 ;; anything we like. But in case the user doesn't know to write
497 ;; elements before he reads elements (or to read manuals before
498 ;; he writes code:-), we'll signal a STYLE-WARNING in case he
499 ;; didn't realize this.
501 (compiler-warn "~S ~S is not a ~S"
502 :initial-element default-initial-element
504 (compiler-style-warn "The default initial element ~S is not a ~S."
505 default-initial-element
507 (let ((parameters (eliminate-keyword-args
508 call 1 '((:element-type element-type)
509 (:initial-element initial-element)))))
510 `(lambda (length ,@parameters)
511 (declare (ignorable ,@parameters))
514 ;;; IMPORTANT: The order of these three MAKE-ARRAY forms matters: the least
515 ;;; specific must come first, otherwise suboptimal transforms will result for
518 (deftransform make-array ((dims &key initial-element element-type
519 adjustable fill-pointer)
521 (when (null initial-element)
522 (give-up-ir1-transform))
523 (let* ((eltype (cond ((not element-type) t)
524 ((not (constant-lvar-p element-type))
525 (give-up-ir1-transform
526 "ELEMENT-TYPE is not constant."))
528 (lvar-value element-type))))
529 (eltype-type (ir1-transform-specifier-type eltype))
530 (saetp (find-if (lambda (saetp)
531 (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
532 sb!vm:*specialized-array-element-type-properties*))
533 (creation-form `(make-array dims
534 :element-type ',(type-specifier (sb!vm:saetp-ctype saetp))
536 '(:fill-pointer fill-pointer))
538 '(:adjustable adjustable)))))
541 (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
543 (cond ((and (constant-lvar-p initial-element)
544 (eql (lvar-value initial-element)
545 (sb!vm:saetp-initial-element-default saetp)))
548 ;; error checking for target, disabled on the host because
549 ;; (CTYPE-OF #\Null) is not possible.
551 (when (constant-lvar-p initial-element)
552 (let ((value (lvar-value initial-element)))
554 ((not (ctypep value (sb!vm:saetp-ctype saetp)))
555 ;; this case will cause an error at runtime, so we'd
556 ;; better WARN about it now.
557 (warn 'array-initial-element-mismatch
558 :format-control "~@<~S is not a ~S (which is the ~
563 (type-specifier (sb!vm:saetp-ctype saetp))
564 'upgraded-array-element-type
566 ((not (ctypep value eltype-type))
567 ;; this case will not cause an error at runtime, but
568 ;; it's still worth STYLE-WARNing about.
569 (compiler-style-warn "~S is not a ~S."
571 `(let ((array ,creation-form))
572 (multiple-value-bind (vector)
573 (%data-vector-and-index array 0)
574 (fill vector (the ,(sb!vm:saetp-specifier saetp) initial-element)))
577 ;;; The list type restriction does not ensure that the result will be a
578 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
579 ;;; and displaced-to keywords ensures that it will be simple.
581 ;;; FIXME: should we generalize this transform to non-simple (though
582 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
583 ;;; deal with those? Maybe when the DEFTRANSFORM
584 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
586 (deftransform make-array ((dims &key
587 element-type initial-element initial-contents)
589 (:element-type (constant-arg *))
591 (:initial-contents *))
595 (when (lvar-matches dims :fun-names '(list) :arg-count 1)
596 (let ((length (car (splice-fun-args dims :any 1))))
597 (return-from make-array
598 (transform-make-array-vector length
603 (unless (constant-lvar-p dims)
604 (give-up-ir1-transform
605 "The dimension list is not constant; cannot open code array creation."))
606 (let ((dims (lvar-value dims)))
607 (unless (every #'integerp dims)
608 (give-up-ir1-transform
609 "The dimension list contains something other than an integer: ~S"
611 (if (= (length dims) 1)
612 `(make-array ',(car dims)
614 '(:element-type element-type))
615 ,@(when initial-element
616 '(:initial-element initial-element))
617 ,@(when initial-contents
618 '(:initial-contents initial-contents)))
619 (let* ((total-size (reduce #'* dims))
622 ,(cond ((null element-type) t)
623 ((and (constant-lvar-p element-type)
624 (ir1-transform-specifier-type
625 (lvar-value element-type)))
626 (sb!xc:upgraded-array-element-type
627 (lvar-value element-type)))
629 ,(make-list rank :initial-element '*))))
630 `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank))
631 (data (make-array ,total-size
633 '(:element-type element-type))
634 ,@(when initial-element
635 '(:initial-element initial-element)))))
636 ,@(when initial-contents
637 ;; FIXME: This is could be open coded at least a bit too
638 `((sb!impl::fill-data-vector data ',dims initial-contents)))
639 (setf (%array-fill-pointer header) ,total-size)
640 (setf (%array-fill-pointer-p header) nil)
641 (setf (%array-available-elements header) ,total-size)
642 (setf (%array-data-vector header) data)
643 (setf (%array-displaced-p header) nil)
644 (setf (%array-displaced-from header) nil)
646 (mapcar (lambda (dim)
647 `(setf (%array-dimension header ,(incf axis))
650 (truly-the ,spec header)))))))
652 (deftransform make-array ((dims &key element-type initial-element initial-contents)
654 (:element-type (constant-arg *))
656 (:initial-contents *))
659 (transform-make-array-vector dims
665 ;;;; miscellaneous properties of arrays
667 ;;; Transforms for various array properties. If the property is know
668 ;;; at compile time because of a type spec, use that constant value.
670 ;;; Most of this logic may end up belonging in code/late-type.lisp;
671 ;;; however, here we also need the -OR-GIVE-UP for the transforms, and
672 ;;; maybe this is just too sloppy for actual type logic. -- CSR,
674 (defun array-type-dimensions-or-give-up (type)
675 (labels ((maybe-array-type-dimensions (type)
678 (array-type-dimensions type))
680 (let* ((types (remove nil (mapcar #'maybe-array-type-dimensions
681 (union-type-types type))))
682 (result (car types)))
683 (dolist (other (cdr types) result)
684 (unless (equal result other)
685 (give-up-ir1-transform
686 "~@<dimensions of arrays in union type ~S do not match~:@>"
687 (type-specifier type))))))
689 (let* ((types (remove nil (mapcar #'maybe-array-type-dimensions
690 (intersection-type-types type))))
691 (result (car types)))
692 (dolist (other (cdr types) result)
693 (unless (equal result other)
695 "~@<dimensions of arrays in intersection type ~S do not match~:@>"
696 (type-specifier type)))))))))
697 (or (maybe-array-type-dimensions type)
698 (give-up-ir1-transform
699 "~@<don't know how to extract array dimensions from type ~S~:@>"
700 (type-specifier type)))))
702 (defun conservative-array-type-complexp (type)
704 (array-type (array-type-complexp type))
706 (let ((types (union-type-types type)))
707 (aver (> (length types) 1))
708 (let ((result (conservative-array-type-complexp (car types))))
709 (dolist (type (cdr types) result)
710 (unless (eq (conservative-array-type-complexp type) result)
711 (return-from conservative-array-type-complexp :maybe))))))
712 ;; FIXME: intersection type
715 ;;; If we can tell the rank from the type info, use it instead.
716 (deftransform array-rank ((array))
717 (let ((array-type (lvar-type array)))
718 (let ((dims (array-type-dimensions-or-give-up array-type)))
721 ((eq t (array-type-complexp array-type))
722 '(%array-rank array))
724 `(if (array-header-p array)
728 ;;; If we know the dimensions at compile time, just use it. Otherwise,
729 ;;; if we can tell that the axis is in bounds, convert to
730 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
731 ;;; (if it's simple and a vector).
732 (deftransform array-dimension ((array axis)
734 (unless (constant-lvar-p axis)
735 (give-up-ir1-transform "The axis is not constant."))
736 ;; Dimensions may change thanks to ADJUST-ARRAY, so we need the
737 ;; conservative type.
738 (let ((array-type (lvar-conservative-type array))
739 (axis (lvar-value axis)))
740 (let ((dims (array-type-dimensions-or-give-up array-type)))
742 (give-up-ir1-transform
743 "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
744 (unless (> (length dims) axis)
745 (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
748 (let ((dim (nth axis dims)))
749 (cond ((integerp dim)
752 (ecase (conservative-array-type-complexp array-type)
754 '(%array-dimension array 0))
756 '(vector-length array))
758 `(if (array-header-p array)
759 (%array-dimension array axis)
760 (vector-length array)))))
762 '(%array-dimension array axis)))))))
764 ;;; If the length has been declared and it's simple, just return it.
765 (deftransform length ((vector)
766 ((simple-array * (*))))
767 (let ((type (lvar-type vector)))
768 (let ((dims (array-type-dimensions-or-give-up type)))
769 (unless (and (listp dims) (integerp (car dims)))
770 (give-up-ir1-transform
771 "Vector length is unknown, must call LENGTH at runtime."))
774 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
775 ;;; simple, it will extract the length slot from the vector. It it's
776 ;;; complex, it will extract the fill pointer slot from the array
778 (deftransform length ((vector) (vector))
779 '(vector-length vector))
781 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
782 ;;; compile-time constant.
783 (deftransform vector-length ((vector))
784 (let ((vtype (lvar-type vector)))
785 (let ((dim (first (array-type-dimensions-or-give-up vtype))))
787 (give-up-ir1-transform))
788 (when (conservative-array-type-complexp vtype)
789 (give-up-ir1-transform))
792 ;;; Again, if we can tell the results from the type, just use it.
793 ;;; Otherwise, if we know the rank, convert into a computation based
794 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
795 ;;; multiplications because we know that the total size must be an
797 (deftransform array-total-size ((array)
799 (let ((array-type (lvar-type array)))
800 (let ((dims (array-type-dimensions-or-give-up array-type)))
802 (give-up-ir1-transform "can't tell the rank at compile time"))
804 (do ((form 1 `(truly-the index
805 (* (array-dimension array ,i) ,form)))
807 ((= i (length dims)) form))
808 (reduce #'* dims)))))
810 ;;; Only complex vectors have fill pointers.
811 (deftransform array-has-fill-pointer-p ((array))
812 (let ((array-type (lvar-type array)))
813 (let ((dims (array-type-dimensions-or-give-up array-type)))
814 (if (and (listp dims) (not (= (length dims) 1)))
816 (ecase (conservative-array-type-complexp array-type)
822 (give-up-ir1-transform
823 "The array type is ambiguous; must call ~
824 ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
826 ;;; Primitive used to verify indices into arrays. If we can tell at
827 ;;; compile-time or we are generating unsafe code, don't bother with
829 (deftransform %check-bound ((array dimension index) * * :node node)
830 (cond ((policy node (= insert-array-bounds-checks 0))
832 ((not (constant-lvar-p dimension))
833 (give-up-ir1-transform))
835 (let ((dim (lvar-value dimension)))
836 ;; FIXME: Can SPEED > SAFETY weaken this check to INTEGER?
837 `(the (integer 0 (,dim)) index)))))
841 ;;; This checks to see whether the array is simple and the start and
842 ;;; end are in bounds. If so, it proceeds with those values.
843 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
844 ;;; may be further optimized.
846 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
847 ;;; START-VAR and END-VAR to the start and end of the designated
848 ;;; portion of the data vector. SVALUE and EVALUE are any start and
849 ;;; end specified to the original operation, and are factored into the
850 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
851 ;;; offset of all displacements encountered, and does not include
854 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
855 ;;; forced to be inline, overriding the ordinary judgment of the
856 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
857 ;;; fairly picky about their arguments, figuring that if you haven't
858 ;;; bothered to get all your ducks in a row, you probably don't care
859 ;;; that much about speed anyway! But in some cases it makes sense to
860 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
861 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
862 ;;; sense to use FORCE-INLINE option in that case.
863 (def!macro with-array-data (((data-var array &key offset-var)
864 (start-var &optional (svalue 0))
865 (end-var &optional (evalue nil))
866 &key force-inline check-fill-pointer)
869 (once-only ((n-array array)
870 (n-svalue `(the index ,svalue))
871 (n-evalue `(the (or index null) ,evalue)))
872 (let ((check-bounds (policy env (plusp insert-array-bounds-checks))))
873 `(multiple-value-bind (,data-var
876 ,@(when offset-var `(,offset-var)))
877 (if (not (array-header-p ,n-array))
878 (let ((,n-array ,n-array))
879 (declare (type (simple-array * (*)) ,n-array))
880 ,(once-only ((n-len (if check-fill-pointer
882 `(array-total-size ,n-array)))
883 (n-end `(or ,n-evalue ,n-len)))
885 `(if (<= 0 ,n-svalue ,n-end ,n-len)
886 (values ,n-array ,n-svalue ,n-end 0)
887 ,(if check-fill-pointer
888 `(sequence-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)
889 `(array-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)))
890 `(values ,n-array ,n-svalue ,n-end 0))))
892 `(%with-array-data-macro ,n-array ,n-svalue ,n-evalue
893 :check-bounds ,check-bounds
894 :check-fill-pointer ,check-fill-pointer)
895 (if check-fill-pointer
896 `(%with-array-data/fp ,n-array ,n-svalue ,n-evalue)
897 `(%with-array-data ,n-array ,n-svalue ,n-evalue))))
900 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
901 ;;; DEFTRANSFORMs and DEFUNs.
902 (def!macro %with-array-data-macro (array
909 (with-unique-names (size defaulted-end data cumulative-offset)
910 `(let* ((,size ,(if check-fill-pointer
912 `(array-total-size ,array)))
913 (,defaulted-end (or ,end ,size)))
915 `((unless (<= ,start ,defaulted-end ,size)
916 ,(if check-fill-pointer
917 `(sequence-bounding-indices-bad-error ,array ,start ,end)
918 `(array-bounding-indices-bad-error ,array ,start ,end)))))
919 (do ((,data ,array (%array-data-vector ,data))
920 (,cumulative-offset 0
921 (+ ,cumulative-offset
922 (%array-displacement ,data))))
923 ((not (array-header-p ,data))
924 (values (the (simple-array ,element-type 1) ,data)
925 (the index (+ ,cumulative-offset ,start))
926 (the index (+ ,cumulative-offset ,defaulted-end))
927 (the index ,cumulative-offset)))
928 (declare (type index ,cumulative-offset))))))
930 (defun transform-%with-array-data/muble (array node check-fill-pointer)
931 (let ((element-type (upgraded-element-type-specifier-or-give-up array))
932 (type (lvar-type array))
933 (check-bounds (policy node (plusp insert-array-bounds-checks))))
934 (if (and (array-type-p type)
935 (not (array-type-complexp type))
936 (listp (array-type-dimensions type))
937 (not (null (cdr (array-type-dimensions type)))))
938 ;; If it's a simple multidimensional array, then just return
939 ;; its data vector directly rather than going through
940 ;; %WITH-ARRAY-DATA-MACRO. SBCL doesn't generally generate
941 ;; code that would use this currently, but we have encouraged
942 ;; users to use WITH-ARRAY-DATA and we may use it ourselves at
943 ;; some point in the future for optimized libraries or
946 `(let* ((data (truly-the (simple-array ,element-type (*))
947 (%array-data-vector array)))
949 (real-end (or end len)))
950 (unless (<= 0 start data-end lend)
951 (sequence-bounding-indices-bad-error array start end))
952 (values data 0 real-end 0))
953 `(let ((data (truly-the (simple-array ,element-type (*))
954 (%array-data-vector array))))
955 (values data 0 (or end (length data)) 0)))
956 `(%with-array-data-macro array start end
957 :check-fill-pointer ,check-fill-pointer
958 :check-bounds ,check-bounds
959 :element-type ,element-type))))
961 ;; It might very well be reasonable to allow general ARRAY here, I
962 ;; just haven't tried to understand the performance issues involved.
963 ;; -- WHN, and also CSR 2002-05-26
964 (deftransform %with-array-data ((array start end)
965 ((or vector simple-array) index (or index null) t)
968 :policy (> speed space))
969 "inline non-SIMPLE-vector-handling logic"
970 (transform-%with-array-data/muble array node nil))
971 (deftransform %with-array-data/fp ((array start end)
972 ((or vector simple-array) index (or index null) t)
975 :policy (> speed space))
976 "inline non-SIMPLE-vector-handling logic"
977 (transform-%with-array-data/muble array node t))
981 ;;; We convert all typed array accessors into AREF and %ASET with type
982 ;;; assertions on the array.
983 (macrolet ((define-bit-frob (reffer setter simplep)
985 (define-source-transform ,reffer (a &rest i)
986 `(aref (the (,',(if simplep 'simple-array 'array)
988 ,(mapcar (constantly '*) i))
990 (define-source-transform ,setter (a &rest i)
991 `(%aset (the (,',(if simplep 'simple-array 'array)
993 ,(cdr (mapcar (constantly '*) i)))
995 (define-bit-frob sbit %sbitset t)
996 (define-bit-frob bit %bitset nil))
997 (macrolet ((define-frob (reffer setter type)
999 (define-source-transform ,reffer (a i)
1000 `(aref (the ,',type ,a) ,i))
1001 (define-source-transform ,setter (a i v)
1002 `(%aset (the ,',type ,a) ,i ,v)))))
1003 (define-frob svref %svset simple-vector)
1004 (define-frob schar %scharset simple-string)
1005 (define-frob char %charset string))
1007 (macrolet (;; This is a handy macro for computing the row-major index
1008 ;; given a set of indices. We wrap each index with a call
1009 ;; to %CHECK-BOUND to ensure that everything works out
1010 ;; correctly. We can wrap all the interior arithmetic with
1011 ;; TRULY-THE INDEX because we know the resultant
1012 ;; row-major index must be an index.
1013 (with-row-major-index ((array indices index &optional new-value)
1015 `(let (n-indices dims)
1016 (dotimes (i (length ,indices))
1017 (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
1018 (push (make-symbol (format nil "DIM-~D" i)) dims))
1019 (setf n-indices (nreverse n-indices))
1020 (setf dims (nreverse dims))
1021 `(lambda (,',array ,@n-indices
1022 ,@',(when new-value (list new-value)))
1023 (let* (,@(let ((,index -1))
1024 (mapcar (lambda (name)
1025 `(,name (array-dimension
1032 (do* ((dims dims (cdr dims))
1033 (indices n-indices (cdr indices))
1034 (last-dim nil (car dims))
1035 (form `(%check-bound ,',array
1047 ((null (cdr dims)) form)))))
1050 ;; Just return the index after computing it.
1051 (deftransform array-row-major-index ((array &rest indices))
1052 (with-row-major-index (array indices index)
1055 ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
1056 ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
1057 ;; expression for the row major index.
1058 (deftransform aref ((array &rest indices))
1059 (with-row-major-index (array indices index)
1060 (hairy-data-vector-ref array index)))
1062 (deftransform %aset ((array &rest stuff))
1063 (let ((indices (butlast stuff)))
1064 (with-row-major-index (array indices index new-value)
1065 (hairy-data-vector-set array index new-value)))))
1067 ;; For AREF of vectors we do the bounds checking in the callee. This
1068 ;; lets us do a significantly more efficient check for simple-arrays
1069 ;; without bloating the code. If we already know the type of the array
1070 ;; with sufficient precision, skip directly to DATA-VECTOR-REF.
1071 (deftransform aref ((array index) (t t) * :node node)
1072 (let* ((type (lvar-type array))
1073 (element-ctype (array-type-upgraded-element-type type)))
1075 ((and (array-type-p type)
1076 (null (array-type-complexp type))
1077 (not (eql element-ctype *wild-type*))
1078 (eql (length (array-type-dimensions type)) 1))
1079 (let* ((declared-element-ctype (array-type-declared-element-type type))
1081 `(data-vector-ref array
1082 (%check-bound array (array-dimension array 0) index))))
1083 (if (type= declared-element-ctype element-ctype)
1085 `(the ,(type-specifier declared-element-ctype) ,bare-form))))
1086 ((policy node (zerop insert-array-bounds-checks))
1087 `(hairy-data-vector-ref array index))
1088 (t `(hairy-data-vector-ref/check-bounds array index)))))
1090 (deftransform %aset ((array index new-value) (t t t) * :node node)
1091 (if (policy node (zerop insert-array-bounds-checks))
1092 `(hairy-data-vector-set array index new-value)
1093 `(hairy-data-vector-set/check-bounds array index new-value)))
1095 ;;; But if we find out later that there's some useful type information
1096 ;;; available, switch back to the normal one to give other transforms
1098 (macrolet ((define (name transform-to extra extra-type)
1099 (declare (ignore extra-type))
1100 `(deftransform ,name ((array index ,@extra))
1101 (let* ((type (lvar-type array))
1102 (element-type (array-type-upgraded-element-type type))
1103 (declared-type (type-specifier
1104 (array-type-declared-element-type type))))
1105 ;; If an element type has been declared, we want to
1106 ;; use that information it for type checking (even
1107 ;; if the access can't be optimized due to the array
1108 ;; not being simple).
1109 (when (and (eql element-type *wild-type*)
1110 ;; This type logic corresponds to the special
1111 ;; case for strings in HAIRY-DATA-VECTOR-REF
1112 ;; (generic/vm-tran.lisp)
1113 (not (csubtypep type (specifier-type 'simple-string))))
1114 (when (or (not (array-type-p type))
1115 ;; If it's a simple array, we might be able
1116 ;; to inline the access completely.
1117 (not (null (array-type-complexp type))))
1118 (give-up-ir1-transform
1119 "Upgraded element type of array is not known at compile time.")))
1121 ``(truly-the ,declared-type
1122 (,',transform-to array
1124 (array-dimension array 0)
1126 (the ,declared-type ,@',extra)))
1127 ``(the ,declared-type
1128 (,',transform-to array
1130 (array-dimension array 0)
1132 (define hairy-data-vector-ref/check-bounds
1133 hairy-data-vector-ref nil nil)
1134 (define hairy-data-vector-set/check-bounds
1135 hairy-data-vector-set (new-value) (*)))
1137 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
1138 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
1139 ;;; array total size.
1140 (deftransform row-major-aref ((array index))
1141 `(hairy-data-vector-ref array
1142 (%check-bound array (array-total-size array) index)))
1143 (deftransform %set-row-major-aref ((array index new-value))
1144 `(hairy-data-vector-set array
1145 (%check-bound array (array-total-size array) index)
1148 ;;;; bit-vector array operation canonicalization
1150 ;;;; We convert all bit-vector operations to have the result array
1151 ;;;; specified. This allows any result allocation to be open-coded,
1152 ;;;; and eliminates the need for any VM-dependent transforms to handle
1155 (macrolet ((def (fun)
1157 (deftransform ,fun ((bit-array-1 bit-array-2
1158 &optional result-bit-array)
1159 (bit-vector bit-vector &optional null) *
1160 :policy (>= speed space))
1161 `(,',fun bit-array-1 bit-array-2
1162 (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1163 ;; If result is T, make it the first arg.
1164 (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
1165 (bit-vector bit-vector (eql t)) *)
1166 `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
1178 ;;; Similar for BIT-NOT, but there is only one arg...
1179 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
1180 (bit-vector &optional null) *
1181 :policy (>= speed space))
1182 '(bit-not bit-array-1
1183 (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1184 (deftransform bit-not ((bit-array-1 result-bit-array)
1185 (bit-vector (eql t)))
1186 '(bit-not bit-array-1 bit-array-1))
1188 ;;; Pick off some constant cases.
1189 (defoptimizer (array-header-p derive-type) ((array))
1190 (let ((type (lvar-type array)))
1191 (cond ((not (array-type-p type))
1192 ;; FIXME: use analogue of ARRAY-TYPE-DIMENSIONS-OR-GIVE-UP
1195 (let ((dims (array-type-dimensions type)))
1196 (cond ((csubtypep type (specifier-type '(simple-array * (*))))
1198 (specifier-type 'null))
1199 ((and (listp dims) (/= (length dims) 1))
1200 ;; multi-dimensional array, will have a header
1201 (specifier-type '(eql t)))
1202 ((eql (array-type-complexp type) t)
1203 (specifier-type '(eql t)))