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