0.8.0.78.vector-nil-string.7:
[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 (deftransform make-array ((dims &key initial-element element-type
201                                      adjustable fill-pointer)
202                           (t &rest *))
203   (when (null initial-element)
204     (give-up-ir1-transform))
205   (let* ((eltype (cond ((not element-type) t)
206                        ((not (constant-continuation-p element-type))
207                         (give-up-ir1-transform
208                          "ELEMENT-TYPE is not constant."))
209                        (t
210                         (continuation-value element-type))))
211          (eltype-type (ir1-transform-specifier-type eltype))
212          (saetp (find-if (lambda (saetp)
213                            (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
214                          sb!vm:*specialized-array-element-type-properties*))
215          (creation-form `(make-array dims
216                           :element-type ',(type-specifier (sb!vm:saetp-ctype saetp))
217                           ,@(when fill-pointer
218                                   '(:fill-pointer fill-pointer))
219                           ,@(when adjustable
220                                   '(:adjustable adjustable)))))
221
222     (unless saetp
223       (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
224
225     (cond ((and (constant-continuation-p initial-element)
226                 (eql (continuation-value initial-element)
227                      (sb!vm:saetp-initial-element-default saetp)))
228            creation-form)
229           (t
230            ;; error checking for target, disabled on the host because
231            ;; (CTYPE-OF #\Null) is not possible.
232            #-sb-xc-host
233            (when (constant-continuation-p initial-element)
234              (let ((value (continuation-value initial-element)))
235                (cond
236                  ((not (ctypep value (sb!vm:saetp-ctype saetp)))
237                   ;; this case will cause an error at runtime, so we'd
238                   ;; better WARN about it now.
239                   (compiler-warn "~@<~S is not a ~S (which is the ~
240                                  UPGRADED-ARRAY-ELEMENT-TYPE of ~S).~@:>"
241                                  value
242                                  (type-specifier (sb!vm:saetp-ctype saetp))
243                                  eltype))
244                  ((not (ctypep value eltype-type))
245                   ;; this case will not cause an error at runtime, but
246                   ;; it's still worth STYLE-WARNing about.
247                   (compiler-style-warn "~S is not a ~S."
248                                        value eltype)))))
249            `(let ((array ,creation-form))
250              (multiple-value-bind (vector)
251                  (%data-vector-and-index array 0)
252                (fill vector initial-element))
253              array)))))
254
255 ;;; The integer type restriction on the length ensures that it will be
256 ;;; a vector. The lack of :ADJUSTABLE, :FILL-POINTER, and
257 ;;; :DISPLACED-TO keywords ensures that it will be simple; the lack of
258 ;;; :INITIAL-ELEMENT relies on another transform to deal with that
259 ;;; kind of initialization efficiently.
260 (deftransform make-array ((length &key element-type)
261                           (integer &rest *))
262   (let* ((eltype (cond ((not element-type) t)
263                        ((not (constant-continuation-p element-type))
264                         (give-up-ir1-transform
265                          "ELEMENT-TYPE is not constant."))
266                        (t
267                         (continuation-value element-type))))
268          (len (if (constant-continuation-p length)
269                   (continuation-value length)
270                   '*))
271          (result-type-spec `(simple-array ,eltype (,len)))
272          (eltype-type (ir1-transform-specifier-type eltype))
273          (saetp (find-if (lambda (saetp)
274                            (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
275                          sb!vm:*specialized-array-element-type-properties*)))
276     (unless saetp
277       (give-up-ir1-transform
278        "cannot open-code creation of ~S" result-type-spec))
279     #-sb-xc-host
280     (unless (csubtypep (ctype-of (sb!vm:saetp-initial-element-default saetp))
281                        eltype-type)
282       ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
283       ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
284       ;; INITIAL-ELEMENT is not supplied, the consequences of later
285       ;; reading an uninitialized element of new-array are undefined,"
286       ;; so this could be legal code as long as the user plans to
287       ;; write before he reads, and if he doesn't we're free to do
288       ;; anything we like. But in case the user doesn't know to write
289       ;; elements before he reads elements (or to read manuals before
290       ;; he writes code:-), we'll signal a STYLE-WARNING in case he
291       ;; didn't realize this.
292       (compiler-style-warn "The default initial element ~S is not a ~S."
293                            (sb!vm:saetp-initial-element-default saetp)
294                            eltype))
295     (let* ((n-bits-per-element (sb!vm:saetp-n-bits saetp))
296            (typecode (sb!vm:saetp-typecode saetp))
297            (n-pad-elements (sb!vm:saetp-n-pad-elements saetp))
298            (padded-length-form (if (zerop n-pad-elements)
299                                    'length
300                                    `(+ length ,n-pad-elements)))
301            (n-words-form
302             (cond
303               ((= n-bits-per-element 0) 0)
304               ((>= n-bits-per-element sb!vm:n-word-bits)
305                `(* ,padded-length-form
306                  (the fixnum ; i.e., not RATIO
307                    ,(/ n-bits-per-element sb!vm:n-word-bits))))
308               (t
309                (let ((n-elements-per-word (/ sb!vm:n-word-bits
310                                              n-bits-per-element)))
311                  (declare (type index n-elements-per-word)) ; i.e., not RATIO
312                  `(ceiling ,padded-length-form ,n-elements-per-word))))))
313       (values
314        `(truly-the ,result-type-spec
315          (allocate-vector ,typecode length ,n-words-form))
316        '((declare (type index length)))))))
317
318 ;;; The list type restriction does not ensure that the result will be a
319 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
320 ;;; and displaced-to keywords ensures that it will be simple.
321 ;;;
322 ;;; FIXME: should we generalize this transform to non-simple (though
323 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
324 ;;; deal with those? Maybe when the DEFTRANSFORM
325 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
326 ;;; CSR, 2002-07-01
327 (deftransform make-array ((dims &key element-type)
328                           (list &rest *))
329   (unless (or (null element-type) (constant-continuation-p element-type))
330     (give-up-ir1-transform
331      "The element-type is not constant; cannot open code array creation."))
332   (unless (constant-continuation-p dims)
333     (give-up-ir1-transform
334      "The dimension list is not constant; cannot open code array creation."))
335   (let ((dims (continuation-value dims)))
336     (unless (every #'integerp dims)
337       (give-up-ir1-transform
338        "The dimension list contains something other than an integer: ~S"
339        dims))
340     (if (= (length dims) 1)
341         `(make-array ',(car dims)
342                      ,@(when element-type
343                          '(:element-type element-type)))
344         (let* ((total-size (reduce #'* dims))
345                (rank (length dims))
346                (spec `(simple-array
347                        ,(cond ((null element-type) t)
348                               ((constant-continuation-p element-type)
349                                (continuation-value element-type))
350                               (t '*))
351                            ,(make-list rank :initial-element '*))))
352           `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank)))
353              (setf (%array-fill-pointer header) ,total-size)
354              (setf (%array-fill-pointer-p header) nil)
355              (setf (%array-available-elements header) ,total-size)
356              (setf (%array-data-vector header)
357                    (make-array ,total-size
358                                ,@(when element-type
359                                    '(:element-type element-type))))
360              (setf (%array-displaced-p header) nil)
361              ,@(let ((axis -1))
362                  (mapcar (lambda (dim)
363                            `(setf (%array-dimension header ,(incf axis))
364                                   ,dim))
365                          dims))
366              (truly-the ,spec header))))))
367 \f
368 ;;;; miscellaneous properties of arrays
369
370 ;;; Transforms for various array properties. If the property is know
371 ;;; at compile time because of a type spec, use that constant value.
372
373 ;;; If we can tell the rank from the type info, use it instead.
374 (deftransform array-rank ((array))
375   (let ((array-type (continuation-type array)))
376     (unless (array-type-p array-type)
377       (give-up-ir1-transform))
378     (let ((dims (array-type-dimensions array-type)))
379       (if (not (listp dims))
380           (give-up-ir1-transform
381            "The array rank is not known at compile time: ~S"
382            dims)
383           (length dims)))))
384
385 ;;; If we know the dimensions at compile time, just use it. Otherwise,
386 ;;; if we can tell that the axis is in bounds, convert to
387 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
388 ;;; (if it's simple and a vector).
389 (deftransform array-dimension ((array axis)
390                                (array index))
391   (unless (constant-continuation-p axis)
392     (give-up-ir1-transform "The axis is not constant."))
393   (let ((array-type (continuation-type array))
394         (axis (continuation-value axis)))
395     (unless (array-type-p array-type)
396       (give-up-ir1-transform))
397     (let ((dims (array-type-dimensions array-type)))
398       (unless (listp dims)
399         (give-up-ir1-transform
400          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
401       (unless (> (length dims) axis)
402         (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
403                              dims
404                              axis))
405       (let ((dim (nth axis dims)))
406         (cond ((integerp dim)
407                dim)
408               ((= (length dims) 1)
409                (ecase (array-type-complexp array-type)
410                  ((t)
411                   '(%array-dimension array 0))
412                  ((nil)
413                   '(length array))
414                  ((:maybe)
415                   (give-up-ir1-transform
416                    "can't tell whether array is simple"))))
417               (t
418                '(%array-dimension array axis)))))))
419
420 ;;; If the length has been declared and it's simple, just return it.
421 (deftransform length ((vector)
422                       ((simple-array * (*))))
423   (let ((type (continuation-type vector)))
424     (unless (array-type-p type)
425       (give-up-ir1-transform))
426     (let ((dims (array-type-dimensions type)))
427       (unless (and (listp dims) (integerp (car dims)))
428         (give-up-ir1-transform
429          "Vector length is unknown, must call LENGTH at runtime."))
430       (car dims))))
431
432 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
433 ;;; simple, it will extract the length slot from the vector. It it's
434 ;;; complex, it will extract the fill pointer slot from the array
435 ;;; header.
436 (deftransform length ((vector) (vector))
437   '(vector-length vector))
438
439 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
440 ;;; compile-time constant.
441 (deftransform vector-length ((vector))
442   (let ((vtype (continuation-type vector)))
443     (if (and (array-type-p vtype)
444              (not (array-type-complexp vtype)))
445         (let ((dim (first (array-type-dimensions vtype))))
446           (when (eq dim '*) (give-up-ir1-transform))
447           dim)
448         (give-up-ir1-transform))))
449
450 ;;; Again, if we can tell the results from the type, just use it.
451 ;;; Otherwise, if we know the rank, convert into a computation based
452 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
453 ;;; multiplications because we know that the total size must be an
454 ;;; INDEX.
455 (deftransform array-total-size ((array)
456                                 (array))
457   (let ((array-type (continuation-type array)))
458     (unless (array-type-p array-type)
459       (give-up-ir1-transform))
460     (let ((dims (array-type-dimensions array-type)))
461       (unless (listp dims)
462         (give-up-ir1-transform "can't tell the rank at compile time"))
463       (if (member '* dims)
464           (do ((form 1 `(truly-the index
465                                    (* (array-dimension array ,i) ,form)))
466                (i 0 (1+ i)))
467               ((= i (length dims)) form))
468           (reduce #'* dims)))))
469
470 ;;; Only complex vectors have fill pointers.
471 (deftransform array-has-fill-pointer-p ((array))
472   (let ((array-type (continuation-type array)))
473     (unless (array-type-p array-type)
474       (give-up-ir1-transform))
475     (let ((dims (array-type-dimensions array-type)))
476       (if (and (listp dims) (not (= (length dims) 1)))
477           nil
478           (ecase (array-type-complexp array-type)
479             ((t)
480              t)
481             ((nil)
482              nil)
483             ((:maybe)
484              (give-up-ir1-transform
485               "The array type is ambiguous; must call ~
486               ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
487
488 ;;; Primitive used to verify indices into arrays. If we can tell at
489 ;;; compile-time or we are generating unsafe code, don't bother with
490 ;;; the VOP.
491 (deftransform %check-bound ((array dimension index) * * :node node)
492   (cond ((policy node (and (> speed safety) (= safety 0)))
493          'index)
494         ((not (constant-continuation-p dimension))
495          (give-up-ir1-transform))
496         (t
497          (let ((dim (continuation-value dimension)))
498            `(the (integer 0 ,dim) index)))))
499 \f
500 ;;;; WITH-ARRAY-DATA
501
502 ;;; This checks to see whether the array is simple and the start and
503 ;;; end are in bounds. If so, it proceeds with those values.
504 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
505 ;;; may be further optimized.
506 ;;;
507 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
508 ;;; START-VAR and END-VAR to the start and end of the designated
509 ;;; portion of the data vector. SVALUE and EVALUE are any start and
510 ;;; end specified to the original operation, and are factored into the
511 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
512 ;;; offset of all displacements encountered, and does not include
513 ;;; SVALUE.
514 ;;;
515 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
516 ;;; forced to be inline, overriding the ordinary judgment of the
517 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
518 ;;; fairly picky about their arguments, figuring that if you haven't
519 ;;; bothered to get all your ducks in a row, you probably don't care
520 ;;; that much about speed anyway! But in some cases it makes sense to
521 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
522 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
523 ;;; sense to use FORCE-INLINE option in that case.
524 (def!macro with-array-data (((data-var array &key offset-var)
525                              (start-var &optional (svalue 0))
526                              (end-var &optional (evalue nil))
527                              &key force-inline)
528                             &body forms)
529   (once-only ((n-array array)
530               (n-svalue `(the index ,svalue))
531               (n-evalue `(the (or index null) ,evalue)))
532     `(multiple-value-bind (,data-var
533                            ,start-var
534                            ,end-var
535                            ,@(when offset-var `(,offset-var)))
536          (if (not (array-header-p ,n-array))
537              (let ((,n-array ,n-array))
538                (declare (type (simple-array * (*)) ,n-array))
539                ,(once-only ((n-len `(length ,n-array))
540                             (n-end `(or ,n-evalue ,n-len)))
541                   `(if (<= ,n-svalue ,n-end ,n-len)
542                        ;; success
543                        (values ,n-array ,n-svalue ,n-end 0)
544                        (failed-%with-array-data ,n-array
545                                                 ,n-svalue
546                                                 ,n-evalue))))
547              (,(if force-inline '%with-array-data-macro '%with-array-data)
548               ,n-array ,n-svalue ,n-evalue))
549        ,@forms)))
550
551 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
552 ;;; DEFTRANSFORMs and DEFUNs.
553 (def!macro %with-array-data-macro (array
554                                    start
555                                    end
556                                    &key
557                                    (element-type '*)
558                                    unsafe?
559                                    fail-inline?)
560   (with-unique-names (size defaulted-end data cumulative-offset)
561     `(let* ((,size (array-total-size ,array))
562             (,defaulted-end
563               (cond (,end
564                      (unless (or ,unsafe? (<= ,end ,size))
565                        ,(if fail-inline?
566                             `(error 'bounding-indices-bad-error
567                               :datum (cons ,start ,end)
568                               :expected-type `(cons (integer 0 ,',size)
569                                                     (integer ,',start ,',size))
570                               :object ,array)
571                             `(failed-%with-array-data ,array ,start ,end)))
572                      ,end)
573                     (t ,size))))
574        (unless (or ,unsafe? (<= ,start ,defaulted-end))
575          ,(if fail-inline?
576               `(error 'bounding-indices-bad-error
577                 :datum (cons ,start ,end)
578                 :expected-type `(cons (integer 0 ,',size)
579                                       (integer ,',start ,',size))
580                 :object ,array)
581               `(failed-%with-array-data ,array ,start ,end)))
582        (do ((,data ,array (%array-data-vector ,data))
583             (,cumulative-offset 0
584                                 (+ ,cumulative-offset
585                                    (%array-displacement ,data))))
586            ((not (array-header-p ,data))
587             (values (the (simple-array ,element-type 1) ,data)
588                     (the index (+ ,cumulative-offset ,start))
589                     (the index (+ ,cumulative-offset ,defaulted-end))
590                     (the index ,cumulative-offset)))
591          (declare (type index ,cumulative-offset))))))
592
593 (deftransform %with-array-data ((array start end)
594                                 ;; It might very well be reasonable to
595                                 ;; allow general ARRAY here, I just
596                                 ;; haven't tried to understand the
597                                 ;; performance issues involved. --
598                                 ;; WHN, and also CSR 2002-05-26
599                                 ((or vector simple-array) index (or index null))
600                                 *
601                                 :important t
602                                 :node node
603                                 :policy (> speed space))
604   "inline non-SIMPLE-vector-handling logic"
605   (let ((element-type (upgraded-element-type-specifier-or-give-up array)))
606     `(%with-array-data-macro array start end
607                              :unsafe? ,(policy node (= safety 0))
608                              :element-type ,element-type)))
609 \f
610 ;;;; array accessors
611
612 ;;; We convert all typed array accessors into AREF and %ASET with type
613 ;;; assertions on the array.
614 (macrolet ((define-frob (reffer setter type)
615              `(progn
616                 (define-source-transform ,reffer (a &rest i)
617                   `(aref (the ,',type ,a) ,@i))
618                 (define-source-transform ,setter (a &rest i)
619                   `(%aset (the ,',type ,a) ,@i)))))
620   (define-frob sbit %sbitset (simple-array bit))
621   (define-frob bit %bitset (array bit)))
622 (macrolet ((define-frob (reffer setter type)
623              `(progn
624                 (define-source-transform ,reffer (a i)
625                   `(aref (the ,',type ,a) ,i))
626                 (define-source-transform ,setter (a i v)
627                   `(%aset (the ,',type ,a) ,i ,v)))))
628   (define-frob svref %svset simple-vector)
629   (define-frob schar %scharset simple-string)
630   (define-frob char %charset string))
631
632 (macrolet (;; This is a handy macro for computing the row-major index
633            ;; given a set of indices. We wrap each index with a call
634            ;; to %CHECK-BOUND to ensure that everything works out
635            ;; correctly. We can wrap all the interior arithmetic with
636            ;; TRULY-THE INDEX because we know the the resultant
637            ;; row-major index must be an index.
638            (with-row-major-index ((array indices index &optional new-value)
639                                   &rest body)
640              `(let (n-indices dims)
641                 (dotimes (i (length ,indices))
642                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
643                   (push (make-symbol (format nil "DIM-~D" i)) dims))
644                 (setf n-indices (nreverse n-indices))
645                 (setf dims (nreverse dims))
646                 `(lambda (,',array ,@n-indices
647                                    ,@',(when new-value (list new-value)))
648                    (let* (,@(let ((,index -1))
649                               (mapcar (lambda (name)
650                                         `(,name (array-dimension
651                                                  ,',array
652                                                  ,(incf ,index))))
653                                       dims))
654                             (,',index
655                              ,(if (null dims)
656                                   0
657                                 (do* ((dims dims (cdr dims))
658                                       (indices n-indices (cdr indices))
659                                       (last-dim nil (car dims))
660                                       (form `(%check-bound ,',array
661                                                            ,(car dims)
662                                                            ,(car indices))
663                                             `(truly-the
664                                               index
665                                               (+ (truly-the index
666                                                             (* ,form
667                                                                ,last-dim))
668                                                  (%check-bound
669                                                   ,',array
670                                                   ,(car dims)
671                                                   ,(car indices))))))
672                                     ((null (cdr dims)) form)))))
673                      ,',@body)))))
674
675   ;; Just return the index after computing it.
676   (deftransform array-row-major-index ((array &rest indices))
677     (with-row-major-index (array indices index)
678       index))
679
680   ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
681   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
682   ;; expression for the row major index.
683   (deftransform aref ((array &rest indices))
684     (with-row-major-index (array indices index)
685       (hairy-data-vector-ref array index)))
686   (deftransform %aset ((array &rest stuff))
687     (let ((indices (butlast stuff)))
688       (with-row-major-index (array indices index new-value)
689         (hairy-data-vector-set array index new-value)))))
690
691 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
692 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
693 ;;; array total size.
694 (deftransform row-major-aref ((array index))
695   `(hairy-data-vector-ref array
696                           (%check-bound array (array-total-size array) index)))
697 (deftransform %set-row-major-aref ((array index new-value))
698   `(hairy-data-vector-set array
699                           (%check-bound array (array-total-size array) index)
700                           new-value))
701 \f
702 ;;;; bit-vector array operation canonicalization
703 ;;;;
704 ;;;; We convert all bit-vector operations to have the result array
705 ;;;; specified. This allows any result allocation to be open-coded,
706 ;;;; and eliminates the need for any VM-dependent transforms to handle
707 ;;;; these cases.
708
709 (macrolet ((def (fun)
710              `(progn
711                (deftransform ,fun ((bit-array-1 bit-array-2
712                                                 &optional result-bit-array)
713                                    (bit-vector bit-vector &optional null) *
714                                    :policy (>= speed space))
715                  `(,',fun bit-array-1 bit-array-2
716                    (make-array (length bit-array-1) :element-type 'bit)))
717                ;; If result is T, make it the first arg.
718                (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
719                                    (bit-vector bit-vector (member t)) *)
720                  `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
721   (def bit-and)
722   (def bit-ior)
723   (def bit-xor)
724   (def bit-eqv)
725   (def bit-nand)
726   (def bit-nor)
727   (def bit-andc1)
728   (def bit-andc2)
729   (def bit-orc1)
730   (def bit-orc2))
731
732 ;;; Similar for BIT-NOT, but there is only one arg...
733 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
734                        (bit-vector &optional null) *
735                        :policy (>= speed space))
736   '(bit-not bit-array-1
737             (make-array (length bit-array-1) :element-type 'bit)))
738 (deftransform bit-not ((bit-array-1 result-bit-array)
739                        (bit-vector (constant-arg t)))
740   '(bit-not bit-array-1 bit-array-1))
741 ;;; FIXME: What does (CONSTANT-ARG T) mean? Is it the same thing
742 ;;; as (CONSTANT-ARG (MEMBER T)), or does it mean any constant
743 ;;; value?
744 \f
745 ;;; Pick off some constant cases.
746 (deftransform array-header-p ((array) (array))
747   (let ((type (continuation-type array)))
748     (unless (array-type-p type)
749       (give-up-ir1-transform))
750     (let ((dims (array-type-dimensions type)))
751       (cond ((csubtypep type (specifier-type '(simple-array * (*))))
752              ;; no array header
753              nil)
754             ((and (listp dims) (/= (length dims) 1))
755              ;; multi-dimensional array, will have a header
756              t)
757             (t
758              (give-up-ir1-transform))))))