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