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