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