1.0.28.71: two regressions from the 1.0.28. series
[sbcl.git] / src / compiler / array-tran.lisp
1 ;;;; array-specific optimizers and transforms
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
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.
11
12 (in-package "SB!C")
13 \f
14 ;;;; utilities for optimizing array operations
15
16 ;;; Return UPGRADED-ARRAY-ELEMENT-TYPE for LVAR, or do
17 ;;; GIVE-UP-IR1-TRANSFORM if the upgraded element type can't be
18 ;;; determined.
19 (defun upgraded-element-type-specifier-or-give-up (lvar)
20   (let* ((element-ctype (extract-upgraded-element-type lvar))
21          (element-type-specifier (type-specifier element-ctype)))
22     (if (eq element-type-specifier '*)
23         (give-up-ir1-transform
24          "upgraded array element type not known at compile time")
25         element-type-specifier)))
26
27 ;;; Array access functions return an object from the array, hence its type is
28 ;;; going to be the array upgraded element type. Secondary return value is the
29 ;;; known supertype of the upgraded-array-element-type, if if the exact
30 ;;; U-A-E-T is not known. (If it is NIL, the primary return value is as good
31 ;;; as it gets.)
32 (defun extract-upgraded-element-type (array)
33   (let ((type (lvar-type array)))
34     (cond
35       ;; Note that this IF mightn't be satisfied even if the runtime
36       ;; value is known to be a subtype of some specialized ARRAY, because
37       ;; we can have values declared e.g. (AND SIMPLE-VECTOR UNKNOWN-TYPE),
38       ;; which are represented in the compiler as INTERSECTION-TYPE, not
39       ;; array type.
40       ((array-type-p type)
41        (values (array-type-specialized-element-type type) nil))
42       ;; fix for bug #396. This type logic corresponds to the special case for
43       ;; strings in HAIRY-DATA-VECTOR-REF (generic/vm-tran.lisp)
44       ((csubtypep type (specifier-type 'string))
45        (cond
46          ((csubtypep type (specifier-type '(array character (*))))
47           (values (specifier-type 'character) nil))
48          #!+sb-unicode
49          ((csubtypep type (specifier-type '(array base-char (*))))
50           (values (specifier-type 'base-char) nil))
51          ((csubtypep type (specifier-type '(array nil (*))))
52           (values *empty-type* nil))
53          (t
54           ;; See KLUDGE below.
55           (values *wild-type* (specifier-type 'character)))))
56       (t
57        ;; KLUDGE: there is no good answer here, but at least
58        ;; *wild-type* won't cause HAIRY-DATA-VECTOR-{REF,SET} to be
59        ;; erroneously optimized (see generic/vm-tran.lisp) -- CSR,
60        ;; 2002-08-21
61        (values *wild-type* nil)))))
62
63 (defun extract-declared-element-type (array)
64   (let ((type (lvar-type array)))
65     (if (array-type-p type)
66         (array-type-element-type type)
67         *wild-type*)))
68
69 ;;; The ``new-value'' for array setters must fit in the array, and the
70 ;;; return type is going to be the same as the new-value for SETF
71 ;;; functions.
72 (defun assert-new-value-type (new-value array)
73   (let ((type (lvar-type array)))
74     (when (array-type-p type)
75       (assert-lvar-type
76        new-value
77        (array-type-specialized-element-type type)
78        (lexenv-policy (node-lexenv (lvar-dest new-value))))))
79   (lvar-type new-value))
80
81 (defun assert-array-complex (array)
82   (assert-lvar-type
83    array
84    (make-array-type :complexp t
85                     :element-type *wild-type*)
86    (lexenv-policy (node-lexenv (lvar-dest array))))
87   nil)
88
89 ;;; Return true if ARG is NIL, or is a constant-lvar whose
90 ;;; value is NIL, false otherwise.
91 (defun unsupplied-or-nil (arg)
92   (declare (type (or lvar null) arg))
93   (or (not arg)
94       (and (constant-lvar-p arg)
95            (not (lvar-value arg)))))
96 \f
97 ;;;; DERIVE-TYPE optimizers
98
99 ;;; Array operations that use a specific number of indices implicitly
100 ;;; assert that the array is of that rank.
101 (defun assert-array-rank (array rank)
102   (assert-lvar-type
103    array
104    (specifier-type `(array * ,(make-list rank :initial-element '*)))
105    (lexenv-policy (node-lexenv (lvar-dest array)))))
106
107 (defun derive-aref-type (array)
108   (multiple-value-bind (uaet other) (extract-upgraded-element-type array)
109     (or other uaet)))
110
111 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
112   (assert-array-rank array (length indices))
113   *universal-type*)
114
115 (defoptimizer (aref derive-type) ((array &rest indices) node)
116   (assert-array-rank array (length indices))
117   (derive-aref-type array))
118
119 (defoptimizer (%aset derive-type) ((array &rest stuff))
120   (assert-array-rank array (1- (length stuff)))
121   (assert-new-value-type (car (last stuff)) array))
122
123 (macrolet ((define (name)
124              `(defoptimizer (,name derive-type) ((array index))
125                 (derive-aref-type array))))
126   (define hairy-data-vector-ref)
127   (define hairy-data-vector-ref/check-bounds)
128   (define data-vector-ref))
129
130 #!+(or x86 x86-64)
131 (defoptimizer (data-vector-ref-with-offset derive-type) ((array index offset))
132   (derive-aref-type array))
133
134 (macrolet ((define (name)
135              `(defoptimizer (,name derive-type) ((array index new-value))
136                 (assert-new-value-type new-value array))))
137   (define hairy-data-vector-set)
138   (define hairy-data-vector-set/check-bounds)
139   (define data-vector-set))
140
141 #!+(or x86 x86-64)
142 (defoptimizer (data-vector-set-with-offset derive-type) ((array index offset new-value))
143   (assert-new-value-type new-value array))
144
145 ;;; Figure out the type of the data vector if we know the argument
146 ;;; element type.
147 (defun derive-%with-array-data/mumble-type (array)
148   (let ((atype (lvar-type array)))
149     (when (array-type-p atype)
150       (specifier-type
151        `(simple-array ,(type-specifier
152                         (array-type-specialized-element-type atype))
153                       (*))))))
154 (defoptimizer (%with-array-data derive-type) ((array start end))
155   (derive-%with-array-data/mumble-type array))
156 (defoptimizer (%with-array-data/fp derive-type) ((array start end))
157   (derive-%with-array-data/mumble-type array))
158
159 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
160   (assert-array-rank array (length indices))
161   *universal-type*)
162
163 (defoptimizer (row-major-aref derive-type) ((array index))
164   (derive-aref-type array))
165
166 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
167   (assert-new-value-type new-value array))
168
169 (defoptimizer (make-array derive-type)
170               ((dims &key initial-element element-type initial-contents
171                 adjustable fill-pointer displaced-index-offset displaced-to))
172   (let ((simple (and (unsupplied-or-nil adjustable)
173                      (unsupplied-or-nil displaced-to)
174                      (unsupplied-or-nil fill-pointer))))
175     (or (careful-specifier-type
176          `(,(if simple 'simple-array 'array)
177             ,(cond ((not element-type) t)
178                    ((constant-lvar-p element-type)
179                     (let ((ctype (careful-specifier-type
180                                   (lvar-value element-type))))
181                       (cond
182                         ((or (null ctype) (unknown-type-p ctype)) '*)
183                         (t (sb!xc:upgraded-array-element-type
184                             (lvar-value element-type))))))
185                    (t
186                     '*))
187             ,(cond ((constant-lvar-p dims)
188                     (let* ((val (lvar-value dims))
189                            (cdims (if (listp val) val (list val))))
190                       (if simple
191                           cdims
192                           (length cdims))))
193                    ((csubtypep (lvar-type dims)
194                                (specifier-type 'integer))
195                     '(*))
196                    (t
197                     '*))))
198         (specifier-type 'array))))
199
200 ;;; Complex array operations should assert that their array argument
201 ;;; is complex.  In SBCL, vectors with fill-pointers are complex.
202 (defoptimizer (fill-pointer derive-type) ((vector))
203   (assert-array-complex vector))
204 (defoptimizer (%set-fill-pointer derive-type) ((vector index))
205   (declare (ignorable index))
206   (assert-array-complex vector))
207
208 (defoptimizer (vector-push derive-type) ((object vector))
209   (declare (ignorable object))
210   (assert-array-complex vector))
211 (defoptimizer (vector-push-extend derive-type)
212     ((object vector &optional index))
213   (declare (ignorable object index))
214   (assert-array-complex vector))
215 (defoptimizer (vector-pop derive-type) ((vector))
216   (assert-array-complex vector))
217 \f
218 ;;;; constructors
219
220 ;;; Convert VECTOR into a MAKE-ARRAY.
221 (define-source-transform vector (&rest elements)
222   `(make-array ,(length elements) :initial-contents (list ,@elements)))
223
224 ;;; Just convert it into a MAKE-ARRAY.
225 (deftransform make-string ((length &key
226                                    (element-type 'character)
227                                    (initial-element
228                                     #.*default-init-char-form*)))
229   `(the simple-string (make-array (the index length)
230                        :element-type element-type
231                        ,@(when initial-element
232                            '(:initial-element initial-element)))))
233
234 ;;; Prevent open coding DIMENSION and :INITIAL-CONTENTS arguments,
235 ;;; so that we can pick them apart.
236 (define-source-transform make-array (&whole form dimensions &rest keyargs
237                                      &environment env)
238   (if (and (fun-lexically-notinline-p 'list)
239            (fun-lexically-notinline-p 'vector))
240       (values nil t)
241       `(locally (declare (notinline list vector))
242          ;; Transform '(3) style dimensions to integer args directly.
243          ,(if (sb!xc:constantp dimensions env)
244               (let ((dims (constant-form-value dimensions env)))
245                 (if (and (listp dims) (= 1 (length dims)))
246                     `(make-array ',(car dims) ,@keyargs)
247                     form))
248               form))))
249
250 ;;; This baby is a bit of a monster, but it takes care of any MAKE-ARRAY
251 ;;; call which creates a vector with a known element type -- and tries
252 ;;; to do a good job with all the different ways it can happen.
253 (defun transform-make-array-vector (length element-type initial-element
254                                     initial-contents call)
255   (aver (or (not element-type) (constant-lvar-p element-type)))
256   (let* ((c-length (when (constant-lvar-p length)
257                      (lvar-value length)))
258          (elt-spec (if element-type
259                        (lvar-value element-type)
260                        t))
261          (elt-ctype (ir1-transform-specifier-type elt-spec))
262          (saetp (if (unknown-type-p elt-ctype)
263                     (give-up-ir1-transform "~S is an unknown type: ~S"
264                                            :element-type elt-spec)
265                     (find-saetp-by-ctype elt-ctype)))
266          (default-initial-element (sb!vm:saetp-initial-element-default saetp))
267          (n-bits (sb!vm:saetp-n-bits saetp))
268          (typecode (sb!vm:saetp-typecode saetp))
269          (n-pad-elements (sb!vm:saetp-n-pad-elements saetp))
270          (n-words-form
271           (if c-length
272               (ceiling (* (+ c-length n-pad-elements) n-bits)
273                        sb!vm:n-word-bits)
274               (let ((padded-length-form (if (zerop n-pad-elements)
275                                             'length
276                                             `(+ length ,n-pad-elements))))
277                 (cond
278                   ((= n-bits 0) 0)
279                   ((>= n-bits sb!vm:n-word-bits)
280                    `(* ,padded-length-form
281                        ;; i.e., not RATIO
282                        ,(the fixnum (/ n-bits sb!vm:n-word-bits))))
283                   (t
284                    (let ((n-elements-per-word (/ sb!vm:n-word-bits n-bits)))
285                      (declare (type index n-elements-per-word)) ; i.e., not RATIO
286                      `(ceiling ,padded-length-form ,n-elements-per-word)))))))
287          (result-spec
288           `(simple-array ,(sb!vm:saetp-specifier saetp) (,(or c-length '*))))
289          (alloc-form
290           `(truly-the ,result-spec
291                       (allocate-vector ,typecode (the index length) ,n-words-form))))
292     (cond ((and initial-element initial-contents)
293            (abort-ir1-transform "Both ~S and ~S specified."
294                                 :initial-contents :initial-element))
295           ;; :INITIAL-CONTENTS (LIST ...), (VECTOR ...) and `(1 1 ,x) with a
296           ;; constant LENGTH.
297           ((and initial-contents c-length
298                 (lvar-matches initial-contents
299                               :fun-names '(list vector sb!impl::backq-list)
300                               :arg-count c-length))
301            (let ((parameters (eliminate-keyword-args
302                               call 1 '((:element-type element-type)
303                                        (:initial-contents initial-contents))))
304                  (elt-vars (make-gensym-list c-length))
305                  (lambda-list '(length)))
306              (splice-fun-args initial-contents :any c-length)
307              (dolist (p parameters)
308                (setf lambda-list
309                      (append lambda-list
310                              (if (eq p 'initial-contents)
311                                  elt-vars
312                                  (list p)))))
313              `(lambda ,lambda-list
314                 (declare (type ,elt-spec ,@elt-vars)
315                          (ignorable ,@lambda-list))
316                 (truly-the ,result-spec
317                  (initialize-vector ,alloc-form ,@elt-vars)))))
318           ;; constant :INITIAL-CONTENTS and LENGTH
319           ((and initial-contents c-length (constant-lvar-p initial-contents))
320            (let ((contents (lvar-value initial-contents)))
321              (unless (= c-length (length contents))
322                (abort-ir1-transform "~S has ~S elements, vector length is ~S."
323                                     :initial-contents (length contents) c-length))
324              (let ((parameters (eliminate-keyword-args
325                                 call 1 '((:element-type element-type)
326                                          (:initial-contents initial-contents)))))
327                `(lambda (length ,@parameters)
328                   (declare (ignorable ,@parameters))
329                   (truly-the ,result-spec
330                    (initialize-vector ,alloc-form
331                                       ,@(map 'list (lambda (elt)
332                                                      `(the ,elt-spec ',elt))
333                                              contents)))))))
334           ;; any other :INITIAL-CONTENTS
335           (initial-contents
336            (let ((parameters (eliminate-keyword-args
337                               call 1 '((:element-type element-type)
338                                        (:initial-contents initial-contents)))))
339              `(lambda (length ,@parameters)
340                 (declare (ignorable ,@parameters))
341                 (unless (= length (length initial-contents))
342                   (error "~S has ~S elements, vector length is ~S."
343                          :initial-contents (length initial-contents) length))
344                 (truly-the ,result-spec
345                            (replace ,alloc-form initial-contents)))))
346           ;; :INITIAL-ELEMENT, not EQL to the default
347           ((and initial-element
348                 (or (not (constant-lvar-p initial-element))
349                     (not (eql default-initial-element (lvar-value initial-element)))))
350            (let ((parameters (eliminate-keyword-args
351                               call 1 '((:element-type element-type)
352                                        (:initial-element initial-element))))
353                  (init (if (constant-lvar-p initial-element)
354                            (lvar-value initial-element)
355                            'initial-element)))
356              `(lambda (length ,@parameters)
357                 (declare (ignorable ,@parameters))
358                 (truly-the ,result-spec
359                            (fill ,alloc-form (the ,elt-spec ,init))))))
360           ;; just :ELEMENT-TYPE, or maybe with :INITIAL-ELEMENT EQL to the
361           ;; default
362           (t
363            #-sb-xc-host
364            (unless (ctypep default-initial-element elt-ctype)
365              ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
366              ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
367              ;; INITIAL-ELEMENT is not supplied, the consequences of later
368              ;; reading an uninitialized element of new-array are undefined,"
369              ;; so this could be legal code as long as the user plans to
370              ;; write before he reads, and if he doesn't we're free to do
371              ;; anything we like. But in case the user doesn't know to write
372              ;; elements before he reads elements (or to read manuals before
373              ;; he writes code:-), we'll signal a STYLE-WARNING in case he
374              ;; didn't realize this.
375              (if initial-element
376                  (compiler-warn "~S ~S is not a ~S"
377                                 :initial-element default-initial-element
378                                 elt-spec)
379                  (compiler-style-warn "The default initial element ~S is not a ~S."
380                                       default-initial-element
381                                       elt-spec)))
382            (let ((parameters (eliminate-keyword-args
383                               call 1 '((:element-type element-type)))))
384              `(lambda (length ,@parameters)
385                 (declare (ignorable ,@parameters))
386                 ,alloc-form))))))
387
388 (deftransform make-array ((dims &key
389                                 element-type initial-element initial-contents)
390                           (integer &key
391                                    (:element-type (constant-arg *))
392                                    (:initial-element *)
393                                    (:initial-contents *))
394                           *
395                           :node call)
396   (transform-make-array-vector dims
397                                element-type
398                                initial-element
399                                initial-contents
400                                call))
401
402 ;;; The list type restriction does not ensure that the result will be a
403 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
404 ;;; and displaced-to keywords ensures that it will be simple.
405 ;;;
406 ;;; FIXME: should we generalize this transform to non-simple (though
407 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
408 ;;; deal with those? Maybe when the DEFTRANSFORM
409 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
410 ;;; CSR, 2002-07-01
411 (deftransform make-array ((dims &key
412                                 element-type initial-element initial-contents)
413                           (list &key
414                                 (:element-type (constant-arg *))
415                                 (:initial-element *)
416                                 (:initial-contents *))
417                           *
418                           :node call)
419   (block make-array
420     (when (lvar-matches dims :fun-names '(list) :arg-count 1)
421       (let ((length (car (splice-fun-args dims :any 1))))
422         (return-from make-array
423           (transform-make-array-vector length
424                                        element-type
425                                        initial-element
426                                        initial-contents
427                                        call))))
428     (unless (constant-lvar-p dims)
429       (give-up-ir1-transform
430        "The dimension list is not constant; cannot open code array creation."))
431     (let ((dims (lvar-value dims)))
432       (unless (every #'integerp dims)
433         (give-up-ir1-transform
434          "The dimension list contains something other than an integer: ~S"
435          dims))
436       (if (= (length dims) 1)
437           `(make-array ',(car dims)
438                        ,@(when element-type
439                                '(:element-type element-type))
440                        ,@(when initial-element
441                                '(:initial-element initial-element))
442                        ,@(when initial-contents
443                                '(:initial-contents initial-contents)))
444           (let* ((total-size (reduce #'* dims))
445                  (rank (length dims))
446                  (spec `(simple-array
447                          ,(cond ((null element-type) t)
448                                 ((and (constant-lvar-p element-type)
449                                       (ir1-transform-specifier-type
450                                        (lvar-value element-type)))
451                                  (sb!xc:upgraded-array-element-type
452                                   (lvar-value element-type)))
453                                 (t '*))
454                          ,(make-list rank :initial-element '*))))
455             `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank))
456                    (data (make-array ,total-size
457                                      ,@(when element-type
458                                              '(:element-type element-type))
459                                      ,@(when initial-element
460                                              '(:initial-element initial-element)))))
461                ,@(when initial-contents
462                        ;; FIXME: This is could be open coded at least a bit too
463                        `((sb!impl::fill-data-vector data ',dims initial-contents)))
464                (setf (%array-fill-pointer header) ,total-size)
465                (setf (%array-fill-pointer-p header) nil)
466                (setf (%array-available-elements header) ,total-size)
467                (setf (%array-data-vector header) data)
468                (setf (%array-displaced-p header) nil)
469                (setf (%array-displaced-from header) nil)
470                ,@(let ((axis -1))
471                       (mapcar (lambda (dim)
472                                 `(setf (%array-dimension header ,(incf axis))
473                                        ,dim))
474                               dims))
475                (truly-the ,spec header)))))))
476
477 (deftransform make-array ((dims &key initial-element element-type
478                                      adjustable fill-pointer)
479                           (t &rest *))
480   (when (null initial-element)
481     (give-up-ir1-transform))
482   (let* ((eltype (cond ((not element-type) t)
483                        ((not (constant-lvar-p element-type))
484                         (give-up-ir1-transform
485                          "ELEMENT-TYPE is not constant."))
486                        (t
487                         (lvar-value element-type))))
488          (eltype-type (ir1-transform-specifier-type eltype))
489          (saetp (find-if (lambda (saetp)
490                            (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
491                          sb!vm:*specialized-array-element-type-properties*))
492          (creation-form `(make-array dims
493                           :element-type ',(type-specifier (sb!vm:saetp-ctype saetp))
494                           ,@(when fill-pointer
495                                   '(:fill-pointer fill-pointer))
496                           ,@(when adjustable
497                                   '(:adjustable adjustable)))))
498
499     (unless saetp
500       (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
501
502     (cond ((and (constant-lvar-p initial-element)
503                 (eql (lvar-value initial-element)
504                      (sb!vm:saetp-initial-element-default saetp)))
505            creation-form)
506           (t
507            ;; error checking for target, disabled on the host because
508            ;; (CTYPE-OF #\Null) is not possible.
509            #-sb-xc-host
510            (when (constant-lvar-p initial-element)
511              (let ((value (lvar-value initial-element)))
512                (cond
513                  ((not (ctypep value (sb!vm:saetp-ctype saetp)))
514                   ;; this case will cause an error at runtime, so we'd
515                   ;; better WARN about it now.
516                   (warn 'array-initial-element-mismatch
517                         :format-control "~@<~S is not a ~S (which is the ~
518                                          ~S of ~S).~@:>"
519                         :format-arguments
520                         (list
521                          value
522                          (type-specifier (sb!vm:saetp-ctype saetp))
523                          'upgraded-array-element-type
524                          eltype)))
525                  ((not (ctypep value eltype-type))
526                   ;; this case will not cause an error at runtime, but
527                   ;; it's still worth STYLE-WARNing about.
528                   (compiler-style-warn "~S is not a ~S."
529                                        value eltype)))))
530            `(let ((array ,creation-form))
531              (multiple-value-bind (vector)
532                  (%data-vector-and-index array 0)
533                (fill vector (the ,(sb!vm:saetp-specifier saetp) initial-element)))
534              array)))))
535 \f
536 ;;;; miscellaneous properties of arrays
537
538 ;;; Transforms for various array properties. If the property is know
539 ;;; at compile time because of a type spec, use that constant value.
540
541 ;;; Most of this logic may end up belonging in code/late-type.lisp;
542 ;;; however, here we also need the -OR-GIVE-UP for the transforms, and
543 ;;; maybe this is just too sloppy for actual type logic.  -- CSR,
544 ;;; 2004-02-18
545 (defun array-type-dimensions-or-give-up (type)
546   (typecase type
547     (array-type (array-type-dimensions type))
548     (union-type
549      (let ((types (union-type-types type)))
550        ;; there are at least two types, right?
551        (aver (> (length types) 1))
552        (let ((result (array-type-dimensions-or-give-up (car types))))
553          (dolist (type (cdr types) result)
554            (unless (equal (array-type-dimensions-or-give-up type) result)
555              (give-up-ir1-transform))))))
556     ;; FIXME: intersection type [e.g. (and (array * (*)) (satisfies foo)) ]
557     (t (give-up-ir1-transform))))
558
559 (defun conservative-array-type-complexp (type)
560   (typecase type
561     (array-type (array-type-complexp type))
562     (union-type
563      (let ((types (union-type-types type)))
564        (aver (> (length types) 1))
565        (let ((result (conservative-array-type-complexp (car types))))
566          (dolist (type (cdr types) result)
567            (unless (eq (conservative-array-type-complexp type) result)
568              (return-from conservative-array-type-complexp :maybe))))))
569     ;; FIXME: intersection type
570     (t :maybe)))
571
572 ;;; If we can tell the rank from the type info, use it instead.
573 (deftransform array-rank ((array))
574   (let ((array-type (lvar-type array)))
575     (let ((dims (array-type-dimensions-or-give-up array-type)))
576       (cond ((listp dims)
577              (length dims))
578             ((eq t (array-type-complexp array-type))
579              '(%array-rank array))
580             (t
581              `(if (array-header-p array)
582                   (%array-rank array)
583                   1))))))
584
585 ;;; If we know the dimensions at compile time, just use it. Otherwise,
586 ;;; if we can tell that the axis is in bounds, convert to
587 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
588 ;;; (if it's simple and a vector).
589 (deftransform array-dimension ((array axis)
590                                (array index))
591   (unless (constant-lvar-p axis)
592     (give-up-ir1-transform "The axis is not constant."))
593   ;; Dimensions may change thanks to ADJUST-ARRAY, so we need the
594   ;; conservative type.
595   (let ((array-type (lvar-conservative-type array))
596         (axis (lvar-value axis)))
597     (let ((dims (array-type-dimensions-or-give-up array-type)))
598       (unless (listp dims)
599         (give-up-ir1-transform
600          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
601       (unless (> (length dims) axis)
602         (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
603                              dims
604                              axis))
605       (let ((dim (nth axis dims)))
606         (cond ((integerp dim)
607                dim)
608               ((= (length dims) 1)
609                (ecase (conservative-array-type-complexp array-type)
610                  ((t)
611                   '(%array-dimension array 0))
612                  ((nil)
613                   '(vector-length array))
614                  ((:maybe)
615                   `(if (array-header-p array)
616                        (%array-dimension array axis)
617                        (vector-length array)))))
618               (t
619                '(%array-dimension array axis)))))))
620
621 ;;; If the length has been declared and it's simple, just return it.
622 (deftransform length ((vector)
623                       ((simple-array * (*))))
624   (let ((type (lvar-type vector)))
625     (let ((dims (array-type-dimensions-or-give-up type)))
626       (unless (and (listp dims) (integerp (car dims)))
627         (give-up-ir1-transform
628          "Vector length is unknown, must call LENGTH at runtime."))
629       (car dims))))
630
631 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
632 ;;; simple, it will extract the length slot from the vector. It it's
633 ;;; complex, it will extract the fill pointer slot from the array
634 ;;; header.
635 (deftransform length ((vector) (vector))
636   '(vector-length vector))
637
638 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
639 ;;; compile-time constant.
640 (deftransform vector-length ((vector))
641   (let ((vtype (lvar-type vector)))
642     (let ((dim (first (array-type-dimensions-or-give-up vtype))))
643       (when (eq dim '*)
644         (give-up-ir1-transform))
645       (when (conservative-array-type-complexp vtype)
646         (give-up-ir1-transform))
647       dim)))
648
649 ;;; Again, if we can tell the results from the type, just use it.
650 ;;; Otherwise, if we know the rank, convert into a computation based
651 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
652 ;;; multiplications because we know that the total size must be an
653 ;;; INDEX.
654 (deftransform array-total-size ((array)
655                                 (array))
656   (let ((array-type (lvar-type array)))
657     (let ((dims (array-type-dimensions-or-give-up array-type)))
658       (unless (listp dims)
659         (give-up-ir1-transform "can't tell the rank at compile time"))
660       (if (member '* dims)
661           (do ((form 1 `(truly-the index
662                                    (* (array-dimension array ,i) ,form)))
663                (i 0 (1+ i)))
664               ((= i (length dims)) form))
665           (reduce #'* dims)))))
666
667 ;;; Only complex vectors have fill pointers.
668 (deftransform array-has-fill-pointer-p ((array))
669   (let ((array-type (lvar-type array)))
670     (let ((dims (array-type-dimensions-or-give-up array-type)))
671       (if (and (listp dims) (not (= (length dims) 1)))
672           nil
673           (ecase (conservative-array-type-complexp array-type)
674             ((t)
675              t)
676             ((nil)
677              nil)
678             ((:maybe)
679              (give-up-ir1-transform
680               "The array type is ambiguous; must call ~
681                ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
682
683 ;;; Primitive used to verify indices into arrays. If we can tell at
684 ;;; compile-time or we are generating unsafe code, don't bother with
685 ;;; the VOP.
686 (deftransform %check-bound ((array dimension index) * * :node node)
687   (cond ((policy node (= insert-array-bounds-checks 0))
688          'index)
689         ((not (constant-lvar-p dimension))
690          (give-up-ir1-transform))
691         (t
692          (let ((dim (lvar-value dimension)))
693            ;; FIXME: Can SPEED > SAFETY weaken this check to INTEGER?
694            `(the (integer 0 (,dim)) index)))))
695 \f
696 ;;;; WITH-ARRAY-DATA
697
698 ;;; This checks to see whether the array is simple and the start and
699 ;;; end are in bounds. If so, it proceeds with those values.
700 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
701 ;;; may be further optimized.
702 ;;;
703 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
704 ;;; START-VAR and END-VAR to the start and end of the designated
705 ;;; portion of the data vector. SVALUE and EVALUE are any start and
706 ;;; end specified to the original operation, and are factored into the
707 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
708 ;;; offset of all displacements encountered, and does not include
709 ;;; SVALUE.
710 ;;;
711 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
712 ;;; forced to be inline, overriding the ordinary judgment of the
713 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
714 ;;; fairly picky about their arguments, figuring that if you haven't
715 ;;; bothered to get all your ducks in a row, you probably don't care
716 ;;; that much about speed anyway! But in some cases it makes sense to
717 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
718 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
719 ;;; sense to use FORCE-INLINE option in that case.
720 (def!macro with-array-data (((data-var array &key offset-var)
721                              (start-var &optional (svalue 0))
722                              (end-var &optional (evalue nil))
723                              &key force-inline check-fill-pointer)
724                             &body forms
725                             &environment env)
726   (once-only ((n-array array)
727               (n-svalue `(the index ,svalue))
728               (n-evalue `(the (or index null) ,evalue)))
729     (let ((check-bounds (policy env (plusp insert-array-bounds-checks))))
730       `(multiple-value-bind (,data-var
731                              ,start-var
732                              ,end-var
733                              ,@(when offset-var `(,offset-var)))
734            (if (not (array-header-p ,n-array))
735                (let ((,n-array ,n-array))
736                  (declare (type (simple-array * (*)) ,n-array))
737                  ,(once-only ((n-len (if check-fill-pointer
738                                          `(length ,n-array)
739                                          `(array-total-size ,n-array)))
740                               (n-end `(or ,n-evalue ,n-len)))
741                              (if check-bounds
742                                  `(if (<= 0 ,n-svalue ,n-end ,n-len)
743                                       (values ,n-array ,n-svalue ,n-end 0)
744                                       ,(if check-fill-pointer
745                                            `(sequence-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)
746                                            `(array-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)))
747                                  `(values ,n-array ,n-svalue ,n-end 0))))
748                ,(if force-inline
749                     `(%with-array-data-macro ,n-array ,n-svalue ,n-evalue
750                                              :check-bounds ,check-bounds
751                                              :check-fill-pointer ,check-fill-pointer)
752                     (if check-fill-pointer
753                         `(%with-array-data/fp ,n-array ,n-svalue ,n-evalue)
754                         `(%with-array-data ,n-array ,n-svalue ,n-evalue))))
755          ,@forms))))
756
757 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
758 ;;; DEFTRANSFORMs and DEFUNs.
759 (def!macro %with-array-data-macro (array
760                                    start
761                                    end
762                                    &key
763                                    (element-type '*)
764                                    check-bounds
765                                    check-fill-pointer)
766   (with-unique-names (size defaulted-end data cumulative-offset)
767     `(let* ((,size ,(if check-fill-pointer
768                         `(length ,array)
769                         `(array-total-size ,array)))
770             (,defaulted-end (or ,end ,size)))
771        ,@(when check-bounds
772                `((unless (<= ,start ,defaulted-end ,size)
773                    ,(if check-fill-pointer
774                         `(sequence-bounding-indices-bad-error ,array ,start ,end)
775                         `(array-bounding-indices-bad-error ,array ,start ,end)))))
776        (do ((,data ,array (%array-data-vector ,data))
777             (,cumulative-offset 0
778                                 (+ ,cumulative-offset
779                                    (%array-displacement ,data))))
780            ((not (array-header-p ,data))
781             (values (the (simple-array ,element-type 1) ,data)
782                     (the index (+ ,cumulative-offset ,start))
783                     (the index (+ ,cumulative-offset ,defaulted-end))
784                     (the index ,cumulative-offset)))
785          (declare (type index ,cumulative-offset))))))
786
787 (defun transform-%with-array-data/muble (array node check-fill-pointer)
788   (let ((element-type (upgraded-element-type-specifier-or-give-up array))
789         (type (lvar-type array))
790         (check-bounds (policy node (plusp insert-array-bounds-checks))))
791     (if (and (array-type-p type)
792              (not (array-type-complexp type))
793              (listp (array-type-dimensions type))
794              (not (null (cdr (array-type-dimensions type)))))
795         ;; If it's a simple multidimensional array, then just return
796         ;; its data vector directly rather than going through
797         ;; %WITH-ARRAY-DATA-MACRO. SBCL doesn't generally generate
798         ;; code that would use this currently, but we have encouraged
799         ;; users to use WITH-ARRAY-DATA and we may use it ourselves at
800         ;; some point in the future for optimized libraries or
801         ;; similar.
802         (if check-bounds
803             `(let* ((data (truly-the (simple-array ,element-type (*))
804                                      (%array-data-vector array)))
805                     (len (length data))
806                     (real-end (or end len)))
807                (unless (<= 0 start data-end lend)
808                  (sequence-bounding-indices-bad-error array start end))
809                (values data 0 real-end 0))
810             `(let ((data (truly-the (simple-array ,element-type (*))
811                                     (%array-data-vector array))))
812                (values data 0 (or end (length data)) 0)))
813         `(%with-array-data-macro array start end
814                                  :check-fill-pointer ,check-fill-pointer
815                                  :check-bounds ,check-bounds
816                                  :element-type ,element-type))))
817
818 ;; It might very well be reasonable to allow general ARRAY here, I
819 ;; just haven't tried to understand the performance issues involved.
820 ;; -- WHN, and also CSR 2002-05-26
821 (deftransform %with-array-data ((array start end)
822                                 ((or vector simple-array) index (or index null) t)
823                                 *
824                                 :node node
825                                 :policy (> speed space))
826   "inline non-SIMPLE-vector-handling logic"
827   (transform-%with-array-data/muble array node nil))
828 (deftransform %with-array-data/fp ((array start end)
829                                 ((or vector simple-array) index (or index null) t)
830                                 *
831                                 :node node
832                                 :policy (> speed space))
833   "inline non-SIMPLE-vector-handling logic"
834   (transform-%with-array-data/muble array node t))
835 \f
836 ;;;; array accessors
837
838 ;;; We convert all typed array accessors into AREF and %ASET with type
839 ;;; assertions on the array.
840 (macrolet ((define-bit-frob (reffer setter simplep)
841              `(progn
842                 (define-source-transform ,reffer (a &rest i)
843                   `(aref (the (,',(if simplep 'simple-array 'array)
844                                   bit
845                                   ,(mapcar (constantly '*) i))
846                            ,a) ,@i))
847                 (define-source-transform ,setter (a &rest i)
848                   `(%aset (the (,',(if simplep 'simple-array 'array)
849                                    bit
850                                    ,(cdr (mapcar (constantly '*) i)))
851                             ,a) ,@i)))))
852   (define-bit-frob sbit %sbitset t)
853   (define-bit-frob bit %bitset nil))
854 (macrolet ((define-frob (reffer setter type)
855              `(progn
856                 (define-source-transform ,reffer (a i)
857                   `(aref (the ,',type ,a) ,i))
858                 (define-source-transform ,setter (a i v)
859                   `(%aset (the ,',type ,a) ,i ,v)))))
860   (define-frob svref %svset simple-vector)
861   (define-frob schar %scharset simple-string)
862   (define-frob char %charset string))
863
864 (macrolet (;; This is a handy macro for computing the row-major index
865            ;; given a set of indices. We wrap each index with a call
866            ;; to %CHECK-BOUND to ensure that everything works out
867            ;; correctly. We can wrap all the interior arithmetic with
868            ;; TRULY-THE INDEX because we know the resultant
869            ;; row-major index must be an index.
870            (with-row-major-index ((array indices index &optional new-value)
871                                   &rest body)
872              `(let (n-indices dims)
873                 (dotimes (i (length ,indices))
874                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
875                   (push (make-symbol (format nil "DIM-~D" i)) dims))
876                 (setf n-indices (nreverse n-indices))
877                 (setf dims (nreverse dims))
878                 `(lambda (,',array ,@n-indices
879                                    ,@',(when new-value (list new-value)))
880                    (let* (,@(let ((,index -1))
881                               (mapcar (lambda (name)
882                                         `(,name (array-dimension
883                                                  ,',array
884                                                  ,(incf ,index))))
885                                       dims))
886                             (,',index
887                              ,(if (null dims)
888                                   0
889                                 (do* ((dims dims (cdr dims))
890                                       (indices n-indices (cdr indices))
891                                       (last-dim nil (car dims))
892                                       (form `(%check-bound ,',array
893                                                            ,(car dims)
894                                                            ,(car indices))
895                                             `(truly-the
896                                               index
897                                               (+ (truly-the index
898                                                             (* ,form
899                                                                ,last-dim))
900                                                  (%check-bound
901                                                   ,',array
902                                                   ,(car dims)
903                                                   ,(car indices))))))
904                                     ((null (cdr dims)) form)))))
905                      ,',@body)))))
906
907   ;; Just return the index after computing it.
908   (deftransform array-row-major-index ((array &rest indices))
909     (with-row-major-index (array indices index)
910       index))
911
912   ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
913   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
914   ;; expression for the row major index.
915   (deftransform aref ((array &rest indices))
916     (with-row-major-index (array indices index)
917       (hairy-data-vector-ref array index)))
918
919   (deftransform %aset ((array &rest stuff))
920     (let ((indices (butlast stuff)))
921       (with-row-major-index (array indices index new-value)
922         (hairy-data-vector-set array index new-value)))))
923
924 ;; For AREF of vectors we do the bounds checking in the callee. This
925 ;; lets us do a significantly more efficient check for simple-arrays
926 ;; without bloating the code. If we already know the type of the array
927 ;; with sufficient precision, skip directly to DATA-VECTOR-REF.
928 (deftransform aref ((array index) (t t) * :node node)
929   (let* ((type (lvar-type array))
930          (element-ctype (extract-upgraded-element-type array)))
931     (cond
932       ((and (array-type-p type)
933             (null (array-type-complexp type))
934             (not (eql element-ctype *wild-type*))
935             (eql (length (array-type-dimensions type)) 1))
936        (let* ((declared-element-ctype (extract-declared-element-type array))
937               (bare-form
938                `(data-vector-ref array
939                  (%check-bound array (array-dimension array 0) index))))
940          (if (type= declared-element-ctype element-ctype)
941              bare-form
942              `(the ,(type-specifier declared-element-ctype) ,bare-form))))
943       ((policy node (zerop insert-array-bounds-checks))
944        `(hairy-data-vector-ref array index))
945       (t `(hairy-data-vector-ref/check-bounds array index)))))
946
947 (deftransform %aset ((array index new-value) (t t t) * :node node)
948   (if (policy node (zerop insert-array-bounds-checks))
949       `(hairy-data-vector-set array index new-value)
950       `(hairy-data-vector-set/check-bounds array index new-value)))
951
952 ;;; But if we find out later that there's some useful type information
953 ;;; available, switch back to the normal one to give other transforms
954 ;;; a stab at it.
955 (macrolet ((define (name transform-to extra extra-type)
956              (declare (ignore extra-type))
957              `(deftransform ,name ((array index ,@extra))
958                 (let ((type (lvar-type array))
959                       (element-type (extract-upgraded-element-type array))
960                       (declared-type (extract-declared-element-type array)))
961                   ;; If an element type has been declared, we want to
962                   ;; use that information it for type checking (even
963                   ;; if the access can't be optimized due to the array
964                   ;; not being simple).
965                   (when (and (eql element-type *wild-type*)
966                              ;; This type logic corresponds to the special
967                              ;; case for strings in HAIRY-DATA-VECTOR-REF
968                              ;; (generic/vm-tran.lisp)
969                              (not (csubtypep type (specifier-type 'simple-string))))
970                     (when (or (not (array-type-p type))
971                               ;; If it's a simple array, we might be able
972                               ;; to inline the access completely.
973                               (not (null (array-type-complexp type))))
974                       (give-up-ir1-transform
975                        "Upgraded element type of array is not known at compile time.")))
976                   ,(if extra
977                        ``(truly-the ,declared-type
978                                     (,',transform-to array
979                                                      (%check-bound array
980                                                                    (array-dimension array 0)
981                                                                    index)
982                                                      (the ,declared-type ,@',extra)))
983                        ``(the ,declared-type
984                            (,',transform-to array
985                                             (%check-bound array
986                                                           (array-dimension array 0)
987                                                           index))))))))
988   (define hairy-data-vector-ref/check-bounds
989       hairy-data-vector-ref nil nil)
990   (define hairy-data-vector-set/check-bounds
991       hairy-data-vector-set (new-value) (*)))
992
993 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
994 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
995 ;;; array total size.
996 (deftransform row-major-aref ((array index))
997   `(hairy-data-vector-ref array
998                           (%check-bound array (array-total-size array) index)))
999 (deftransform %set-row-major-aref ((array index new-value))
1000   `(hairy-data-vector-set array
1001                           (%check-bound array (array-total-size array) index)
1002                           new-value))
1003 \f
1004 ;;;; bit-vector array operation canonicalization
1005 ;;;;
1006 ;;;; We convert all bit-vector operations to have the result array
1007 ;;;; specified. This allows any result allocation to be open-coded,
1008 ;;;; and eliminates the need for any VM-dependent transforms to handle
1009 ;;;; these cases.
1010
1011 (macrolet ((def (fun)
1012              `(progn
1013                (deftransform ,fun ((bit-array-1 bit-array-2
1014                                                 &optional result-bit-array)
1015                                    (bit-vector bit-vector &optional null) *
1016                                    :policy (>= speed space))
1017                  `(,',fun bit-array-1 bit-array-2
1018                    (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1019                ;; If result is T, make it the first arg.
1020                (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
1021                                    (bit-vector bit-vector (eql t)) *)
1022                  `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
1023   (def bit-and)
1024   (def bit-ior)
1025   (def bit-xor)
1026   (def bit-eqv)
1027   (def bit-nand)
1028   (def bit-nor)
1029   (def bit-andc1)
1030   (def bit-andc2)
1031   (def bit-orc1)
1032   (def bit-orc2))
1033
1034 ;;; Similar for BIT-NOT, but there is only one arg...
1035 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
1036                        (bit-vector &optional null) *
1037                        :policy (>= speed space))
1038   '(bit-not bit-array-1
1039             (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1040 (deftransform bit-not ((bit-array-1 result-bit-array)
1041                        (bit-vector (eql t)))
1042   '(bit-not bit-array-1 bit-array-1))
1043 \f
1044 ;;; Pick off some constant cases.
1045 (defoptimizer (array-header-p derive-type) ((array))
1046   (let ((type (lvar-type array)))
1047     (cond ((not (array-type-p type))
1048            ;; FIXME: use analogue of ARRAY-TYPE-DIMENSIONS-OR-GIVE-UP
1049            nil)
1050           (t
1051            (let ((dims (array-type-dimensions type)))
1052              (cond ((csubtypep type (specifier-type '(simple-array * (*))))
1053                     ;; no array header
1054                     (specifier-type 'null))
1055                    ((and (listp dims) (/= (length dims) 1))
1056                     ;; multi-dimensional array, will have a header
1057                     (specifier-type '(eql t)))
1058                    ((eql (array-type-complexp type) t)
1059                     (specifier-type '(eql t)))
1060                    (t
1061                     nil)))))))