0.8.0.76:
[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 CONTINUATION, 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 (continuation)
20   (let* ((element-ctype (extract-upgraded-element-type continuation))
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
28 ;;; type is going to be the array upgraded element type.
29 (defun extract-upgraded-element-type (array)
30   (let ((type (continuation-type array)))
31     ;; Note that this IF mightn't be satisfied even if the runtime
32     ;; value is known to be a subtype of some specialized ARRAY, because
33     ;; we can have values declared e.g. (AND SIMPLE-VECTOR UNKNOWN-TYPE),
34     ;; which are represented in the compiler as INTERSECTION-TYPE, not
35     ;; array type.
36     (if (array-type-p type)
37         (array-type-specialized-element-type type)
38         ;; KLUDGE: there is no good answer here, but at least
39         ;; *wild-type* won't cause HAIRY-DATA-VECTOR-{REF,SET} to be
40         ;; erroneously optimized (see generic/vm-tran.lisp) -- CSR,
41         ;; 2002-08-21
42         *wild-type*)))
43
44 ;;; The ``new-value'' for array setters must fit in the array, and the
45 ;;; return type is going to be the same as the new-value for SETF
46 ;;; functions.
47 (defun assert-new-value-type (new-value array)
48   (let ((type (continuation-type array)))
49     (when (array-type-p type)
50       (assert-continuation-type
51        new-value
52        (array-type-specialized-element-type type)
53        (lexenv-policy (node-lexenv (continuation-dest new-value))))))
54   (continuation-type new-value))
55
56 (defun assert-array-complex (array)
57   (assert-continuation-type
58    array
59    (make-array-type :complexp t
60                     :element-type *wild-type*)
61    (lexenv-policy (node-lexenv (continuation-dest array))))
62   nil)
63
64 ;;; Return true if ARG is NIL, or is a constant-continuation whose
65 ;;; value is NIL, false otherwise.
66 (defun unsupplied-or-nil (arg)
67   (declare (type (or continuation null) arg))
68   (or (not arg)
69       (and (constant-continuation-p arg)
70            (not (continuation-value arg)))))
71 \f
72 ;;;; DERIVE-TYPE optimizers
73
74 ;;; Array operations that use a specific number of indices implicitly
75 ;;; assert that the array is of that rank.
76 (defun assert-array-rank (array rank)
77   (assert-continuation-type
78    array
79    (specifier-type `(array * ,(make-list rank :initial-element '*)))
80    (lexenv-policy (node-lexenv (continuation-dest array)))))
81
82 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
83   (assert-array-rank array (length indices))
84   *universal-type*)
85
86 (defoptimizer (aref derive-type) ((array &rest indices) node)
87   (assert-array-rank array (length indices))
88   ;; If the node continuation has a single use then assert its type.
89   (let ((cont (node-cont node)))
90     (when (= (length (find-uses cont)) 1)
91       (assert-continuation-type cont (extract-upgraded-element-type array)
92                                 (lexenv-policy (node-lexenv node)))))
93   (extract-upgraded-element-type array))
94
95 (defoptimizer (%aset derive-type) ((array &rest stuff))
96   (assert-array-rank array (1- (length stuff)))
97   (assert-new-value-type (car (last stuff)) array))
98
99 (defoptimizer (hairy-data-vector-ref derive-type) ((array index))
100   (extract-upgraded-element-type array))
101 (defoptimizer (data-vector-ref derive-type) ((array index))
102   (extract-upgraded-element-type array))
103
104 (defoptimizer (data-vector-set derive-type) ((array index new-value))
105   (assert-new-value-type new-value array))
106 (defoptimizer (hairy-data-vector-set derive-type) ((array index new-value))
107   (assert-new-value-type new-value array))
108
109 ;;; Figure out the type of the data vector if we know the argument
110 ;;; element type.
111 (defoptimizer (%with-array-data derive-type) ((array start end))
112   (let ((atype (continuation-type array)))
113     (when (array-type-p atype)
114       (specifier-type
115        `(simple-array ,(type-specifier
116                        (array-type-specialized-element-type atype))
117                      (*))))))
118
119 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
120   (assert-array-rank array (length indices))
121   *universal-type*)
122
123 (defoptimizer (row-major-aref derive-type) ((array index))
124   (extract-upgraded-element-type array))
125
126 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
127   (assert-new-value-type new-value array))
128
129 (defoptimizer (make-array derive-type)
130               ((dims &key initial-element element-type initial-contents
131                 adjustable fill-pointer displaced-index-offset displaced-to))
132   (let ((simple (and (unsupplied-or-nil adjustable)
133                      (unsupplied-or-nil displaced-to)
134                      (unsupplied-or-nil fill-pointer))))
135     (or (careful-specifier-type
136          `(,(if simple 'simple-array 'array)
137             ,(cond ((not element-type) t)
138                    ((constant-continuation-p element-type)
139                     (continuation-value element-type))
140                    (t
141                     '*))
142             ,(cond ((constant-continuation-p dims)
143                     (let* ((val (continuation-value dims))
144                            (cdims (if (listp val) val (list val))))
145                       (if simple
146                           cdims
147                           (length cdims))))
148                    ((csubtypep (continuation-type dims)
149                                (specifier-type 'integer))
150                     '(*))
151                    (t
152                     '*))))
153         (specifier-type 'array))))
154
155 ;;; Complex array operations should assert that their array argument
156 ;;; is complex.  In SBCL, vectors with fill-pointers are complex.
157 (defoptimizer (fill-pointer derive-type) ((vector))
158   (assert-array-complex vector))
159 (defoptimizer (%set-fill-pointer derive-type) ((vector index))
160   (declare (ignorable index))
161   (assert-array-complex vector))
162
163 (defoptimizer (vector-push derive-type) ((object vector))
164   (declare (ignorable object))
165   (assert-array-complex vector))
166 (defoptimizer (vector-push-extend derive-type)
167     ((object vector &optional index))
168   (declare (ignorable object index))
169   (assert-array-complex vector))
170 (defoptimizer (vector-pop derive-type) ((vector))
171   (assert-array-complex vector))
172 \f
173 ;;;; constructors
174
175 ;;; Convert VECTOR into a MAKE-ARRAY followed by SETFs of all the
176 ;;; elements.
177 (define-source-transform vector (&rest elements)
178   (let ((len (length elements))
179         (n -1))
180     (once-only ((n-vec `(make-array ,len)))
181       `(progn
182          ,@(mapcar (lambda (el)
183                      (once-only ((n-val el))
184                        `(locally (declare (optimize (safety 0)))
185                                  (setf (svref ,n-vec ,(incf n))
186                                        ,n-val))))
187                    elements)
188          ,n-vec))))
189
190 ;;; Just convert it into a MAKE-ARRAY.
191 (deftransform make-string ((length &key
192                                    (element-type 'base-char)
193                                    (initial-element
194                                     #.*default-init-char-form*)))
195   '(make-array (the index length)
196                :element-type element-type
197                :initial-element initial-element))
198
199 (defstruct (specialized-array-element-type-properties
200             (:conc-name saetp-)
201             (:constructor !make-saetp (ctype
202                                        initial-element-default
203                                        n-bits
204                                        typecode
205                                        &key
206                                        (n-pad-elements 0)))
207             (:copier nil))
208   ;; the element type, e.g. #<BUILT-IN-CLASS BASE-CHAR (sealed)> or
209   ;; #<SB-KERNEL:NUMERIC-TYPE (UNSIGNED-BYTE 4)>
210   (ctype (missing-arg) :type ctype :read-only t)
211   ;; what we get when the low-level vector-creation logic zeroes all
212   ;; the bits (which also serves as the default value of MAKE-ARRAY's
213   ;; :INITIAL-ELEMENT keyword)
214   (initial-element-default (missing-arg) :read-only t)
215   ;; how many bits per element
216   (n-bits (missing-arg) :type index :read-only t)
217   ;; the low-level type code
218   (typecode (missing-arg) :type index :read-only t)
219   ;; the number of extra elements we use at the end of the array for
220   ;; low level hackery (e.g., one element for arrays of BASE-CHAR,
221   ;; which is used for a fixed #\NULL so that when we call out to C
222   ;; we don't need to cons a new copy)
223   (n-pad-elements (missing-arg) :type index :read-only t))
224
225 (defparameter *specialized-array-element-type-properties*
226   (map 'simple-vector
227        (lambda (args)
228          (destructuring-bind (type-spec &rest rest) args
229            (let ((ctype (specifier-type type-spec)))
230              (apply #'!make-saetp ctype rest))))
231        `(;; Erm.  Yeah.  There aren't a lot of things that make sense
232          ;; for an initial element for (ARRAY NIL). -- CSR, 2002-03-07
233          (nil '#:mu 0 ,sb!vm:simple-array-nil-widetag)
234          (base-char ,(code-char 0) 8 ,sb!vm:simple-string-widetag
235                     ;; (SIMPLE-STRINGs are stored with an extra trailing
236                     ;; #\NULL for convenience in calling out to C.)
237                     :n-pad-elements 1)
238          (single-float 0.0f0 32 ,sb!vm:simple-array-single-float-widetag)
239          (double-float 0.0d0 64 ,sb!vm:simple-array-double-float-widetag)
240          #!+long-float (long-float 0.0L0 #!+x86 96 #!+sparc 128
241                                    ,sb!vm:simple-array-long-float-widetag)
242          (bit 0 1 ,sb!vm:simple-bit-vector-widetag)
243          ;; KLUDGE: The fact that these UNSIGNED-BYTE entries come
244          ;; before their SIGNED-BYTE partners is significant in the
245          ;; implementation of the compiler; some of the cross-compiler
246          ;; code (see e.g. COERCE-TO-SMALLEST-ELTYPE in
247          ;; src/compiler/debug-dump.lisp) attempts to create an array
248          ;; specialized on (UNSIGNED-BYTE FOO), where FOO could be 7;
249          ;; (UNSIGNED-BYTE 7) is SUBTYPEP (SIGNED-BYTE 8), so if we're
250          ;; not careful we could get the wrong specialized array when
251          ;; we try to FIND-IF, below. -- CSR, 2002-07-08
252          ((unsigned-byte 2) 0 2 ,sb!vm:simple-array-unsigned-byte-2-widetag)
253          ((unsigned-byte 4) 0 4 ,sb!vm:simple-array-unsigned-byte-4-widetag)
254          ((unsigned-byte 8) 0 8 ,sb!vm:simple-array-unsigned-byte-8-widetag)
255          ((unsigned-byte 16) 0 16 ,sb!vm:simple-array-unsigned-byte-16-widetag)
256          ((unsigned-byte 32) 0 32 ,sb!vm:simple-array-unsigned-byte-32-widetag)
257          ((signed-byte 8) 0 8 ,sb!vm:simple-array-signed-byte-8-widetag)
258          ((signed-byte 16) 0 16 ,sb!vm:simple-array-signed-byte-16-widetag)
259          ((signed-byte 30) 0 32 ,sb!vm:simple-array-signed-byte-30-widetag)
260          ((signed-byte 32) 0 32 ,sb!vm:simple-array-signed-byte-32-widetag)
261          ((complex single-float) #C(0.0f0 0.0f0) 64
262           ,sb!vm:simple-array-complex-single-float-widetag)
263          ((complex double-float) #C(0.0d0 0.0d0) 128
264           ,sb!vm:simple-array-complex-double-float-widetag)
265          #!+long-float ((complex long-float) #C(0.0L0 0.0L0)
266                         #!+x86 192 #!+sparc 256
267                         ,sb!vm:simple-array-complex-long-float-widetag)
268          (t 0 32 ,sb!vm:simple-vector-widetag))))
269
270 (deftransform make-array ((dims &key initial-element element-type
271                                      adjustable fill-pointer)
272                           (t &rest *))
273   (when (null initial-element)
274     (give-up-ir1-transform))
275   (let* ((eltype (cond ((not element-type) t)
276                        ((not (constant-continuation-p element-type))
277                         (give-up-ir1-transform
278                          "ELEMENT-TYPE is not constant."))
279                        (t
280                         (continuation-value element-type))))
281          (eltype-type (ir1-transform-specifier-type eltype))
282          (saetp (find-if (lambda (saetp)
283                            (csubtypep eltype-type (saetp-ctype saetp)))
284                          *specialized-array-element-type-properties*))
285          (creation-form `(make-array dims
286                           :element-type ',(type-specifier (saetp-ctype saetp))
287                           ,@(when fill-pointer
288                                   '(:fill-pointer fill-pointer))
289                           ,@(when adjustable
290                                   '(:adjustable adjustable)))))
291
292     (unless saetp
293       (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
294
295     (cond ((and (constant-continuation-p initial-element)
296                 (eql (continuation-value initial-element)
297                      (saetp-initial-element-default saetp)))
298            creation-form)
299           (t
300            ;; error checking for target, disabled on the host because
301            ;; (CTYPE-OF #\Null) is not possible.
302            #-sb-xc-host
303            (when (constant-continuation-p initial-element)
304              (let ((value (continuation-value initial-element)))
305                (cond
306                  ((not (ctypep value (saetp-ctype saetp)))
307                   ;; this case will cause an error at runtime, so we'd
308                   ;; better WARN about it now.
309                   (compiler-warn "~@<~S is not a ~S (which is the ~
310                                  UPGRADED-ARRAY-ELEMENT-TYPE of ~S).~@:>"
311                                  value
312                                  (type-specifier (saetp-ctype saetp))
313                                  eltype))
314                  ((not (ctypep value eltype-type))
315                   ;; this case will not cause an error at runtime, but
316                   ;; it's still worth STYLE-WARNing about.
317                   (compiler-style-warn "~S is not a ~S."
318                                        value eltype)))))
319            `(let ((array ,creation-form))
320              (multiple-value-bind (vector)
321                  (%data-vector-and-index array 0)
322                (fill vector initial-element))
323              array)))))
324
325 ;;; The integer type restriction on the length ensures that it will be
326 ;;; a vector. The lack of :ADJUSTABLE, :FILL-POINTER, and
327 ;;; :DISPLACED-TO keywords ensures that it will be simple; the lack of
328 ;;; :INITIAL-ELEMENT relies on another transform to deal with that
329 ;;; kind of initialization efficiently.
330 (deftransform make-array ((length &key element-type)
331                           (integer &rest *))
332   (let* ((eltype (cond ((not element-type) t)
333                        ((not (constant-continuation-p element-type))
334                         (give-up-ir1-transform
335                          "ELEMENT-TYPE is not constant."))
336                        (t
337                         (continuation-value element-type))))
338          (len (if (constant-continuation-p length)
339                   (continuation-value length)
340                   '*))
341          (result-type-spec `(simple-array ,eltype (,len)))
342          (eltype-type (ir1-transform-specifier-type eltype))
343          (saetp (find-if (lambda (saetp)
344                            (csubtypep eltype-type (saetp-ctype saetp)))
345                          *specialized-array-element-type-properties*)))
346     (unless saetp
347       (give-up-ir1-transform
348        "cannot open-code creation of ~S" result-type-spec))
349     #-sb-xc-host
350     (unless (csubtypep (ctype-of (saetp-initial-element-default saetp))
351                        eltype-type)
352       ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
353       ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
354       ;; INITIAL-ELEMENT is not supplied, the consequences of later
355       ;; reading an uninitialized element of new-array are undefined,"
356       ;; so this could be legal code as long as the user plans to
357       ;; write before he reads, and if he doesn't we're free to do
358       ;; anything we like. But in case the user doesn't know to write
359       ;; elements before he reads elements (or to read manuals before
360       ;; he writes code:-), we'll signal a STYLE-WARNING in case he
361       ;; didn't realize this.
362       (compiler-style-warn "The default initial element ~S is not a ~S."
363                            (saetp-initial-element-default saetp)
364                            eltype))
365     (let* ((n-bits-per-element (saetp-n-bits saetp))
366            (typecode (saetp-typecode saetp))
367            (n-pad-elements (saetp-n-pad-elements saetp))
368            (padded-length-form (if (zerop n-pad-elements)
369                                    'length
370                                    `(+ length ,n-pad-elements)))
371            (n-words-form
372             (cond
373               ((= n-bits-per-element 0) 0)
374               ((>= n-bits-per-element sb!vm:n-word-bits)
375                `(* ,padded-length-form
376                  (the fixnum ; i.e., not RATIO
377                    ,(/ n-bits-per-element sb!vm:n-word-bits))))
378               (t
379                (let ((n-elements-per-word (/ sb!vm:n-word-bits
380                                              n-bits-per-element)))
381                  (declare (type index n-elements-per-word)) ; i.e., not RATIO
382                  `(ceiling ,padded-length-form ,n-elements-per-word))))))
383       (values
384        `(truly-the ,result-type-spec
385          (allocate-vector ,typecode length ,n-words-form))
386        '((declare (type index length)))))))
387
388 ;;; The list type restriction does not ensure that the result will be a
389 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
390 ;;; and displaced-to keywords ensures that it will be simple.
391 ;;;
392 ;;; FIXME: should we generalize this transform to non-simple (though
393 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
394 ;;; deal with those? Maybe when the DEFTRANSFORM
395 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
396 ;;; CSR, 2002-07-01
397 (deftransform make-array ((dims &key element-type)
398                           (list &rest *))
399   (unless (or (null element-type) (constant-continuation-p element-type))
400     (give-up-ir1-transform
401      "The element-type is not constant; cannot open code array creation."))
402   (unless (constant-continuation-p dims)
403     (give-up-ir1-transform
404      "The dimension list is not constant; cannot open code array creation."))
405   (let ((dims (continuation-value dims)))
406     (unless (every #'integerp dims)
407       (give-up-ir1-transform
408        "The dimension list contains something other than an integer: ~S"
409        dims))
410     (if (= (length dims) 1)
411         `(make-array ',(car dims)
412                      ,@(when element-type
413                          '(:element-type element-type)))
414         (let* ((total-size (reduce #'* dims))
415                (rank (length dims))
416                (spec `(simple-array
417                        ,(cond ((null element-type) t)
418                               ((constant-continuation-p element-type)
419                                (continuation-value element-type))
420                               (t '*))
421                            ,(make-list rank :initial-element '*))))
422           `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank)))
423              (setf (%array-fill-pointer header) ,total-size)
424              (setf (%array-fill-pointer-p header) nil)
425              (setf (%array-available-elements header) ,total-size)
426              (setf (%array-data-vector header)
427                    (make-array ,total-size
428                                ,@(when element-type
429                                    '(:element-type element-type))))
430              (setf (%array-displaced-p header) nil)
431              ,@(let ((axis -1))
432                  (mapcar (lambda (dim)
433                            `(setf (%array-dimension header ,(incf axis))
434                                   ,dim))
435                          dims))
436              (truly-the ,spec header))))))
437 \f
438 ;;;; miscellaneous properties of arrays
439
440 ;;; Transforms for various array properties. If the property is know
441 ;;; at compile time because of a type spec, use that constant value.
442
443 ;;; If we can tell the rank from the type info, use it instead.
444 (deftransform array-rank ((array))
445   (let ((array-type (continuation-type array)))
446     (unless (array-type-p array-type)
447       (give-up-ir1-transform))
448     (let ((dims (array-type-dimensions array-type)))
449       (if (not (listp dims))
450           (give-up-ir1-transform
451            "The array rank is not known at compile time: ~S"
452            dims)
453           (length dims)))))
454
455 ;;; If we know the dimensions at compile time, just use it. Otherwise,
456 ;;; if we can tell that the axis is in bounds, convert to
457 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
458 ;;; (if it's simple and a vector).
459 (deftransform array-dimension ((array axis)
460                                (array index))
461   (unless (constant-continuation-p axis)
462     (give-up-ir1-transform "The axis is not constant."))
463   (let ((array-type (continuation-type array))
464         (axis (continuation-value axis)))
465     (unless (array-type-p array-type)
466       (give-up-ir1-transform))
467     (let ((dims (array-type-dimensions array-type)))
468       (unless (listp dims)
469         (give-up-ir1-transform
470          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
471       (unless (> (length dims) axis)
472         (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
473                              dims
474                              axis))
475       (let ((dim (nth axis dims)))
476         (cond ((integerp dim)
477                dim)
478               ((= (length dims) 1)
479                (ecase (array-type-complexp array-type)
480                  ((t)
481                   '(%array-dimension array 0))
482                  ((nil)
483                   '(length array))
484                  ((:maybe)
485                   (give-up-ir1-transform
486                    "can't tell whether array is simple"))))
487               (t
488                '(%array-dimension array axis)))))))
489
490 ;;; If the length has been declared and it's simple, just return it.
491 (deftransform length ((vector)
492                       ((simple-array * (*))))
493   (let ((type (continuation-type vector)))
494     (unless (array-type-p type)
495       (give-up-ir1-transform))
496     (let ((dims (array-type-dimensions type)))
497       (unless (and (listp dims) (integerp (car dims)))
498         (give-up-ir1-transform
499          "Vector length is unknown, must call LENGTH at runtime."))
500       (car dims))))
501
502 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
503 ;;; simple, it will extract the length slot from the vector. It it's
504 ;;; complex, it will extract the fill pointer slot from the array
505 ;;; header.
506 (deftransform length ((vector) (vector))
507   '(vector-length vector))
508
509 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
510 ;;; compile-time constant.
511 (deftransform vector-length ((vector))
512   (let ((vtype (continuation-type vector)))
513     (if (and (array-type-p vtype)
514              (not (array-type-complexp vtype)))
515         (let ((dim (first (array-type-dimensions vtype))))
516           (when (eq dim '*) (give-up-ir1-transform))
517           dim)
518         (give-up-ir1-transform))))
519
520 ;;; Again, if we can tell the results from the type, just use it.
521 ;;; Otherwise, if we know the rank, convert into a computation based
522 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
523 ;;; multiplications because we know that the total size must be an
524 ;;; INDEX.
525 (deftransform array-total-size ((array)
526                                 (array))
527   (let ((array-type (continuation-type array)))
528     (unless (array-type-p array-type)
529       (give-up-ir1-transform))
530     (let ((dims (array-type-dimensions array-type)))
531       (unless (listp dims)
532         (give-up-ir1-transform "can't tell the rank at compile time"))
533       (if (member '* dims)
534           (do ((form 1 `(truly-the index
535                                    (* (array-dimension array ,i) ,form)))
536                (i 0 (1+ i)))
537               ((= i (length dims)) form))
538           (reduce #'* dims)))))
539
540 ;;; Only complex vectors have fill pointers.
541 (deftransform array-has-fill-pointer-p ((array))
542   (let ((array-type (continuation-type array)))
543     (unless (array-type-p array-type)
544       (give-up-ir1-transform))
545     (let ((dims (array-type-dimensions array-type)))
546       (if (and (listp dims) (not (= (length dims) 1)))
547           nil
548           (ecase (array-type-complexp array-type)
549             ((t)
550              t)
551             ((nil)
552              nil)
553             ((:maybe)
554              (give-up-ir1-transform
555               "The array type is ambiguous; must call ~
556               ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
557
558 ;;; Primitive used to verify indices into arrays. If we can tell at
559 ;;; compile-time or we are generating unsafe code, don't bother with
560 ;;; the VOP.
561 (deftransform %check-bound ((array dimension index) * * :node node)
562   (cond ((policy node (and (> speed safety) (= safety 0)))
563          'index)
564         ((not (constant-continuation-p dimension))
565          (give-up-ir1-transform))
566         (t
567          (let ((dim (continuation-value dimension)))
568            `(the (integer 0 ,dim) index)))))
569 \f
570 ;;;; WITH-ARRAY-DATA
571
572 ;;; This checks to see whether the array is simple and the start and
573 ;;; end are in bounds. If so, it proceeds with those values.
574 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
575 ;;; may be further optimized.
576 ;;;
577 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
578 ;;; START-VAR and END-VAR to the start and end of the designated
579 ;;; portion of the data vector. SVALUE and EVALUE are any start and
580 ;;; end specified to the original operation, and are factored into the
581 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
582 ;;; offset of all displacements encountered, and does not include
583 ;;; SVALUE.
584 ;;;
585 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
586 ;;; forced to be inline, overriding the ordinary judgment of the
587 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
588 ;;; fairly picky about their arguments, figuring that if you haven't
589 ;;; bothered to get all your ducks in a row, you probably don't care
590 ;;; that much about speed anyway! But in some cases it makes sense to
591 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
592 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
593 ;;; sense to use FORCE-INLINE option in that case.
594 (def!macro with-array-data (((data-var array &key offset-var)
595                              (start-var &optional (svalue 0))
596                              (end-var &optional (evalue nil))
597                              &key force-inline)
598                             &body forms)
599   (once-only ((n-array array)
600               (n-svalue `(the index ,svalue))
601               (n-evalue `(the (or index null) ,evalue)))
602     `(multiple-value-bind (,data-var
603                            ,start-var
604                            ,end-var
605                            ,@(when offset-var `(,offset-var)))
606          (if (not (array-header-p ,n-array))
607              (let ((,n-array ,n-array))
608                (declare (type (simple-array * (*)) ,n-array))
609                ,(once-only ((n-len `(length ,n-array))
610                             (n-end `(or ,n-evalue ,n-len)))
611                   `(if (<= ,n-svalue ,n-end ,n-len)
612                        ;; success
613                        (values ,n-array ,n-svalue ,n-end 0)
614                        (failed-%with-array-data ,n-array
615                                                 ,n-svalue
616                                                 ,n-evalue))))
617              (,(if force-inline '%with-array-data-macro '%with-array-data)
618               ,n-array ,n-svalue ,n-evalue))
619        ,@forms)))
620
621 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
622 ;;; DEFTRANSFORMs and DEFUNs.
623 (def!macro %with-array-data-macro (array
624                                    start
625                                    end
626                                    &key
627                                    (element-type '*)
628                                    unsafe?
629                                    fail-inline?)
630   (with-unique-names (size defaulted-end data cumulative-offset)
631     `(let* ((,size (array-total-size ,array))
632             (,defaulted-end
633               (cond (,end
634                      (unless (or ,unsafe? (<= ,end ,size))
635                        ,(if fail-inline?
636                             `(error 'bounding-indices-bad-error
637                               :datum (cons ,start ,end)
638                               :expected-type `(cons (integer 0 ,',size)
639                                                     (integer ,',start ,',size))
640                               :object ,array)
641                             `(failed-%with-array-data ,array ,start ,end)))
642                      ,end)
643                     (t ,size))))
644        (unless (or ,unsafe? (<= ,start ,defaulted-end))
645          ,(if fail-inline?
646               `(error 'bounding-indices-bad-error
647                 :datum (cons ,start ,end)
648                 :expected-type `(cons (integer 0 ,',size)
649                                       (integer ,',start ,',size))
650                 :object ,array)
651               `(failed-%with-array-data ,array ,start ,end)))
652        (do ((,data ,array (%array-data-vector ,data))
653             (,cumulative-offset 0
654                                 (+ ,cumulative-offset
655                                    (%array-displacement ,data))))
656            ((not (array-header-p ,data))
657             (values (the (simple-array ,element-type 1) ,data)
658                     (the index (+ ,cumulative-offset ,start))
659                     (the index (+ ,cumulative-offset ,defaulted-end))
660                     (the index ,cumulative-offset)))
661          (declare (type index ,cumulative-offset))))))
662
663 (deftransform %with-array-data ((array start end)
664                                 ;; It might very well be reasonable to
665                                 ;; allow general ARRAY here, I just
666                                 ;; haven't tried to understand the
667                                 ;; performance issues involved. --
668                                 ;; WHN, and also CSR 2002-05-26
669                                 ((or vector simple-array) index (or index null))
670                                 *
671                                 :important t
672                                 :node node
673                                 :policy (> speed space))
674   "inline non-SIMPLE-vector-handling logic"
675   (let ((element-type (upgraded-element-type-specifier-or-give-up array)))
676     `(%with-array-data-macro array start end
677                              :unsafe? ,(policy node (= safety 0))
678                              :element-type ,element-type)))
679 \f
680 ;;;; array accessors
681
682 ;;; We convert all typed array accessors into AREF and %ASET with type
683 ;;; assertions on the array.
684 (macrolet ((define-frob (reffer setter type)
685              `(progn
686                 (define-source-transform ,reffer (a &rest i)
687                   `(aref (the ,',type ,a) ,@i))
688                 (define-source-transform ,setter (a &rest i)
689                   `(%aset (the ,',type ,a) ,@i)))))
690   (define-frob sbit %sbitset (simple-array bit))
691   (define-frob bit %bitset (array bit)))
692 (macrolet ((define-frob (reffer setter type)
693              `(progn
694                 (define-source-transform ,reffer (a i)
695                   `(aref (the ,',type ,a) ,i))
696                 (define-source-transform ,setter (a i v)
697                   `(%aset (the ,',type ,a) ,i ,v)))))
698   (define-frob svref %svset simple-vector)
699   (define-frob schar %scharset simple-string)
700   (define-frob char %charset string))
701
702 (macrolet (;; This is a handy macro for computing the row-major index
703            ;; given a set of indices. We wrap each index with a call
704            ;; to %CHECK-BOUND to ensure that everything works out
705            ;; correctly. We can wrap all the interior arithmetic with
706            ;; TRULY-THE INDEX because we know the the resultant
707            ;; row-major index must be an index.
708            (with-row-major-index ((array indices index &optional new-value)
709                                   &rest body)
710              `(let (n-indices dims)
711                 (dotimes (i (length ,indices))
712                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
713                   (push (make-symbol (format nil "DIM-~D" i)) dims))
714                 (setf n-indices (nreverse n-indices))
715                 (setf dims (nreverse dims))
716                 `(lambda (,',array ,@n-indices
717                                    ,@',(when new-value (list new-value)))
718                    (let* (,@(let ((,index -1))
719                               (mapcar (lambda (name)
720                                         `(,name (array-dimension
721                                                  ,',array
722                                                  ,(incf ,index))))
723                                       dims))
724                             (,',index
725                              ,(if (null dims)
726                                   0
727                                 (do* ((dims dims (cdr dims))
728                                       (indices n-indices (cdr indices))
729                                       (last-dim nil (car dims))
730                                       (form `(%check-bound ,',array
731                                                            ,(car dims)
732                                                            ,(car indices))
733                                             `(truly-the
734                                               index
735                                               (+ (truly-the index
736                                                             (* ,form
737                                                                ,last-dim))
738                                                  (%check-bound
739                                                   ,',array
740                                                   ,(car dims)
741                                                   ,(car indices))))))
742                                     ((null (cdr dims)) form)))))
743                      ,',@body)))))
744
745   ;; Just return the index after computing it.
746   (deftransform array-row-major-index ((array &rest indices))
747     (with-row-major-index (array indices index)
748       index))
749
750   ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
751   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
752   ;; expression for the row major index.
753   (deftransform aref ((array &rest indices))
754     (with-row-major-index (array indices index)
755       (hairy-data-vector-ref array index)))
756   (deftransform %aset ((array &rest stuff))
757     (let ((indices (butlast stuff)))
758       (with-row-major-index (array indices index new-value)
759         (hairy-data-vector-set array index new-value)))))
760
761 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
762 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
763 ;;; array total size.
764 (deftransform row-major-aref ((array index))
765   `(hairy-data-vector-ref array
766                           (%check-bound array (array-total-size array) index)))
767 (deftransform %set-row-major-aref ((array index new-value))
768   `(hairy-data-vector-set array
769                           (%check-bound array (array-total-size array) index)
770                           new-value))
771 \f
772 ;;;; bit-vector array operation canonicalization
773 ;;;;
774 ;;;; We convert all bit-vector operations to have the result array
775 ;;;; specified. This allows any result allocation to be open-coded,
776 ;;;; and eliminates the need for any VM-dependent transforms to handle
777 ;;;; these cases.
778
779 (macrolet ((def (fun)
780              `(progn
781                (deftransform ,fun ((bit-array-1 bit-array-2
782                                                 &optional result-bit-array)
783                                    (bit-vector bit-vector &optional null) *
784                                    :policy (>= speed space))
785                  `(,',fun bit-array-1 bit-array-2
786                    (make-array (length bit-array-1) :element-type 'bit)))
787                ;; If result is T, make it the first arg.
788                (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
789                                    (bit-vector bit-vector (member t)) *)
790                  `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
791   (def bit-and)
792   (def bit-ior)
793   (def bit-xor)
794   (def bit-eqv)
795   (def bit-nand)
796   (def bit-nor)
797   (def bit-andc1)
798   (def bit-andc2)
799   (def bit-orc1)
800   (def bit-orc2))
801
802 ;;; Similar for BIT-NOT, but there is only one arg...
803 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
804                        (bit-vector &optional null) *
805                        :policy (>= speed space))
806   '(bit-not bit-array-1
807             (make-array (length bit-array-1) :element-type 'bit)))
808 (deftransform bit-not ((bit-array-1 result-bit-array)
809                        (bit-vector (constant-arg t)))
810   '(bit-not bit-array-1 bit-array-1))
811 ;;; FIXME: What does (CONSTANT-ARG T) mean? Is it the same thing
812 ;;; as (CONSTANT-ARG (MEMBER T)), or does it mean any constant
813 ;;; value?
814 \f
815 ;;; Pick off some constant cases.
816 (deftransform array-header-p ((array) (array))
817   (let ((type (continuation-type array)))
818     (unless (array-type-p type)
819       (give-up-ir1-transform))
820     (let ((dims (array-type-dimensions type)))
821       (cond ((csubtypep type (specifier-type '(simple-array * (*))))
822              ;; no array header
823              nil)
824             ((and (listp dims) (/= (length dims) 1))
825              ;; multi-dimensional array, will have a header
826              t)
827             (t
828              (give-up-ir1-transform))))))