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