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