a21399b3380cd6daa16707c08232e46087da5400
[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 ;;;; Derive-Type Optimizers
15
16 ;;; Array operations that use a specific number of indices implicitly assert
17 ;;; that the array is of that rank.
18 (defun assert-array-rank (array rank)
19   (assert-continuation-type
20    array
21    (specifier-type `(array * ,(make-list rank :initial-element '*)))))
22
23 ;;; Array access functions return an object from the array, hence its
24 ;;; type will be asserted to be array element type.
25 (defun extract-element-type (array)
26   (let ((type (continuation-type array)))
27     (if (array-type-p type)
28         (array-type-element-type type)
29         *universal-type*)))
30
31 ;;; Array access functions return an object from the array, hence its
32 ;;; type is going to be the array upgraded element type.
33 (defun extract-upgraded-element-type (array)
34   (let ((type (continuation-type array)))
35     (if (array-type-p type)
36         (array-type-specialized-element-type type)
37         *universal-type*)))
38
39 ;;; The ``new-value'' for array setters must fit in the array, and the
40 ;;; return type is going to be the same as the new-value for SETF
41 ;;; functions.
42 (defun assert-new-value-type (new-value array)
43   (let ((type (continuation-type array)))
44     (when (array-type-p type)
45       (assert-continuation-type new-value (array-type-element-type type))))
46   (continuation-type new-value))
47
48 ;;; Return true if Arg is NIL, or is a constant-continuation whose value is
49 ;;; NIL, false otherwise.
50 (defun unsupplied-or-nil (arg)
51   (declare (type (or continuation null) arg))
52   (or (not arg)
53       (and (constant-continuation-p arg)
54            (not (continuation-value arg)))))
55
56 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
57   (assert-array-rank array (length indices))
58   *universal-type*)
59
60 (defoptimizer (aref derive-type) ((array &rest indices) node)
61   (assert-array-rank array (length indices))
62   ;; If the node continuation has a single use then assert its type.
63   (let ((cont (node-cont node)))
64     (when (= (length (find-uses cont)) 1)
65       (assert-continuation-type cont (extract-element-type array))))
66   (extract-upgraded-element-type array))
67
68 (defoptimizer (%aset derive-type) ((array &rest stuff))
69   (assert-array-rank array (1- (length stuff)))
70   (assert-new-value-type (car (last stuff)) array))
71
72 (defoptimizer (hairy-data-vector-ref derive-type) ((array index))
73   (extract-upgraded-element-type array))
74 (defoptimizer (data-vector-ref derive-type) ((array index))
75   (extract-upgraded-element-type array))
76
77 (defoptimizer (data-vector-set derive-type) ((array index new-value))
78   (assert-new-value-type new-value array))
79 (defoptimizer (hairy-data-vector-set derive-type) ((array index new-value))
80   (assert-new-value-type new-value array))
81
82 ;;; Figure out the type of the data vector if we know the argument element
83 ;;; type.
84 (defoptimizer (%with-array-data derive-type) ((array start end))
85   (let ((atype (continuation-type array)))
86     (when (array-type-p atype)
87       (values-specifier-type
88        `(values (simple-array ,(type-specifier
89                                 (array-type-element-type atype))
90                               (*))
91                 index index index)))))
92
93 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
94   (assert-array-rank array (length indices))
95   *universal-type*)
96
97 (defoptimizer (row-major-aref derive-type) ((array index))
98   (extract-upgraded-element-type array))
99
100 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
101   (assert-new-value-type new-value array))
102
103 (defoptimizer (make-array derive-type)
104               ((dims &key initial-element element-type initial-contents
105                 adjustable fill-pointer displaced-index-offset displaced-to))
106   (let ((simple (and (unsupplied-or-nil adjustable)
107                      (unsupplied-or-nil displaced-to)
108                      (unsupplied-or-nil fill-pointer))))
109     (specifier-type
110      `(,(if simple 'simple-array 'array)
111        ,(cond ((not element-type) 't)
112               ((constant-continuation-p element-type)
113                (continuation-value element-type))
114               (t
115                '*))
116        ,(cond ((not simple)
117                '*)
118               ((constant-continuation-p dims)
119                (let ((val (continuation-value dims)))
120                  (if (listp val) val (list val))))
121               ((csubtypep (continuation-type dims)
122                           (specifier-type 'integer))
123                '(*))
124               (t
125                '*))))))
126 \f
127 ;;;; constructors
128
129 ;;; Convert VECTOR into a MAKE-ARRAY followed by SETFs of all the
130 ;;; elements.
131 (def-source-transform vector (&rest elements)
132   (if (byte-compiling)
133       (values nil t)
134       (let ((len (length elements))
135             (n -1))
136         (once-only ((n-vec `(make-array ,len)))
137           `(progn
138              ,@(mapcar #'(lambda (el)
139                            (once-only ((n-val el))
140                              `(locally (declare (optimize (safety 0)))
141                                        (setf (svref ,n-vec ,(incf n))
142                                              ,n-val))))
143                        elements)
144              ,n-vec)))))
145
146 ;;; Just convert it into a MAKE-ARRAY.
147 (def-source-transform make-string (length &key
148                                           (element-type ''base-char)
149                                           (initial-element default-init-char))
150   (if (byte-compiling)
151       (values nil t)
152       `(make-array (the index ,length)
153                    :element-type ,element-type
154                    :initial-element ,initial-element)))
155
156 (defparameter *array-info*
157   #((base-char #.default-init-char 8 sb!vm:simple-string-type)
158     (single-float 0.0s0 32 sb!vm:simple-array-single-float-type)
159     (double-float 0.0d0 64 sb!vm:simple-array-double-float-type)
160     #!+long-float (long-float 0.0l0 #!+x86 96 #!+sparc 128
161                               sb!vm:simple-array-long-float-type)
162     (bit 0 1 sb!vm:simple-bit-vector-type)
163     ((unsigned-byte 2) 0 2 sb!vm:simple-array-unsigned-byte-2-type)
164     ((unsigned-byte 4) 0 4 sb!vm:simple-array-unsigned-byte-4-type)
165     ((unsigned-byte 8) 0 8 sb!vm:simple-array-unsigned-byte-8-type)
166     ((unsigned-byte 16) 0 16 sb!vm:simple-array-unsigned-byte-16-type)
167     ((unsigned-byte 32) 0 32 sb!vm:simple-array-unsigned-byte-32-type)
168     ((signed-byte 8) 0 8 sb!vm:simple-array-signed-byte-8-type)
169     ((signed-byte 16) 0 16 sb!vm:simple-array-signed-byte-16-type)
170     ((signed-byte 30) 0 32 sb!vm:simple-array-signed-byte-30-type)
171     ((signed-byte 32) 0 32 sb!vm:simple-array-signed-byte-32-type)
172     ((complex single-float) #C(0.0s0 0.0s0) 64
173      sb!vm:simple-array-complex-single-float-type)
174     ((complex double-float) #C(0.0d0 0.0d0) 128
175      sb!vm:simple-array-complex-double-float-type)
176     #!+long-float
177     ((complex long-float) #C(0.0l0 0.0l0) #!+x86 192 #!+sparc 256
178      sb!vm:simple-array-complex-long-float-type)
179     (t 0 32 sb!vm:simple-vector-type)))
180
181 ;;; The integer type restriction on the length ensures that it will be
182 ;;; a vector. The lack of adjustable, fill-pointer, and displaced-to
183 ;;; keywords ensures that it will be simple.
184 (deftransform make-array ((length &key initial-element element-type)
185                           (integer &rest *))
186   (let* ((eltype (cond ((not element-type) t)
187                        ((not (constant-continuation-p element-type))
188                         (give-up-ir1-transform
189                          "ELEMENT-TYPE is not constant."))
190                        (t
191                         (continuation-value element-type))))
192          (len (if (constant-continuation-p length)
193                   (continuation-value length)
194                   '*))
195          (spec `(simple-array ,eltype (,len)))
196          (eltype-type (specifier-type eltype)))
197     (multiple-value-bind (default-initial-element element-size typecode)
198         (dovector (info *array-info*
199                         (give-up-ir1-transform
200                          "cannot open-code creation of ~S" spec))
201           (when (csubtypep eltype-type (specifier-type (car info)))
202             (return (values-list (cdr info)))))
203       (let* ((nwords-form
204               (if (>= element-size sb!vm:word-bits)
205                   `(* length ,(/ element-size sb!vm:word-bits))
206                   (let ((elements-per-word (/ 32 element-size)))
207                     `(truncate (+ length
208                                   ,(if (eq 'sb!vm:simple-string-type typecode)
209                                      ;; (Simple strings are stored with an
210                                      ;; extra trailing null for convenience
211                                      ;; in calling out to C.)
212                                      elements-per-word
213                                      (1- elements-per-word)))
214                                ,elements-per-word))))
215              (constructor
216               `(truly-the ,spec
217                           (allocate-vector ,typecode length ,nwords-form))))
218         (values
219          (cond ((and default-initial-element
220                      (or (null initial-element)
221                          (and (constant-continuation-p initial-element)
222                               (eql (continuation-value initial-element)
223                                    default-initial-element))))
224                 (unless (csubtypep (ctype-of default-initial-element)
225                                    eltype-type)
226                   ;; This situation arises e.g. in
227                   ;;   (MAKE-ARRAY 4 :ELEMENT-TYPE '(INTEGER 1 5))
228                   ;; ANSI's definition of MAKE-ARRAY says "If
229                   ;; INITIAL-ELEMENT is not supplied, the consequences
230                   ;; of later reading an uninitialized element of
231                   ;; new-array are undefined," so this could be legal
232                   ;; code as long as the user plans to write before he
233                   ;; reads, and if he doesn't we're free to do
234                   ;; anything we like. But in case the user doesn't
235                   ;; know to write before he reads, we'll signal a
236                   ;; STYLE-WARNING in case he didn't realize this.
237                   ;;
238                   ;; FIXME: should be STYLE-WARNING, not note
239                   (compiler-note "The default initial element ~S is not a ~S."
240                                  default-initial-element
241                                  eltype))
242                 constructor)
243                (t
244                 `(truly-the ,spec (fill ,constructor initial-element))))
245          '((declare (type index length))))))))
246
247 ;;; The list type restriction does not ensure that the result will be a
248 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
249 ;;; and displaced-to keywords ensures that it will be simple.
250 (deftransform make-array ((dims &key initial-element element-type)
251                           (list &rest *))
252   (unless (or (null element-type) (constant-continuation-p element-type))
253     (give-up-ir1-transform
254      "The element-type is not constant; cannot open code array creation."))
255   (unless (constant-continuation-p dims)
256     (give-up-ir1-transform
257      "The dimension list is not constant; cannot open code array creation."))
258   (let ((dims (continuation-value dims)))
259     (unless (every #'integerp dims)
260       (give-up-ir1-transform
261        "The dimension list contains something other than an integer: ~S"
262        dims))
263     (if (= (length dims) 1)
264         `(make-array ',(car dims)
265                      ,@(when initial-element
266                          '(:initial-element initial-element))
267                      ,@(when element-type
268                          '(:element-type element-type)))
269         (let* ((total-size (reduce #'* dims))
270                (rank (length dims))
271                (spec `(simple-array
272                        ,(cond ((null element-type) t)
273                               ((constant-continuation-p element-type)
274                                (continuation-value element-type))
275                               (t '*))
276                            ,(make-list rank :initial-element '*))))
277           `(let ((header (make-array-header sb!vm:simple-array-type ,rank)))
278              (setf (%array-fill-pointer header) ,total-size)
279              (setf (%array-fill-pointer-p header) nil)
280              (setf (%array-available-elements header) ,total-size)
281              (setf (%array-data-vector header)
282                    (make-array ,total-size
283                                ,@(when element-type
284                                    '(:element-type element-type))
285                                ,@(when initial-element
286                                    '(:initial-element initial-element))))
287              (setf (%array-displaced-p header) nil)
288              ,@(let ((axis -1))
289                  (mapcar #'(lambda (dim)
290                              `(setf (%array-dimension header ,(incf axis))
291                                     ,dim))
292                          dims))
293              (truly-the ,spec header))))))
294 \f
295 ;;;; miscellaneous properties of arrays
296
297 ;;; Transforms for various array properties. If the property is know
298 ;;; at compile time because of a type spec, use that constant value.
299
300 ;;; If we can tell the rank from the type info, use it instead.
301 (deftransform array-rank ((array))
302   (let ((array-type (continuation-type array)))
303     (unless (array-type-p array-type)
304       (give-up-ir1-transform))
305     (let ((dims (array-type-dimensions array-type)))
306       (if (not (listp dims))
307           (give-up-ir1-transform
308            "The array rank is not known at compile time: ~S"
309            dims)
310           (length dims)))))
311
312 ;;; If we know the dimensions at compile time, just use it. Otherwise,
313 ;;; if we can tell that the axis is in bounds, convert to
314 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
315 ;;; (if it's simple and a vector).
316 (deftransform array-dimension ((array axis)
317                                (array index))
318   (unless (constant-continuation-p axis)
319     (give-up-ir1-transform "The axis is not constant."))
320   (let ((array-type (continuation-type array))
321         (axis (continuation-value axis)))
322     (unless (array-type-p array-type)
323       (give-up-ir1-transform))
324     (let ((dims (array-type-dimensions array-type)))
325       (unless (listp dims)
326         (give-up-ir1-transform
327          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
328       (unless (> (length dims) axis)
329         (abort-ir1-transform "The array has dimensions ~S, ~D is too large."
330                              dims
331                              axis))
332       (let ((dim (nth axis dims)))
333         (cond ((integerp dim)
334                dim)
335               ((= (length dims) 1)
336                (ecase (array-type-complexp array-type)
337                  ((t)
338                   '(%array-dimension array 0))
339                  ((nil)
340                   '(length array))
341                  ((:maybe)
342                   (give-up-ir1-transform
343                    "can't tell whether array is simple"))))
344               (t
345                '(%array-dimension array axis)))))))
346
347 ;;; If the length has been declared and it's simple, just return it.
348 (deftransform length ((vector)
349                       ((simple-array * (*))))
350   (let ((type (continuation-type vector)))
351     (unless (array-type-p type)
352       (give-up-ir1-transform))
353     (let ((dims (array-type-dimensions type)))
354       (unless (and (listp dims) (integerp (car dims)))
355         (give-up-ir1-transform
356          "Vector length is unknown, must call LENGTH at runtime."))
357       (car dims))))
358
359 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
360 ;;; simple, it will extract the length slot from the vector. It it's
361 ;;; complex, it will extract the fill pointer slot from the array
362 ;;; header.
363 (deftransform length ((vector) (vector))
364   '(vector-length vector))
365
366 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
367 ;;; compile-time constant.
368 (deftransform vector-length ((vector) ((simple-array * (*))))
369   (let ((vtype (continuation-type vector)))
370     (if (array-type-p vtype)
371         (let ((dim (first (array-type-dimensions vtype))))
372           (when (eq dim '*) (give-up-ir1-transform))
373           dim)
374         (give-up-ir1-transform))))
375
376 ;;; Again, if we can tell the results from the type, just use it.
377 ;;; Otherwise, if we know the rank, convert into a computation based
378 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
379 ;;; multiplications because we know that the total size must be an
380 ;;; INDEX.
381 (deftransform array-total-size ((array)
382                                 (array))
383   (let ((array-type (continuation-type array)))
384     (unless (array-type-p array-type)
385       (give-up-ir1-transform))
386     (let ((dims (array-type-dimensions array-type)))
387       (unless (listp dims)
388         (give-up-ir1-transform "can't tell the rank at compile time"))
389       (if (member '* dims)
390           (do ((form 1 `(truly-the index
391                                    (* (array-dimension array ,i) ,form)))
392                (i 0 (1+ i)))
393               ((= i (length dims)) form))
394           (reduce #'* dims)))))
395
396 ;;; Only complex vectors have fill pointers.
397 (deftransform array-has-fill-pointer-p ((array))
398   (let ((array-type (continuation-type array)))
399     (unless (array-type-p array-type)
400       (give-up-ir1-transform))
401     (let ((dims (array-type-dimensions array-type)))
402       (if (and (listp dims) (not (= (length dims) 1)))
403           nil
404           (ecase (array-type-complexp array-type)
405             ((t)
406              t)
407             ((nil)
408              nil)
409             ((:maybe)
410              (give-up-ir1-transform
411               "The array type is ambiguous; must call ~
412               array-has-fill-pointer-p at runtime.")))))))
413
414 ;;; Primitive used to verify indices into arrays. If we can tell at
415 ;;; compile-time or we are generating unsafe code, don't bother with
416 ;;; the VOP.
417 (deftransform %check-bound ((array dimension index))
418   (unless (constant-continuation-p dimension)
419     (give-up-ir1-transform))
420   (let ((dim (continuation-value dimension)))
421     `(the (integer 0 ,dim) index)))
422 (deftransform %check-bound ((array dimension index) * *
423                             :policy (and (> speed safety) (= safety 0)))
424   'index)
425 \f
426 ;;;; array accessors
427
428 ;;; SVREF, %SVSET, SCHAR, %SCHARSET, CHAR,
429 ;;; %CHARSET, SBIT, %SBITSET, BIT, %BITSET
430 ;;;   --  source transforms.
431 ;;;
432 ;;; We convert all typed array accessors into aref and %aset with type
433 ;;; assertions on the array.
434 (macrolet ((define-frob (reffer setter type)
435              `(progn
436                 (def-source-transform ,reffer (a &rest i)
437                   (if (byte-compiling)
438                       (values nil t)
439                       `(aref (the ,',type ,a) ,@i)))
440                 (def-source-transform ,setter (a &rest i)
441                   (if (byte-compiling)
442                       (values nil t)
443                       `(%aset (the ,',type ,a) ,@i))))))
444   (define-frob svref %svset simple-vector)
445   (define-frob schar %scharset simple-string)
446   (define-frob char %charset string)
447   (define-frob sbit %sbitset (simple-array bit))
448   (define-frob bit %bitset (array bit)))
449
450 (macrolet (;; This is a handy macro for computing the row-major index
451            ;; given a set of indices. We wrap each index with a call
452            ;; to %CHECK-BOUND to ensure that everything works out
453            ;; correctly. We can wrap all the interior arithmetic with
454            ;; TRULY-THE INDEX because we know the the resultant
455            ;; row-major index must be an index.
456            (with-row-major-index ((array indices index &optional new-value)
457                                   &rest body)
458              `(let (n-indices dims)
459                 (dotimes (i (length ,indices))
460                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
461                   (push (make-symbol (format nil "DIM-~D" i)) dims))
462                 (setf n-indices (nreverse n-indices))
463                 (setf dims (nreverse dims))
464                 `(lambda (,',array ,@n-indices
465                                    ,@',(when new-value (list new-value)))
466                    (let* (,@(let ((,index -1))
467                               (mapcar #'(lambda (name)
468                                           `(,name (array-dimension
469                                                    ,',array
470                                                    ,(incf ,index))))
471                                       dims))
472                             (,',index
473                              ,(if (null dims)
474                                   0
475                                 (do* ((dims dims (cdr dims))
476                                       (indices n-indices (cdr indices))
477                                       (last-dim nil (car dims))
478                                       (form `(%check-bound ,',array
479                                                            ,(car dims)
480                                                            ,(car indices))
481                                             `(truly-the
482                                               index
483                                               (+ (truly-the index
484                                                             (* ,form
485                                                                ,last-dim))
486                                                  (%check-bound
487                                                   ,',array
488                                                   ,(car dims)
489                                                   ,(car indices))))))
490                                     ((null (cdr dims)) form)))))
491                      ,',@body)))))
492
493   ;; Just return the index after computing it.
494   (deftransform array-row-major-index ((array &rest indices))
495     (with-row-major-index (array indices index)
496       index))
497
498   ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
499   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
500   ;; expression for the row major index.
501   (deftransform aref ((array &rest indices))
502     (with-row-major-index (array indices index)
503       (hairy-data-vector-ref array index)))
504   (deftransform %aset ((array &rest stuff))
505     (let ((indices (butlast stuff)))
506       (with-row-major-index (array indices index new-value)
507         (hairy-data-vector-set array index new-value)))))
508
509 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
510 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
511 ;;; array total size.
512 (deftransform row-major-aref ((array index))
513   `(hairy-data-vector-ref array
514                           (%check-bound array (array-total-size array) index)))
515 (deftransform %set-row-major-aref ((array index new-value))
516   `(hairy-data-vector-set array
517                           (%check-bound array (array-total-size array) index)
518                           new-value))
519 \f
520 ;;;; bit-vector array operation canonicalization
521 ;;;;
522 ;;;; We convert all bit-vector operations to have the result array
523 ;;;; specified. This allows any result allocation to be open-coded,
524 ;;;; and eliminates the need for any VM-dependent transforms to handle
525 ;;;; these cases.
526
527 (dolist (fun '(bit-and bit-ior bit-xor bit-eqv bit-nand bit-nor bit-andc1
528                        bit-andc2 bit-orc1 bit-orc2))
529   ;; Make a result array if result is NIL or unsupplied.
530   (deftransform fun ((bit-array-1 bit-array-2 &optional result-bit-array)
531                      '(bit-vector bit-vector &optional null) '*
532                      :eval-name t
533                      :policy (>= speed space))
534     `(,fun bit-array-1 bit-array-2
535            (make-array (length bit-array-1) :element-type 'bit)))
536   ;; If result is T, make it the first arg.
537   (deftransform fun ((bit-array-1 bit-array-2 result-bit-array)
538                      '(bit-vector bit-vector (member t)) '*
539                      :eval-name t)
540     `(,fun bit-array-1 bit-array-2 bit-array-1)))
541
542 ;;; Similar for BIT-NOT, but there is only one arg...
543 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
544                        (bit-vector &optional null) *
545                        :policy (>= speed space))
546   '(bit-not bit-array-1
547             (make-array (length bit-array-1) :element-type 'bit)))
548 (deftransform bit-not ((bit-array-1 result-bit-array)
549                        (bit-vector (constant-argument t)))
550   '(bit-not bit-array-1 bit-array-1))
551 ;;; FIXME: What does (CONSTANT-ARGUMENT T) mean? Is it the same thing
552 ;;; as (CONSTANT-ARGUMENT (MEMBER T)), or does it mean any constant
553 ;;; value?
554 \f
555 ;;; Pick off some constant cases.
556 (deftransform array-header-p ((array) (array))
557   (let ((type (continuation-type array)))
558     (declare (optimize (safety 3)))
559     (unless (array-type-p type)
560       (give-up-ir1-transform))
561     (let ((dims (array-type-dimensions type)))
562       (cond ((csubtypep type (specifier-type '(simple-array * (*))))
563              ;; No array header.
564              nil)
565             ((and (listp dims) (> (length dims) 1))
566              ;; Multi-dimensional array, will have a header.
567              t)
568             (t
569              (give-up-ir1-transform))))))