1.0.28.51: better MAKE-ARRAY transforms
[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 type is
28 ;;; going to be the array upgraded element type. Secondary return value is the
29 ;;; known supertype of the upgraded-array-element-type, if if the exact
30 ;;; U-A-E-T is not known. (If it is NIL, the primary return value is as good
31 ;;; as it gets.)
32 (defun extract-upgraded-element-type (array)
33   (let ((type (lvar-type array)))
34     (cond
35       ;; Note that this IF mightn't be satisfied even if the runtime
36       ;; value is known to be a subtype of some specialized ARRAY, because
37       ;; we can have values declared e.g. (AND SIMPLE-VECTOR UNKNOWN-TYPE),
38       ;; which are represented in the compiler as INTERSECTION-TYPE, not
39       ;; array type.
40       ((array-type-p type)
41        (values (array-type-specialized-element-type type) nil))
42       ;; fix for bug #396. This type logic corresponds to the special case for
43       ;; strings in HAIRY-DATA-VECTOR-REF (generic/vm-tran.lisp)
44       ((csubtypep type (specifier-type 'string))
45        (cond
46          ((csubtypep type (specifier-type '(array character (*))))
47           (values (specifier-type 'character) nil))
48          #!+sb-unicode
49          ((csubtypep type (specifier-type '(array base-char (*))))
50           (values (specifier-type 'base-char) nil))
51          ((csubtypep type (specifier-type '(array nil (*))))
52           (values *empty-type* nil))
53          (t
54           ;; See KLUDGE below.
55           (values *wild-type* (specifier-type 'character)))))
56       (t
57        ;; KLUDGE: there is no good answer here, but at least
58        ;; *wild-type* won't cause HAIRY-DATA-VECTOR-{REF,SET} to be
59        ;; erroneously optimized (see generic/vm-tran.lisp) -- CSR,
60        ;; 2002-08-21
61        (values *wild-type* nil)))))
62
63 (defun extract-declared-element-type (array)
64   (let ((type (lvar-type array)))
65     (if (array-type-p type)
66         (array-type-element-type type)
67         *wild-type*)))
68
69 ;;; The ``new-value'' for array setters must fit in the array, and the
70 ;;; return type is going to be the same as the new-value for SETF
71 ;;; functions.
72 (defun assert-new-value-type (new-value array)
73   (let ((type (lvar-type array)))
74     (when (array-type-p type)
75       (assert-lvar-type
76        new-value
77        (array-type-specialized-element-type type)
78        (lexenv-policy (node-lexenv (lvar-dest new-value))))))
79   (lvar-type new-value))
80
81 (defun assert-array-complex (array)
82   (assert-lvar-type
83    array
84    (make-array-type :complexp t
85                     :element-type *wild-type*)
86    (lexenv-policy (node-lexenv (lvar-dest array))))
87   nil)
88
89 ;;; Return true if ARG is NIL, or is a constant-lvar whose
90 ;;; value is NIL, false otherwise.
91 (defun unsupplied-or-nil (arg)
92   (declare (type (or lvar null) arg))
93   (or (not arg)
94       (and (constant-lvar-p arg)
95            (not (lvar-value arg)))))
96 \f
97 ;;;; DERIVE-TYPE optimizers
98
99 ;;; Array operations that use a specific number of indices implicitly
100 ;;; assert that the array is of that rank.
101 (defun assert-array-rank (array rank)
102   (assert-lvar-type
103    array
104    (specifier-type `(array * ,(make-list rank :initial-element '*)))
105    (lexenv-policy (node-lexenv (lvar-dest array)))))
106
107 (defun derive-aref-type (array)
108   (multiple-value-bind (uaet other) (extract-upgraded-element-type array)
109     (or other uaet)))
110
111 (defoptimizer (array-in-bounds-p derive-type) ((array &rest indices))
112   (assert-array-rank array (length indices))
113   *universal-type*)
114
115 (defoptimizer (aref derive-type) ((array &rest indices) node)
116   (assert-array-rank array (length indices))
117   (derive-aref-type array))
118
119 (defoptimizer (%aset derive-type) ((array &rest stuff))
120   (assert-array-rank array (1- (length stuff)))
121   (assert-new-value-type (car (last stuff)) array))
122
123 (macrolet ((define (name)
124              `(defoptimizer (,name derive-type) ((array index))
125                 (derive-aref-type array))))
126   (define hairy-data-vector-ref)
127   (define hairy-data-vector-ref/check-bounds)
128   (define data-vector-ref))
129
130 #!+(or x86 x86-64)
131 (defoptimizer (data-vector-ref-with-offset derive-type) ((array index offset))
132   (derive-aref-type array))
133
134 (macrolet ((define (name)
135              `(defoptimizer (,name derive-type) ((array index new-value))
136                 (assert-new-value-type new-value array))))
137   (define hairy-data-vector-set)
138   (define hairy-data-vector-set/check-bounds)
139   (define data-vector-set))
140
141 #!+(or x86 x86-64)
142 (defoptimizer (data-vector-set-with-offset derive-type) ((array index offset new-value))
143   (assert-new-value-type new-value array))
144
145 ;;; Figure out the type of the data vector if we know the argument
146 ;;; element type.
147 (defun derive-%with-array-data/mumble-type (array)
148   (let ((atype (lvar-type array)))
149     (when (array-type-p atype)
150       (specifier-type
151        `(simple-array ,(type-specifier
152                         (array-type-specialized-element-type atype))
153                       (*))))))
154 (defoptimizer (%with-array-data derive-type) ((array start end))
155   (derive-%with-array-data/mumble-type array))
156 (defoptimizer (%with-array-data/fp derive-type) ((array start end))
157   (derive-%with-array-data/mumble-type array))
158
159 (defoptimizer (array-row-major-index derive-type) ((array &rest indices))
160   (assert-array-rank array (length indices))
161   *universal-type*)
162
163 (defoptimizer (row-major-aref derive-type) ((array index))
164   (derive-aref-type array))
165
166 (defoptimizer (%set-row-major-aref derive-type) ((array index new-value))
167   (assert-new-value-type new-value array))
168
169 (defoptimizer (make-array derive-type)
170               ((dims &key initial-element element-type initial-contents
171                 adjustable fill-pointer displaced-index-offset displaced-to))
172   (let ((simple (and (unsupplied-or-nil adjustable)
173                      (unsupplied-or-nil displaced-to)
174                      (unsupplied-or-nil fill-pointer))))
175     (or (careful-specifier-type
176          `(,(if simple 'simple-array 'array)
177             ,(cond ((not element-type) t)
178                    ((constant-lvar-p element-type)
179                     (let ((ctype (careful-specifier-type
180                                   (lvar-value element-type))))
181                       (cond
182                         ((or (null ctype) (unknown-type-p ctype)) '*)
183                         (t (sb!xc:upgraded-array-element-type
184                             (lvar-value element-type))))))
185                    (t
186                     '*))
187             ,(cond ((constant-lvar-p dims)
188                     (let* ((val (lvar-value dims))
189                            (cdims (if (listp val) val (list val))))
190                       (if simple
191                           cdims
192                           (length cdims))))
193                    ((csubtypep (lvar-type dims)
194                                (specifier-type 'integer))
195                     '(*))
196                    (t
197                     '*))))
198         (specifier-type 'array))))
199
200 ;;; Complex array operations should assert that their array argument
201 ;;; is complex.  In SBCL, vectors with fill-pointers are complex.
202 (defoptimizer (fill-pointer derive-type) ((vector))
203   (assert-array-complex vector))
204 (defoptimizer (%set-fill-pointer derive-type) ((vector index))
205   (declare (ignorable index))
206   (assert-array-complex vector))
207
208 (defoptimizer (vector-push derive-type) ((object vector))
209   (declare (ignorable object))
210   (assert-array-complex vector))
211 (defoptimizer (vector-push-extend derive-type)
212     ((object vector &optional index))
213   (declare (ignorable object index))
214   (assert-array-complex vector))
215 (defoptimizer (vector-pop derive-type) ((vector))
216   (assert-array-complex vector))
217 \f
218 ;;;; constructors
219
220 ;;; Convert VECTOR into a MAKE-ARRAY.
221 (define-source-transform vector (&rest elements)
222   `(make-array ,(length elements) :initial-contents (list ,@elements)))
223
224 ;;; Just convert it into a MAKE-ARRAY.
225 (deftransform make-string ((length &key
226                                    (element-type 'character)
227                                    (initial-element
228                                     #.*default-init-char-form*)))
229   `(the simple-string (make-array (the index length)
230                        :element-type element-type
231                        ,@(when initial-element
232                            '(:initial-element initial-element)))))
233
234 ;;; Prevent open coding DIMENSION and :INITIAL-CONTENTS arguments,
235 ;;; so that we can pick them apart.
236 (define-source-transform make-array (&whole form &rest args)
237   (declare (ignore args))
238   (if (and (fun-lexically-notinline-p 'list)
239            (fun-lexically-notinline-p 'vector))
240       (values nil t)
241       `(locally (declare (notinline list vector))
242          ,form)))
243
244 ;;; This baby is a bit of a monster, but it takes care of any MAKE-ARRAY
245 ;;; call which creates a vector with a known element type -- and tries
246 ;;; to do a good job with all the different ways it can happen.
247 (defun transform-make-array-vector (length element-type initial-element
248                                     initial-contents call)
249   (aver (or (not element-type) (constant-lvar-p element-type)))
250   (let* ((c-length (when (constant-lvar-p length)
251                      (lvar-value length)))
252          (elt-spec (if element-type
253                        (lvar-value element-type)
254                        t))
255          (elt-ctype (ir1-transform-specifier-type elt-spec))
256          (saetp (if (unknown-type-p elt-ctype)
257                     (give-up-ir1-transform "~S is an unknown type: ~S"
258                                            :element-type elt-spec)
259                     (find-saetp-by-ctype elt-ctype)))
260          (default-initial-element (sb!vm:saetp-initial-element-default saetp))
261          (n-bits (sb!vm:saetp-n-bits saetp))
262          (typecode (sb!vm:saetp-typecode saetp))
263          (n-pad-elements (sb!vm:saetp-n-pad-elements saetp))
264          (n-words-form
265           (if c-length
266               (ceiling (* (+ c-length n-pad-elements) n-bits)
267                        sb!vm:n-word-bits)
268               (let ((padded-length-form (if (zerop n-pad-elements)
269                                             'length
270                                             `(+ length ,n-pad-elements))))
271                 (cond
272                   ((= n-bits 0) 0)
273                   ((>= n-bits sb!vm:n-word-bits)
274                    `(* ,padded-length-form
275                        ;; i.e., not RATIO
276                        ,(the fixnum (/ n-bits sb!vm:n-word-bits))))
277                   (t
278                    (let ((n-elements-per-word (/ sb!vm:n-word-bits n-bits)))
279                      (declare (type index n-elements-per-word)) ; i.e., not RATIO
280                      `(ceiling ,padded-length-form ,n-elements-per-word)))))))
281          (result-spec
282           `(simple-array ,(sb!vm:saetp-specifier saetp) (,(or c-length '*))))
283          (alloc-form
284           `(truly-the ,result-spec
285                       (allocate-vector ,typecode (the index length) ,n-words-form))))
286     (cond ((and initial-element initial-contents)
287            (abort-ir1-transform "Both ~S and ~S specified."
288                                 :initial-contents :initial-element))
289           ;; :INITIAL-CONTENTS (LIST ...), (VECTOR ...) and `(1 1 ,x) with a
290           ;; constant LENGTH.
291           ((and initial-contents c-length
292                 (lvar-matches initial-contents
293                               :fun-names '(list vector sb!impl::backq-list)
294                               :arg-count c-length))
295            (let ((parameters (eliminate-keyword-args
296                               call 1 '((:element-type element-type)
297                                        (:initial-contents initial-contents))))
298                  (elt-vars (make-gensym-list c-length))
299                  (lambda-list '(length)))
300              (splice-fun-args initial-contents :any c-length)
301              (dolist (p parameters)
302                (setf lambda-list
303                      (append lambda-list
304                              (if (eq p 'initial-contents)
305                                  elt-vars
306                                  (list p)))))
307              `(lambda ,lambda-list
308                 (declare (type ,elt-spec ,@elt-vars)
309                          (ignorable ,@lambda-list))
310                 (truly-the ,result-spec
311                  (initialize-vector ,alloc-form ,@elt-vars)))))
312           ;; constant :INITIAL-CONTENTS and LENGTH
313           ((and initial-contents c-length (constant-lvar-p initial-contents))
314            (let ((contents (lvar-value initial-contents)))
315              (unless (= c-length (length contents))
316                (abort-ir1-transform "~S has ~S elements, vector length is ~S."
317                                     :initial-contents (length contents) c-length))
318              (let ((parameters (eliminate-keyword-args
319                                 call 1 '((:element-type element-type)
320                                          (:initial-contents initial-contents)))))
321                `(lambda (length ,@parameters)
322                   (declare (ignorable ,@parameters))
323                   (truly-the ,result-spec
324                    (initialize-vector ,alloc-form
325                                       ,@(map 'list (lambda (elt)
326                                                      `(the ,elt-spec ,elt))
327                                              contents)))))))
328           ;; any other :INITIAL-CONTENTS
329           (initial-contents
330            (let ((parameters (eliminate-keyword-args
331                               call 1 '((:element-type element-type)
332                                        (:initial-contents initial-contents)))))
333              `(lambda (length ,@parameters)
334                 (declare (ignorable ,@parameters))
335                 (unless (= length (length initial-contents))
336                   (error "~S has ~S elements, vector length is ~S."
337                          :initial-contents (length initial-contents) length))
338                 (truly-the ,result-spec
339                            (replace ,alloc-form initial-contents)))))
340           ;; :INITIAL-ELEMENT, not EQL to the default
341           ((and initial-element
342                 (or (not (constant-lvar-p initial-element))
343                     (not (eql default-initial-element (lvar-value initial-element)))))
344            (let ((parameters (eliminate-keyword-args
345                               call 1 '((:element-type element-type)
346                                        (:initial-element initial-element)))))
347              `(lambda (length ,@parameters)
348                 (declare (ignorable ,@parameters))
349                 (truly-the ,result-spec
350                            (fill ,alloc-form (the ,elt-spec initial-element))))))
351           ;; just :ELEMENT-TYPE, or maybe with :INITIAL-ELEMENT EQL to the
352           ;; default
353           (t
354            #-sb-xc-host
355            (unless (ctypep default-initial-element elt-ctype)
356              ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
357              ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
358              ;; INITIAL-ELEMENT is not supplied, the consequences of later
359              ;; reading an uninitialized element of new-array are undefined,"
360              ;; so this could be legal code as long as the user plans to
361              ;; write before he reads, and if he doesn't we're free to do
362              ;; anything we like. But in case the user doesn't know to write
363              ;; elements before he reads elements (or to read manuals before
364              ;; he writes code:-), we'll signal a STYLE-WARNING in case he
365              ;; didn't realize this.
366              (if initial-element
367                  (compiler-warn "~S ~S is not a ~S"
368                                 :initial-element default-initial-element
369                                 elt-spec)
370                  (compiler-style-warn "The default initial element ~S is not a ~S."
371                                       default-initial-element
372                                       elt-spec)))
373            (let ((parameters (eliminate-keyword-args
374                               call 1 '((:element-type element-type)))))
375              `(lambda (length ,@parameters)
376                 (declare (ignorable ,@parameters))
377                 ,alloc-form))))))
378
379 (deftransform make-array ((dims &key
380                                 element-type initial-element initial-contents)
381                           (integer &key
382                                    (:element-type (constant-arg *))
383                                    (:initial-element *)
384                                    (:initial-contents *))
385                           *
386                           :node call)
387   (transform-make-array-vector dims
388                                element-type
389                                initial-element
390                                initial-contents
391                                call))
392
393 ;;; The list type restriction does not ensure that the result will be a
394 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
395 ;;; and displaced-to keywords ensures that it will be simple.
396 ;;;
397 ;;; FIXME: should we generalize this transform to non-simple (though
398 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
399 ;;; deal with those? Maybe when the DEFTRANSFORM
400 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
401 ;;; CSR, 2002-07-01
402 (deftransform make-array ((dims &key
403                                 element-type initial-element initial-contents)
404                           (list &key
405                                 (:element-type (constant-arg *))
406                                 (:initial-element *)
407                                 (:initial-contents *))
408                           *
409                           :node call)
410   (block make-array
411     (when (lvar-matches dims :fun-names '(list) :arg-count 1)
412       (let ((length (car (splice-fun-args dims :any 1))))
413         (return-from make-array
414           (transform-make-array-vector length
415                                        element-type
416                                        initial-element
417                                        initial-contents
418                                        call))))
419     (unless (constant-lvar-p dims)
420       (give-up-ir1-transform
421        "The dimension list is not constant; cannot open code array creation."))
422     (let ((dims (lvar-value dims)))
423       (unless (every #'integerp dims)
424         (give-up-ir1-transform
425          "The dimension list contains something other than an integer: ~S"
426          dims))
427       (if (= (length dims) 1)
428           `(make-array ',(car dims)
429                        ,@(when element-type
430                                '(:element-type element-type))
431                        ,@(when initial-element
432                                '(:initial-element initial-element))
433                        ,@(when initial-contents
434                                '(:initial-contents initial-contents)))
435           (let* ((total-size (reduce #'* dims))
436                  (rank (length dims))
437                  (spec `(simple-array
438                          ,(cond ((null element-type) t)
439                                 ((and (constant-lvar-p element-type)
440                                       (ir1-transform-specifier-type
441                                        (lvar-value element-type)))
442                                  (sb!xc:upgraded-array-element-type
443                                   (lvar-value element-type)))
444                                 (t '*))
445                          ,(make-list rank :initial-element '*))))
446             `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank))
447                    (data (make-array ,total-size
448                                      ,@(when element-type
449                                              '(:element-type element-type))
450                                      ,@(when initial-element
451                                              '(:initial-element initial-element)))))
452                ,@(when initial-contents
453                        ;; FIXME: This is could be open coded at least a bit too
454                        `((sb!impl::fill-data-vector data ',dims initial-contents)))
455                (setf (%array-fill-pointer header) ,total-size)
456                (setf (%array-fill-pointer-p header) nil)
457                (setf (%array-available-elements header) ,total-size)
458                (setf (%array-data-vector header) data)
459                (setf (%array-displaced-p header) nil)
460                (setf (%array-displaced-from header) nil)
461                ,@(let ((axis -1))
462                       (mapcar (lambda (dim)
463                                 `(setf (%array-dimension header ,(incf axis))
464                                        ,dim))
465                               dims))
466                (truly-the ,spec header)))))))
467
468 (deftransform make-array ((dims &key initial-element element-type
469                                      adjustable fill-pointer)
470                           (t &rest *))
471   (when (null initial-element)
472     (give-up-ir1-transform))
473   (let* ((eltype (cond ((not element-type) t)
474                        ((not (constant-lvar-p element-type))
475                         (give-up-ir1-transform
476                          "ELEMENT-TYPE is not constant."))
477                        (t
478                         (lvar-value element-type))))
479          (eltype-type (ir1-transform-specifier-type eltype))
480          (saetp (find-if (lambda (saetp)
481                            (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
482                          sb!vm:*specialized-array-element-type-properties*))
483          (creation-form `(make-array dims
484                           :element-type ',(type-specifier (sb!vm:saetp-ctype saetp))
485                           ,@(when fill-pointer
486                                   '(:fill-pointer fill-pointer))
487                           ,@(when adjustable
488                                   '(:adjustable adjustable)))))
489
490     (unless saetp
491       (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
492
493     (cond ((and (constant-lvar-p initial-element)
494                 (eql (lvar-value initial-element)
495                      (sb!vm:saetp-initial-element-default saetp)))
496            creation-form)
497           (t
498            ;; error checking for target, disabled on the host because
499            ;; (CTYPE-OF #\Null) is not possible.
500            #-sb-xc-host
501            (when (constant-lvar-p initial-element)
502              (let ((value (lvar-value initial-element)))
503                (cond
504                  ((not (ctypep value (sb!vm:saetp-ctype saetp)))
505                   ;; this case will cause an error at runtime, so we'd
506                   ;; better WARN about it now.
507                   (warn 'array-initial-element-mismatch
508                         :format-control "~@<~S is not a ~S (which is the ~
509                                          ~S of ~S).~@:>"
510                         :format-arguments
511                         (list
512                          value
513                          (type-specifier (sb!vm:saetp-ctype saetp))
514                          'upgraded-array-element-type
515                          eltype)))
516                  ((not (ctypep value eltype-type))
517                   ;; this case will not cause an error at runtime, but
518                   ;; it's still worth STYLE-WARNing about.
519                   (compiler-style-warn "~S is not a ~S."
520                                        value eltype)))))
521            `(let ((array ,creation-form))
522              (multiple-value-bind (vector)
523                  (%data-vector-and-index array 0)
524                (fill vector (the ,(sb!vm:saetp-specifier saetp) initial-element)))
525              array)))))
526 \f
527 ;;;; miscellaneous properties of arrays
528
529 ;;; Transforms for various array properties. If the property is know
530 ;;; at compile time because of a type spec, use that constant value.
531
532 ;;; Most of this logic may end up belonging in code/late-type.lisp;
533 ;;; however, here we also need the -OR-GIVE-UP for the transforms, and
534 ;;; maybe this is just too sloppy for actual type logic.  -- CSR,
535 ;;; 2004-02-18
536 (defun array-type-dimensions-or-give-up (type)
537   (typecase type
538     (array-type (array-type-dimensions type))
539     (union-type
540      (let ((types (union-type-types type)))
541        ;; there are at least two types, right?
542        (aver (> (length types) 1))
543        (let ((result (array-type-dimensions-or-give-up (car types))))
544          (dolist (type (cdr types) result)
545            (unless (equal (array-type-dimensions-or-give-up type) result)
546              (give-up-ir1-transform))))))
547     ;; FIXME: intersection type [e.g. (and (array * (*)) (satisfies foo)) ]
548     (t (give-up-ir1-transform))))
549
550 (defun conservative-array-type-complexp (type)
551   (typecase type
552     (array-type (array-type-complexp type))
553     (union-type
554      (let ((types (union-type-types type)))
555        (aver (> (length types) 1))
556        (let ((result (conservative-array-type-complexp (car types))))
557          (dolist (type (cdr types) result)
558            (unless (eq (conservative-array-type-complexp type) result)
559              (return-from conservative-array-type-complexp :maybe))))))
560     ;; FIXME: intersection type
561     (t :maybe)))
562
563 ;;; If we can tell the rank from the type info, use it instead.
564 (deftransform array-rank ((array))
565   (let ((array-type (lvar-type array)))
566     (let ((dims (array-type-dimensions-or-give-up array-type)))
567       (cond ((listp dims)
568              (length dims))
569             ((eq t (array-type-complexp array-type))
570              '(%array-rank array))
571             (t
572              `(if (array-header-p array)
573                   (%array-rank array)
574                   1))))))
575
576 ;;; If we know the dimensions at compile time, just use it. Otherwise,
577 ;;; if we can tell that the axis is in bounds, convert to
578 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
579 ;;; (if it's simple and a vector).
580 (deftransform array-dimension ((array axis)
581                                (array index))
582   (unless (constant-lvar-p axis)
583     (give-up-ir1-transform "The axis is not constant."))
584   ;; Dimensions may change thanks to ADJUST-ARRAY, so we need the
585   ;; conservative type.
586   (let ((array-type (lvar-conservative-type array))
587         (axis (lvar-value axis)))
588     (let ((dims (array-type-dimensions-or-give-up array-type)))
589       (unless (listp dims)
590         (give-up-ir1-transform
591          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
592       (unless (> (length dims) axis)
593         (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
594                              dims
595                              axis))
596       (let ((dim (nth axis dims)))
597         (cond ((integerp dim)
598                dim)
599               ((= (length dims) 1)
600                (ecase (conservative-array-type-complexp array-type)
601                  ((t)
602                   '(%array-dimension array 0))
603                  ((nil)
604                   '(vector-length array))
605                  ((:maybe)
606                   `(if (array-header-p array)
607                        (%array-dimension array axis)
608                        (vector-length array)))))
609               (t
610                '(%array-dimension array axis)))))))
611
612 ;;; If the length has been declared and it's simple, just return it.
613 (deftransform length ((vector)
614                       ((simple-array * (*))))
615   (let ((type (lvar-type vector)))
616     (let ((dims (array-type-dimensions-or-give-up type)))
617       (unless (and (listp dims) (integerp (car dims)))
618         (give-up-ir1-transform
619          "Vector length is unknown, must call LENGTH at runtime."))
620       (car dims))))
621
622 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
623 ;;; simple, it will extract the length slot from the vector. It it's
624 ;;; complex, it will extract the fill pointer slot from the array
625 ;;; header.
626 (deftransform length ((vector) (vector))
627   '(vector-length vector))
628
629 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
630 ;;; compile-time constant.
631 (deftransform vector-length ((vector))
632   (let ((vtype (lvar-type vector)))
633     (let ((dim (first (array-type-dimensions-or-give-up vtype))))
634       (when (eq dim '*)
635         (give-up-ir1-transform))
636       (when (conservative-array-type-complexp vtype)
637         (give-up-ir1-transform))
638       dim)))
639
640 ;;; Again, if we can tell the results from the type, just use it.
641 ;;; Otherwise, if we know the rank, convert into a computation based
642 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
643 ;;; multiplications because we know that the total size must be an
644 ;;; INDEX.
645 (deftransform array-total-size ((array)
646                                 (array))
647   (let ((array-type (lvar-type array)))
648     (let ((dims (array-type-dimensions-or-give-up array-type)))
649       (unless (listp dims)
650         (give-up-ir1-transform "can't tell the rank at compile time"))
651       (if (member '* dims)
652           (do ((form 1 `(truly-the index
653                                    (* (array-dimension array ,i) ,form)))
654                (i 0 (1+ i)))
655               ((= i (length dims)) form))
656           (reduce #'* dims)))))
657
658 ;;; Only complex vectors have fill pointers.
659 (deftransform array-has-fill-pointer-p ((array))
660   (let ((array-type (lvar-type array)))
661     (let ((dims (array-type-dimensions-or-give-up array-type)))
662       (if (and (listp dims) (not (= (length dims) 1)))
663           nil
664           (ecase (conservative-array-type-complexp array-type)
665             ((t)
666              t)
667             ((nil)
668              nil)
669             ((:maybe)
670              (give-up-ir1-transform
671               "The array type is ambiguous; must call ~
672                ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
673
674 ;;; Primitive used to verify indices into arrays. If we can tell at
675 ;;; compile-time or we are generating unsafe code, don't bother with
676 ;;; the VOP.
677 (deftransform %check-bound ((array dimension index) * * :node node)
678   (cond ((policy node (= insert-array-bounds-checks 0))
679          'index)
680         ((not (constant-lvar-p dimension))
681          (give-up-ir1-transform))
682         (t
683          (let ((dim (lvar-value dimension)))
684            ;; FIXME: Can SPEED > SAFETY weaken this check to INTEGER?
685            `(the (integer 0 (,dim)) index)))))
686 \f
687 ;;;; WITH-ARRAY-DATA
688
689 ;;; This checks to see whether the array is simple and the start and
690 ;;; end are in bounds. If so, it proceeds with those values.
691 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
692 ;;; may be further optimized.
693 ;;;
694 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
695 ;;; START-VAR and END-VAR to the start and end of the designated
696 ;;; portion of the data vector. SVALUE and EVALUE are any start and
697 ;;; end specified to the original operation, and are factored into the
698 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
699 ;;; offset of all displacements encountered, and does not include
700 ;;; SVALUE.
701 ;;;
702 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
703 ;;; forced to be inline, overriding the ordinary judgment of the
704 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
705 ;;; fairly picky about their arguments, figuring that if you haven't
706 ;;; bothered to get all your ducks in a row, you probably don't care
707 ;;; that much about speed anyway! But in some cases it makes sense to
708 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
709 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
710 ;;; sense to use FORCE-INLINE option in that case.
711 (def!macro with-array-data (((data-var array &key offset-var)
712                              (start-var &optional (svalue 0))
713                              (end-var &optional (evalue nil))
714                              &key force-inline check-fill-pointer)
715                             &body forms
716                             &environment env)
717   (once-only ((n-array array)
718               (n-svalue `(the index ,svalue))
719               (n-evalue `(the (or index null) ,evalue)))
720     (let ((check-bounds (policy env (plusp insert-array-bounds-checks))))
721       `(multiple-value-bind (,data-var
722                              ,start-var
723                              ,end-var
724                              ,@(when offset-var `(,offset-var)))
725            (if (not (array-header-p ,n-array))
726                (let ((,n-array ,n-array))
727                  (declare (type (simple-array * (*)) ,n-array))
728                  ,(once-only ((n-len (if check-fill-pointer
729                                          `(length ,n-array)
730                                          `(array-total-size ,n-array)))
731                               (n-end `(or ,n-evalue ,n-len)))
732                              (if check-bounds
733                                  `(if (<= 0 ,n-svalue ,n-end ,n-len)
734                                       (values ,n-array ,n-svalue ,n-end 0)
735                                       ,(if check-fill-pointer
736                                            `(sequence-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)
737                                            `(array-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)))
738                                  `(values ,n-array ,n-svalue ,n-end 0))))
739                ,(if force-inline
740                     `(%with-array-data-macro ,n-array ,n-svalue ,n-evalue
741                                              :check-bounds ,check-bounds
742                                              :check-fill-pointer ,check-fill-pointer)
743                     (if check-fill-pointer
744                         `(%with-array-data/fp ,n-array ,n-svalue ,n-evalue)
745                         `(%with-array-data ,n-array ,n-svalue ,n-evalue))))
746          ,@forms))))
747
748 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
749 ;;; DEFTRANSFORMs and DEFUNs.
750 (def!macro %with-array-data-macro (array
751                                    start
752                                    end
753                                    &key
754                                    (element-type '*)
755                                    check-bounds
756                                    check-fill-pointer)
757   (with-unique-names (size defaulted-end data cumulative-offset)
758     `(let* ((,size ,(if check-fill-pointer
759                         `(length ,array)
760                         `(array-total-size ,array)))
761             (,defaulted-end (or ,end ,size)))
762        ,@(when check-bounds
763                `((unless (<= ,start ,defaulted-end ,size)
764                    ,(if check-fill-pointer
765                         `(sequence-bounding-indices-bad-error ,array ,start ,end)
766                         `(array-bounding-indices-bad-error ,array ,start ,end)))))
767        (do ((,data ,array (%array-data-vector ,data))
768             (,cumulative-offset 0
769                                 (+ ,cumulative-offset
770                                    (%array-displacement ,data))))
771            ((not (array-header-p ,data))
772             (values (the (simple-array ,element-type 1) ,data)
773                     (the index (+ ,cumulative-offset ,start))
774                     (the index (+ ,cumulative-offset ,defaulted-end))
775                     (the index ,cumulative-offset)))
776          (declare (type index ,cumulative-offset))))))
777
778 (defun transform-%with-array-data/muble (array node check-fill-pointer)
779   (let ((element-type (upgraded-element-type-specifier-or-give-up array))
780         (type (lvar-type array))
781         (check-bounds (policy node (plusp insert-array-bounds-checks))))
782     (if (and (array-type-p type)
783              (not (array-type-complexp type))
784              (listp (array-type-dimensions type))
785              (not (null (cdr (array-type-dimensions type)))))
786         ;; If it's a simple multidimensional array, then just return
787         ;; its data vector directly rather than going through
788         ;; %WITH-ARRAY-DATA-MACRO. SBCL doesn't generally generate
789         ;; code that would use this currently, but we have encouraged
790         ;; users to use WITH-ARRAY-DATA and we may use it ourselves at
791         ;; some point in the future for optimized libraries or
792         ;; similar.
793         (if check-bounds
794             `(let* ((data (truly-the (simple-array ,element-type (*))
795                                      (%array-data-vector array)))
796                     (len (length data))
797                     (real-end (or end len)))
798                (unless (<= 0 start data-end lend)
799                  (sequence-bounding-indices-bad-error array start end))
800                (values data 0 real-end 0))
801             `(let ((data (truly-the (simple-array ,element-type (*))
802                                     (%array-data-vector array))))
803                (values data 0 (or end (length data)) 0)))
804         `(%with-array-data-macro array start end
805                                  :check-fill-pointer ,check-fill-pointer
806                                  :check-bounds ,check-bounds
807                                  :element-type ,element-type))))
808
809 ;; It might very well be reasonable to allow general ARRAY here, I
810 ;; just haven't tried to understand the performance issues involved.
811 ;; -- WHN, and also CSR 2002-05-26
812 (deftransform %with-array-data ((array start end)
813                                 ((or vector simple-array) index (or index null) t)
814                                 *
815                                 :node node
816                                 :policy (> speed space))
817   "inline non-SIMPLE-vector-handling logic"
818   (transform-%with-array-data/muble array node nil))
819 (deftransform %with-array-data/fp ((array start end)
820                                 ((or vector simple-array) index (or index null) t)
821                                 *
822                                 :node node
823                                 :policy (> speed space))
824   "inline non-SIMPLE-vector-handling logic"
825   (transform-%with-array-data/muble array node t))
826 \f
827 ;;;; array accessors
828
829 ;;; We convert all typed array accessors into AREF and %ASET with type
830 ;;; assertions on the array.
831 (macrolet ((define-bit-frob (reffer setter simplep)
832              `(progn
833                 (define-source-transform ,reffer (a &rest i)
834                   `(aref (the (,',(if simplep 'simple-array 'array)
835                                   bit
836                                   ,(mapcar (constantly '*) i))
837                            ,a) ,@i))
838                 (define-source-transform ,setter (a &rest i)
839                   `(%aset (the (,',(if simplep 'simple-array 'array)
840                                    bit
841                                    ,(cdr (mapcar (constantly '*) i)))
842                             ,a) ,@i)))))
843   (define-bit-frob sbit %sbitset t)
844   (define-bit-frob bit %bitset nil))
845 (macrolet ((define-frob (reffer setter type)
846              `(progn
847                 (define-source-transform ,reffer (a i)
848                   `(aref (the ,',type ,a) ,i))
849                 (define-source-transform ,setter (a i v)
850                   `(%aset (the ,',type ,a) ,i ,v)))))
851   (define-frob svref %svset simple-vector)
852   (define-frob schar %scharset simple-string)
853   (define-frob char %charset string))
854
855 (macrolet (;; This is a handy macro for computing the row-major index
856            ;; given a set of indices. We wrap each index with a call
857            ;; to %CHECK-BOUND to ensure that everything works out
858            ;; correctly. We can wrap all the interior arithmetic with
859            ;; TRULY-THE INDEX because we know the resultant
860            ;; row-major index must be an index.
861            (with-row-major-index ((array indices index &optional new-value)
862                                   &rest body)
863              `(let (n-indices dims)
864                 (dotimes (i (length ,indices))
865                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
866                   (push (make-symbol (format nil "DIM-~D" i)) dims))
867                 (setf n-indices (nreverse n-indices))
868                 (setf dims (nreverse dims))
869                 `(lambda (,',array ,@n-indices
870                                    ,@',(when new-value (list new-value)))
871                    (let* (,@(let ((,index -1))
872                               (mapcar (lambda (name)
873                                         `(,name (array-dimension
874                                                  ,',array
875                                                  ,(incf ,index))))
876                                       dims))
877                             (,',index
878                              ,(if (null dims)
879                                   0
880                                 (do* ((dims dims (cdr dims))
881                                       (indices n-indices (cdr indices))
882                                       (last-dim nil (car dims))
883                                       (form `(%check-bound ,',array
884                                                            ,(car dims)
885                                                            ,(car indices))
886                                             `(truly-the
887                                               index
888                                               (+ (truly-the index
889                                                             (* ,form
890                                                                ,last-dim))
891                                                  (%check-bound
892                                                   ,',array
893                                                   ,(car dims)
894                                                   ,(car indices))))))
895                                     ((null (cdr dims)) form)))))
896                      ,',@body)))))
897
898   ;; Just return the index after computing it.
899   (deftransform array-row-major-index ((array &rest indices))
900     (with-row-major-index (array indices index)
901       index))
902
903   ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
904   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
905   ;; expression for the row major index.
906   (deftransform aref ((array &rest indices))
907     (with-row-major-index (array indices index)
908       (hairy-data-vector-ref array index)))
909
910   (deftransform %aset ((array &rest stuff))
911     (let ((indices (butlast stuff)))
912       (with-row-major-index (array indices index new-value)
913         (hairy-data-vector-set array index new-value)))))
914
915 ;; For AREF of vectors we do the bounds checking in the callee. This
916 ;; lets us do a significantly more efficient check for simple-arrays
917 ;; without bloating the code. If we already know the type of the array
918 ;; with sufficient precision, skip directly to DATA-VECTOR-REF.
919 (deftransform aref ((array index) (t t) * :node node)
920   (let* ((type (lvar-type array))
921          (element-ctype (extract-upgraded-element-type array)))
922     (cond
923       ((and (array-type-p type)
924             (null (array-type-complexp type))
925             (not (eql element-ctype *wild-type*))
926             (eql (length (array-type-dimensions type)) 1))
927        (let* ((declared-element-ctype (extract-declared-element-type array))
928               (bare-form
929                `(data-vector-ref array
930                  (%check-bound array (array-dimension array 0) index))))
931          (if (type= declared-element-ctype element-ctype)
932              bare-form
933              `(the ,(type-specifier declared-element-ctype) ,bare-form))))
934       ((policy node (zerop insert-array-bounds-checks))
935        `(hairy-data-vector-ref array index))
936       (t `(hairy-data-vector-ref/check-bounds array index)))))
937
938 (deftransform %aset ((array index new-value) (t t t) * :node node)
939   (if (policy node (zerop insert-array-bounds-checks))
940       `(hairy-data-vector-set array index new-value)
941       `(hairy-data-vector-set/check-bounds array index new-value)))
942
943 ;;; But if we find out later that there's some useful type information
944 ;;; available, switch back to the normal one to give other transforms
945 ;;; a stab at it.
946 (macrolet ((define (name transform-to extra extra-type)
947              (declare (ignore extra-type))
948              `(deftransform ,name ((array index ,@extra))
949                 (let ((type (lvar-type array))
950                       (element-type (extract-upgraded-element-type array))
951                       (declared-type (extract-declared-element-type array)))
952                   ;; If an element type has been declared, we want to
953                   ;; use that information it for type checking (even
954                   ;; if the access can't be optimized due to the array
955                   ;; not being simple).
956                   (when (and (eql element-type *wild-type*)
957                              ;; This type logic corresponds to the special
958                              ;; case for strings in HAIRY-DATA-VECTOR-REF
959                              ;; (generic/vm-tran.lisp)
960                              (not (csubtypep type (specifier-type 'simple-string))))
961                     (when (or (not (array-type-p type))
962                               ;; If it's a simple array, we might be able
963                               ;; to inline the access completely.
964                               (not (null (array-type-complexp type))))
965                       (give-up-ir1-transform
966                        "Upgraded element type of array is not known at compile time.")))
967                   ,(if extra
968                        ``(truly-the ,declared-type
969                                     (,',transform-to array
970                                                      (%check-bound array
971                                                                    (array-dimension array 0)
972                                                                    index)
973                                                      (the ,declared-type ,@',extra)))
974                        ``(the ,declared-type
975                            (,',transform-to array
976                                             (%check-bound array
977                                                           (array-dimension array 0)
978                                                           index))))))))
979   (define hairy-data-vector-ref/check-bounds
980       hairy-data-vector-ref nil nil)
981   (define hairy-data-vector-set/check-bounds
982       hairy-data-vector-set (new-value) (*)))
983
984 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
985 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
986 ;;; array total size.
987 (deftransform row-major-aref ((array index))
988   `(hairy-data-vector-ref array
989                           (%check-bound array (array-total-size array) index)))
990 (deftransform %set-row-major-aref ((array index new-value))
991   `(hairy-data-vector-set array
992                           (%check-bound array (array-total-size array) index)
993                           new-value))
994 \f
995 ;;;; bit-vector array operation canonicalization
996 ;;;;
997 ;;;; We convert all bit-vector operations to have the result array
998 ;;;; specified. This allows any result allocation to be open-coded,
999 ;;;; and eliminates the need for any VM-dependent transforms to handle
1000 ;;;; these cases.
1001
1002 (macrolet ((def (fun)
1003              `(progn
1004                (deftransform ,fun ((bit-array-1 bit-array-2
1005                                                 &optional result-bit-array)
1006                                    (bit-vector bit-vector &optional null) *
1007                                    :policy (>= speed space))
1008                  `(,',fun bit-array-1 bit-array-2
1009                    (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1010                ;; If result is T, make it the first arg.
1011                (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
1012                                    (bit-vector bit-vector (eql t)) *)
1013                  `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
1014   (def bit-and)
1015   (def bit-ior)
1016   (def bit-xor)
1017   (def bit-eqv)
1018   (def bit-nand)
1019   (def bit-nor)
1020   (def bit-andc1)
1021   (def bit-andc2)
1022   (def bit-orc1)
1023   (def bit-orc2))
1024
1025 ;;; Similar for BIT-NOT, but there is only one arg...
1026 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
1027                        (bit-vector &optional null) *
1028                        :policy (>= speed space))
1029   '(bit-not bit-array-1
1030             (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1031 (deftransform bit-not ((bit-array-1 result-bit-array)
1032                        (bit-vector (eql t)))
1033   '(bit-not bit-array-1 bit-array-1))
1034 \f
1035 ;;; Pick off some constant cases.
1036 (defoptimizer (array-header-p derive-type) ((array))
1037   (let ((type (lvar-type array)))
1038     (cond ((not (array-type-p type))
1039            ;; FIXME: use analogue of ARRAY-TYPE-DIMENSIONS-OR-GIVE-UP
1040            nil)
1041           (t
1042            (let ((dims (array-type-dimensions type)))
1043              (cond ((csubtypep type (specifier-type '(simple-array * (*))))
1044                     ;; no array header
1045                     (specifier-type 'null))
1046                    ((and (listp dims) (/= (length dims) 1))
1047                     ;; multi-dimensional array, will have a header
1048                     (specifier-type '(eql t)))
1049                    ((eql (array-type-complexp type) t)
1050                     (specifier-type '(eql t)))
1051                    (t
1052                     nil)))))))