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