0.pre7.14.flaky4.5:
[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 will be asserted to be array element type.
29 (defun extract-element-type (array)
30   (let ((type (continuation-type array)))
31     (if (array-type-p type)
32         (array-type-element-type type)
33         *universal-type*)))
34
35 ;;; Array access functions return an object from the array, hence its
36 ;;; type is going to be the array upgraded element type.
37 (defun extract-upgraded-element-type (array)
38   (let ((type (continuation-type array)))
39     (if (array-type-p type)
40         (array-type-specialized-element-type type)
41         *universal-type*)))
42
43 ;;; The ``new-value'' for array setters must fit in the array, and the
44 ;;; return type is going to be the same as the new-value for SETF
45 ;;; functions.
46 (defun assert-new-value-type (new-value array)
47   (let ((type (continuation-type array)))
48     (when (array-type-p type)
49       (assert-continuation-type new-value (array-type-element-type type))))
50   (continuation-type new-value))
51
52 ;;; Return true if Arg is NIL, or is a constant-continuation whose
53 ;;; value is NIL, false otherwise.
54 (defun unsupplied-or-nil (arg)
55   (declare (type (or continuation null) arg))
56   (or (not arg)
57       (and (constant-continuation-p arg)
58            (not (continuation-value arg)))))
59 \f
60 ;;;; DERIVE-TYPE optimizers
61
62 ;;; Array operations that use a specific number of indices implicitly
63 ;;; assert that the array is of that rank.
64 (defun assert-array-rank (array rank)
65   (assert-continuation-type
66    array
67    (specifier-type `(array * ,(make-list rank :initial-element '*)))))
68
69 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
70   (assert-array-rank array (length indices))
71   *universal-type*)
72
73 (defoptimizer (aref derive-type) ((array &rest indices) node)
74   (assert-array-rank array (length indices))
75   ;; If the node continuation has a single use then assert its type.
76   (let ((cont (node-cont node)))
77     (when (= (length (find-uses cont)) 1)
78       (assert-continuation-type cont (extract-element-type array))))
79   (extract-upgraded-element-type array))
80
81 (defoptimizer (%aset derive-type) ((array &rest stuff))
82   (assert-array-rank array (1- (length stuff)))
83   (assert-new-value-type (car (last stuff)) array))
84
85 (defoptimizer (hairy-data-vector-ref derive-type) ((array index))
86   (extract-upgraded-element-type array))
87 (defoptimizer (data-vector-ref derive-type) ((array index))
88   (extract-upgraded-element-type array))
89
90 (defoptimizer (data-vector-set derive-type) ((array index new-value))
91   (assert-new-value-type new-value array))
92 (defoptimizer (hairy-data-vector-set derive-type) ((array index new-value))
93   (assert-new-value-type new-value array))
94
95 ;;; Figure out the type of the data vector if we know the argument
96 ;;; element type.
97 (defoptimizer (%with-array-data derive-type) ((array start end))
98   (let ((atype (continuation-type array)))
99     (when (array-type-p atype)
100       (values-specifier-type
101        `(values (simple-array ,(type-specifier
102                                 (array-type-element-type atype))
103                               (*))
104                 index index index)))))
105
106 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
107   (assert-array-rank array (length indices))
108   *universal-type*)
109
110 (defoptimizer (row-major-aref derive-type) ((array index))
111   (extract-upgraded-element-type array))
112
113 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
114   (assert-new-value-type new-value array))
115
116 (defoptimizer (make-array derive-type)
117               ((dims &key initial-element element-type initial-contents
118                 adjustable fill-pointer displaced-index-offset displaced-to))
119   (let ((simple (and (unsupplied-or-nil adjustable)
120                      (unsupplied-or-nil displaced-to)
121                      (unsupplied-or-nil fill-pointer))))
122     (specifier-type
123      `(,(if simple 'simple-array 'array)
124        ,(cond ((not element-type) t)
125               ((constant-continuation-p element-type)
126                (continuation-value element-type))
127               (t
128                '*))
129        ,(cond ((not simple)
130                '*)
131               ((constant-continuation-p dims)
132                (let ((val (continuation-value dims)))
133                  (if (listp val) val (list val))))
134               ((csubtypep (continuation-type dims)
135                           (specifier-type 'integer))
136                '(*))
137               (t
138                '*))))))
139 \f
140 ;;;; constructors
141
142 ;;; Convert VECTOR into a MAKE-ARRAY followed by SETFs of all the
143 ;;; elements.
144 (def-source-transform vector (&rest elements)
145   (if (byte-compiling)
146       (values nil t)
147       (let ((len (length elements))
148             (n -1))
149         (once-only ((n-vec `(make-array ,len)))
150           `(progn
151              ,@(mapcar #'(lambda (el)
152                            (once-only ((n-val el))
153                              `(locally (declare (optimize (safety 0)))
154                                        (setf (svref ,n-vec ,(incf n))
155                                              ,n-val))))
156                        elements)
157              ,n-vec)))))
158
159 ;;; Just convert it into a MAKE-ARRAY.
160 (def-source-transform make-string (length &key
161                                           (element-type ''base-char)
162                                           (initial-element default-init-char))
163   (if (byte-compiling)
164       (values nil t)
165       `(make-array (the index ,length)
166                    :element-type ,element-type
167                    :initial-element ,initial-element)))
168
169 (defparameter *array-info*
170   #((base-char #.default-init-char 8 sb!vm:simple-string-type)
171     (single-float 0.0s0 32 sb!vm:simple-array-single-float-type)
172     (double-float 0.0d0 64 sb!vm:simple-array-double-float-type)
173     #!+long-float (long-float 0.0l0 #!+x86 96 #!+sparc 128
174                               sb!vm:simple-array-long-float-type)
175     (bit 0 1 sb!vm:simple-bit-vector-type)
176     ((unsigned-byte 2) 0 2 sb!vm:simple-array-unsigned-byte-2-type)
177     ((unsigned-byte 4) 0 4 sb!vm:simple-array-unsigned-byte-4-type)
178     ((unsigned-byte 8) 0 8 sb!vm:simple-array-unsigned-byte-8-type)
179     ((unsigned-byte 16) 0 16 sb!vm:simple-array-unsigned-byte-16-type)
180     ((unsigned-byte 32) 0 32 sb!vm:simple-array-unsigned-byte-32-type)
181     ((signed-byte 8) 0 8 sb!vm:simple-array-signed-byte-8-type)
182     ((signed-byte 16) 0 16 sb!vm:simple-array-signed-byte-16-type)
183     ((signed-byte 30) 0 32 sb!vm:simple-array-signed-byte-30-type)
184     ((signed-byte 32) 0 32 sb!vm:simple-array-signed-byte-32-type)
185     ((complex single-float) #C(0.0s0 0.0s0) 64
186      sb!vm:simple-array-complex-single-float-type)
187     ((complex double-float) #C(0.0d0 0.0d0) 128
188      sb!vm:simple-array-complex-double-float-type)
189     #!+long-float
190     ((complex long-float) #C(0.0l0 0.0l0) #!+x86 192 #!+sparc 256
191      sb!vm:simple-array-complex-long-float-type)
192     (t 0 32 sb!vm:simple-vector-type)))
193
194 ;;; The integer type restriction on the length ensures that it will be
195 ;;; a vector. The lack of adjustable, fill-pointer, and displaced-to
196 ;;; keywords ensures that it will be simple.
197 (deftransform make-array ((length &key initial-element element-type)
198                           (integer &rest *))
199   (let* ((eltype (cond ((not element-type) t)
200                        ((not (constant-continuation-p element-type))
201                         (give-up-ir1-transform
202                          "ELEMENT-TYPE is not constant."))
203                        (t
204                         (continuation-value element-type))))
205          (len (if (constant-continuation-p length)
206                   (continuation-value length)
207                   '*))
208          (spec `(simple-array ,eltype (,len)))
209          (eltype-type (specifier-type eltype)))
210     (multiple-value-bind (default-initial-element element-size typecode)
211         (dovector (info *array-info*
212                         (give-up-ir1-transform
213                          "cannot open-code creation of ~S" spec))
214           (when (csubtypep eltype-type (specifier-type (car info)))
215             (return (values-list (cdr info)))))
216       (let* ((nwords-form
217               (if (>= element-size sb!vm:word-bits)
218                   `(* length ,(/ element-size sb!vm:word-bits))
219                   (let ((elements-per-word (/ 32 element-size)))
220                     `(truncate (+ length
221                                   ,(if (eq 'sb!vm:simple-string-type typecode)
222                                      ;; (Simple strings are stored with an
223                                      ;; extra trailing null for convenience
224                                      ;; in calling out to C.)
225                                      elements-per-word
226                                      (1- elements-per-word)))
227                                ,elements-per-word))))
228              (constructor
229               `(truly-the ,spec
230                           (allocate-vector ,typecode length ,nwords-form))))
231         (values
232          (cond ((and default-initial-element
233                      (or (null initial-element)
234                          (and (constant-continuation-p initial-element)
235                               (eql (continuation-value initial-element)
236                                    default-initial-element))))
237                 (unless (csubtypep (ctype-of default-initial-element)
238                                    eltype-type)
239                   ;; This situation arises e.g. in
240                   ;;   (MAKE-ARRAY 4 :ELEMENT-TYPE '(INTEGER 1 5))
241                   ;; ANSI's definition of MAKE-ARRAY says "If
242                   ;; INITIAL-ELEMENT is not supplied, the consequences
243                   ;; of later reading an uninitialized element of
244                   ;; new-array are undefined," so this could be legal
245                   ;; code as long as the user plans to write before he
246                   ;; reads, and if he doesn't we're free to do
247                   ;; anything we like. But in case the user doesn't
248                   ;; know to write before he reads, we'll signal a
249                   ;; STYLE-WARNING in case he didn't realize this.
250                   ;;
251                   ;; FIXME: should be STYLE-WARNING, not note
252                   (compiler-note "The default initial element ~S is not a ~S."
253                                  default-initial-element
254                                  eltype))
255                 constructor)
256                (t
257                 `(truly-the ,spec (fill ,constructor initial-element))))
258          '((declare (type index length))))))))
259
260 ;;; The list type restriction does not ensure that the result will be a
261 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
262 ;;; and displaced-to keywords ensures that it will be simple.
263 (deftransform make-array ((dims &key initial-element element-type)
264                           (list &rest *))
265   (unless (or (null element-type) (constant-continuation-p element-type))
266     (give-up-ir1-transform
267      "The element-type is not constant; cannot open code array creation."))
268   (unless (constant-continuation-p dims)
269     (give-up-ir1-transform
270      "The dimension list is not constant; cannot open code array creation."))
271   (let ((dims (continuation-value dims)))
272     (unless (every #'integerp dims)
273       (give-up-ir1-transform
274        "The dimension list contains something other than an integer: ~S"
275        dims))
276     (if (= (length dims) 1)
277         `(make-array ',(car dims)
278                      ,@(when initial-element
279                          '(:initial-element initial-element))
280                      ,@(when element-type
281                          '(:element-type element-type)))
282         (let* ((total-size (reduce #'* dims))
283                (rank (length dims))
284                (spec `(simple-array
285                        ,(cond ((null element-type) t)
286                               ((constant-continuation-p element-type)
287                                (continuation-value element-type))
288                               (t '*))
289                            ,(make-list rank :initial-element '*))))
290           `(let ((header (make-array-header sb!vm:simple-array-type ,rank)))
291              (setf (%array-fill-pointer header) ,total-size)
292              (setf (%array-fill-pointer-p header) nil)
293              (setf (%array-available-elements header) ,total-size)
294              (setf (%array-data-vector header)
295                    (make-array ,total-size
296                                ,@(when element-type
297                                    '(:element-type element-type))
298                                ,@(when initial-element
299                                    '(:initial-element initial-element))))
300              (setf (%array-displaced-p header) nil)
301              ,@(let ((axis -1))
302                  (mapcar #'(lambda (dim)
303                              `(setf (%array-dimension header ,(incf axis))
304                                     ,dim))
305                          dims))
306              (truly-the ,spec header))))))
307 \f
308 ;;;; miscellaneous properties of arrays
309
310 ;;; Transforms for various array properties. If the property is know
311 ;;; at compile time because of a type spec, use that constant value.
312
313 ;;; If we can tell the rank from the type info, use it instead.
314 (deftransform array-rank ((array))
315   (let ((array-type (continuation-type array)))
316     (unless (array-type-p array-type)
317       (give-up-ir1-transform))
318     (let ((dims (array-type-dimensions array-type)))
319       (if (not (listp dims))
320           (give-up-ir1-transform
321            "The array rank is not known at compile time: ~S"
322            dims)
323           (length dims)))))
324
325 ;;; If we know the dimensions at compile time, just use it. Otherwise,
326 ;;; if we can tell that the axis is in bounds, convert to
327 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
328 ;;; (if it's simple and a vector).
329 (deftransform array-dimension ((array axis)
330                                (array index))
331   (unless (constant-continuation-p axis)
332     (give-up-ir1-transform "The axis is not constant."))
333   (let ((array-type (continuation-type array))
334         (axis (continuation-value axis)))
335     (unless (array-type-p array-type)
336       (give-up-ir1-transform))
337     (let ((dims (array-type-dimensions array-type)))
338       (unless (listp dims)
339         (give-up-ir1-transform
340          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
341       (unless (> (length dims) axis)
342         (abort-ir1-transform "The array has dimensions ~S, ~D is too large."
343                              dims
344                              axis))
345       (let ((dim (nth axis dims)))
346         (cond ((integerp dim)
347                dim)
348               ((= (length dims) 1)
349                (ecase (array-type-complexp array-type)
350                  ((t)
351                   '(%array-dimension array 0))
352                  ((nil)
353                   '(length array))
354                  ((:maybe)
355                   (give-up-ir1-transform
356                    "can't tell whether array is simple"))))
357               (t
358                '(%array-dimension array axis)))))))
359
360 ;;; If the length has been declared and it's simple, just return it.
361 (deftransform length ((vector)
362                       ((simple-array * (*))))
363   (let ((type (continuation-type vector)))
364     (unless (array-type-p type)
365       (give-up-ir1-transform))
366     (let ((dims (array-type-dimensions type)))
367       (unless (and (listp dims) (integerp (car dims)))
368         (give-up-ir1-transform
369          "Vector length is unknown, must call LENGTH at runtime."))
370       (car dims))))
371
372 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
373 ;;; simple, it will extract the length slot from the vector. It it's
374 ;;; complex, it will extract the fill pointer slot from the array
375 ;;; header.
376 (deftransform length ((vector) (vector))
377   '(vector-length vector))
378
379 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
380 ;;; compile-time constant.
381 (deftransform vector-length ((vector) ((simple-array * (*))))
382   (let ((vtype (continuation-type vector)))
383     (if (array-type-p vtype)
384         (let ((dim (first (array-type-dimensions vtype))))
385           (when (eq dim '*) (give-up-ir1-transform))
386           dim)
387         (give-up-ir1-transform))))
388
389 ;;; Again, if we can tell the results from the type, just use it.
390 ;;; Otherwise, if we know the rank, convert into a computation based
391 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
392 ;;; multiplications because we know that the total size must be an
393 ;;; INDEX.
394 (deftransform array-total-size ((array)
395                                 (array))
396   (let ((array-type (continuation-type array)))
397     (unless (array-type-p array-type)
398       (give-up-ir1-transform))
399     (let ((dims (array-type-dimensions array-type)))
400       (unless (listp dims)
401         (give-up-ir1-transform "can't tell the rank at compile time"))
402       (if (member '* dims)
403           (do ((form 1 `(truly-the index
404                                    (* (array-dimension array ,i) ,form)))
405                (i 0 (1+ i)))
406               ((= i (length dims)) form))
407           (reduce #'* dims)))))
408
409 ;;; Only complex vectors have fill pointers.
410 (deftransform array-has-fill-pointer-p ((array))
411   (let ((array-type (continuation-type array)))
412     (unless (array-type-p array-type)
413       (give-up-ir1-transform))
414     (let ((dims (array-type-dimensions array-type)))
415       (if (and (listp dims) (not (= (length dims) 1)))
416           nil
417           (ecase (array-type-complexp array-type)
418             ((t)
419              t)
420             ((nil)
421              nil)
422             ((:maybe)
423              (give-up-ir1-transform
424               "The array type is ambiguous; must call ~
425               ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
426
427 ;;; Primitive used to verify indices into arrays. If we can tell at
428 ;;; compile-time or we are generating unsafe code, don't bother with
429 ;;; the VOP.
430 (deftransform %check-bound ((array dimension index))
431   (unless (constant-continuation-p dimension)
432     (give-up-ir1-transform))
433   (let ((dim (continuation-value dimension)))
434     `(the (integer 0 ,dim) index)))
435 (deftransform %check-bound ((array dimension index) * *
436                             :policy (and (> speed safety) (= safety 0)))
437   'index)
438 \f
439 ;;;; WITH-ARRAY-DATA
440
441 ;;; This checks to see whether the array is simple and the start and
442 ;;; end are in bounds. If so, it proceeds with those values.
443 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
444 ;;; may be further optimized.
445 ;;;
446 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
447 ;;; START-VAR and END-VAR to the start and end of the designated
448 ;;; portion of the data vector. SVALUE and EVALUE are any start and
449 ;;; end specified to the original operation, and are factored into the
450 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
451 ;;; offset of all displacements encountered, and does not include
452 ;;; SVALUE.
453 ;;;
454 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
455 ;;; forced to be inline, overriding the ordinary judgment of the
456 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
457 ;;; fairly picky about their arguments, figuring that if you haven't
458 ;;; bothered to get all your ducks in a row, you probably don't care
459 ;;; that much about speed anyway! But in some cases it makes sense to
460 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
461 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
462 ;;; sense to use FORCE-INLINE option in that case.
463 (def!macro with-array-data (((data-var array &key offset-var)
464                              (start-var &optional (svalue 0))
465                              (end-var &optional (evalue nil))
466                              &key force-inline)
467                             &body forms)
468   (once-only ((n-array array)
469               (n-svalue `(the index ,svalue))
470               (n-evalue `(the (or index null) ,evalue)))
471     `(multiple-value-bind (,data-var
472                            ,start-var
473                            ,end-var
474                            ,@(when offset-var `(,offset-var)))
475          (if (not (array-header-p ,n-array))
476              (let ((,n-array ,n-array))
477                (declare (type (simple-array * (*)) ,n-array))
478                ,(once-only ((n-len `(length ,n-array))
479                             (n-end `(or ,n-evalue ,n-len)))
480                   `(if (<= ,n-svalue ,n-end ,n-len)
481                        ;; success
482                        (values ,n-array ,n-svalue ,n-end 0)
483                        ;; failure: Make a NOTINLINE call to
484                        ;; %WITH-ARRAY-DATA with our bad data
485                        ;; to cause the error to be signalled.
486                        (locally
487                          (declare (notinline %with-array-data))
488                          (%with-array-data ,n-array ,n-svalue ,n-evalue)))))
489              (,(if force-inline '%with-array-data-macro '%with-array-data)
490               ,n-array ,n-svalue ,n-evalue))
491        ,@forms)))
492
493 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
494 ;;; DEFTRANSFORMs and DEFUNs.
495 (def!macro %with-array-data-macro (array
496                                    start
497                                    end
498                                    &key
499                                    (element-type '*)
500                                    unsafe?
501                                    fail-inline?)
502   (/show "in %WITH-ARRAY-DATA-MACRO, yes.." array start end)
503   (let ((size (gensym "SIZE-"))
504         (defaulted-end (gensym "DEFAULTED-END-"))
505         (data (gensym "DATA-"))
506         (cumulative-offset (gensym "CUMULATIVE-OFFSET-")))
507     `(let* ((,size (array-total-size ,array))
508             (,defaulted-end
509               (cond (,end
510                      (unless (or ,unsafe? (<= ,end ,size))
511                        ,(if fail-inline?
512                             `(error "End ~D is greater than total size ~D."
513                                     ,end ,size)
514                             `(failed-%with-array-data ,array ,start ,end)))
515                      ,end)
516                     (t ,size))))
517        (unless (or ,unsafe? (<= ,start ,defaulted-end))
518          ,(if fail-inline?
519               `(error "Start ~D is greater than end ~D." ,start ,defaulted-end)
520               `(failed-%with-array-data ,array ,start ,end)))
521        (do ((,data ,array (%array-data-vector ,data))
522             (,cumulative-offset 0
523                                 (+ ,cumulative-offset
524                                    (%array-displacement ,data))))
525            ((not (array-header-p ,data))
526             (values (the (simple-array ,element-type 1) ,data)
527                     (the index (+ ,cumulative-offset ,start))
528                     (the index (+ ,cumulative-offset ,defaulted-end))
529                     (the index ,cumulative-offset)))
530          (declare (type index ,cumulative-offset))))))
531
532 (deftransform %with-array-data ((array start end)
533                                 ;; Note: This transform is limited to
534                                 ;; VECTOR only because I happened to
535                                 ;; create it in order to get sequence
536                                 ;; function operations to be more
537                                 ;; efficient. It might very well be
538                                 ;; reasonable to allow general ARRAY
539                                 ;; here, I just haven't tried to
540                                 ;; understand the performance issues
541                                 ;; involved. -- WHN
542                                 (vector index (or index null))
543                                 *
544                                 :important t
545                                 :node node
546                                 :policy (> speed space))
547   "inline non-SIMPLE-vector-handling logic"
548   (let ((element-type (upgraded-element-type-specifier-or-give-up array)))
549     `(%with-array-data-macro array start end
550                              :unsafe? ,(policy node (= safety 0))
551                              :element-type ,element-type)))
552 \f
553 ;;;; array accessors
554
555 ;;; We convert all typed array accessors into AREF and %ASET with type
556 ;;; assertions on the array.
557 (macrolet ((define-frob (reffer setter type)
558              `(progn
559                 (def-source-transform ,reffer (a &rest i)
560                   (if (byte-compiling)
561                       (values nil t)
562                       `(aref (the ,',type ,a) ,@i)))
563                 (def-source-transform ,setter (a &rest i)
564                   (if (byte-compiling)
565                       (values nil t)
566                       `(%aset (the ,',type ,a) ,@i))))))
567   (define-frob svref %svset simple-vector)
568   (define-frob schar %scharset simple-string)
569   (define-frob char %charset string)
570   (define-frob sbit %sbitset (simple-array bit))
571   (define-frob bit %bitset (array bit)))
572
573 (macrolet (;; This is a handy macro for computing the row-major index
574            ;; given a set of indices. We wrap each index with a call
575            ;; to %CHECK-BOUND to ensure that everything works out
576            ;; correctly. We can wrap all the interior arithmetic with
577            ;; TRULY-THE INDEX because we know the the resultant
578            ;; row-major index must be an index.
579            (with-row-major-index ((array indices index &optional new-value)
580                                   &rest body)
581              `(let (n-indices dims)
582                 (dotimes (i (length ,indices))
583                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
584                   (push (make-symbol (format nil "DIM-~D" i)) dims))
585                 (setf n-indices (nreverse n-indices))
586                 (setf dims (nreverse dims))
587                 `(lambda (,',array ,@n-indices
588                                    ,@',(when new-value (list new-value)))
589                    (let* (,@(let ((,index -1))
590                               (mapcar (lambda (name)
591                                         `(,name (array-dimension
592                                                  ,',array
593                                                  ,(incf ,index))))
594                                       dims))
595                             (,',index
596                              ,(if (null dims)
597                                   0
598                                 (do* ((dims dims (cdr dims))
599                                       (indices n-indices (cdr indices))
600                                       (last-dim nil (car dims))
601                                       (form `(%check-bound ,',array
602                                                            ,(car dims)
603                                                            ,(car indices))
604                                             `(truly-the
605                                               index
606                                               (+ (truly-the index
607                                                             (* ,form
608                                                                ,last-dim))
609                                                  (%check-bound
610                                                   ,',array
611                                                   ,(car dims)
612                                                   ,(car indices))))))
613                                     ((null (cdr dims)) form)))))
614                      ,',@body)))))
615
616   ;; Just return the index after computing it.
617   (deftransform array-row-major-index ((array &rest indices))
618     (with-row-major-index (array indices index)
619       index))
620
621   ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
622   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
623   ;; expression for the row major index.
624   (deftransform aref ((array &rest indices))
625     (with-row-major-index (array indices index)
626       (hairy-data-vector-ref array index)))
627   (deftransform %aset ((array &rest stuff))
628     (let ((indices (butlast stuff)))
629       (with-row-major-index (array indices index new-value)
630         (hairy-data-vector-set array index new-value)))))
631
632 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
633 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
634 ;;; array total size.
635 (deftransform row-major-aref ((array index))
636   `(hairy-data-vector-ref array
637                           (%check-bound array (array-total-size array) index)))
638 (deftransform %set-row-major-aref ((array index new-value))
639   `(hairy-data-vector-set array
640                           (%check-bound array (array-total-size array) index)
641                           new-value))
642 \f
643 ;;;; bit-vector array operation canonicalization
644 ;;;;
645 ;;;; We convert all bit-vector operations to have the result array
646 ;;;; specified. This allows any result allocation to be open-coded,
647 ;;;; and eliminates the need for any VM-dependent transforms to handle
648 ;;;; these cases.
649
650 (dolist (fun '(bit-and bit-ior bit-xor bit-eqv bit-nand bit-nor bit-andc1
651                        bit-andc2 bit-orc1 bit-orc2))
652   ;; Make a result array if result is NIL or unsupplied.
653   (deftransform fun ((bit-array-1 bit-array-2 &optional result-bit-array)
654                      '(bit-vector bit-vector &optional null) '*
655                      :eval-name t
656                      :policy (>= speed space))
657     `(,fun bit-array-1 bit-array-2
658            (make-array (length bit-array-1) :element-type 'bit)))
659   ;; If result is T, make it the first arg.
660   (deftransform fun ((bit-array-1 bit-array-2 result-bit-array)
661                      '(bit-vector bit-vector (member t)) '*
662                      :eval-name t)
663     `(,fun bit-array-1 bit-array-2 bit-array-1)))
664
665 ;;; Similar for BIT-NOT, but there is only one arg...
666 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
667                        (bit-vector &optional null) *
668                        :policy (>= speed space))
669   '(bit-not bit-array-1
670             (make-array (length bit-array-1) :element-type 'bit)))
671 (deftransform bit-not ((bit-array-1 result-bit-array)
672                        (bit-vector (constant-argument t)))
673   '(bit-not bit-array-1 bit-array-1))
674 ;;; FIXME: What does (CONSTANT-ARGUMENT T) mean? Is it the same thing
675 ;;; as (CONSTANT-ARGUMENT (MEMBER T)), or does it mean any constant
676 ;;; value?
677 \f
678 ;;; Pick off some constant cases.
679 (deftransform array-header-p ((array) (array))
680   (let ((type (continuation-type array)))
681     (declare (optimize (safety 3)))
682     (unless (array-type-p type)
683       (give-up-ir1-transform))
684     (let ((dims (array-type-dimensions type)))
685       (cond ((csubtypep type (specifier-type '(simple-array * (*))))
686              ;; No array header.
687              nil)
688             ((and (listp dims) (> (length dims) 1))
689              ;; Multi-dimensional array, will have a header.
690              t)
691             (t
692              (give-up-ir1-transform))))))