1.0.28.55: transform FILL to a UB*-BASH-FILL when possible
[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                  (init (if (constant-lvar-p initial-element)
348                            (lvar-value initial-element)
349                            'initial-element)))
350              `(lambda (length ,@parameters)
351                 (declare (ignorable ,@parameters))
352                 (truly-the ,result-spec
353                            (fill ,alloc-form (the ,elt-spec ,init))))))
354           ;; just :ELEMENT-TYPE, or maybe with :INITIAL-ELEMENT EQL to the
355           ;; default
356           (t
357            #-sb-xc-host
358            (unless (ctypep default-initial-element elt-ctype)
359              ;; This situation arises e.g. in (MAKE-ARRAY 4 :ELEMENT-TYPE
360              ;; '(INTEGER 1 5)) ANSI's definition of MAKE-ARRAY says "If
361              ;; INITIAL-ELEMENT is not supplied, the consequences of later
362              ;; reading an uninitialized element of new-array are undefined,"
363              ;; so this could be legal code as long as the user plans to
364              ;; write before he reads, and if he doesn't we're free to do
365              ;; anything we like. But in case the user doesn't know to write
366              ;; elements before he reads elements (or to read manuals before
367              ;; he writes code:-), we'll signal a STYLE-WARNING in case he
368              ;; didn't realize this.
369              (if initial-element
370                  (compiler-warn "~S ~S is not a ~S"
371                                 :initial-element default-initial-element
372                                 elt-spec)
373                  (compiler-style-warn "The default initial element ~S is not a ~S."
374                                       default-initial-element
375                                       elt-spec)))
376            (let ((parameters (eliminate-keyword-args
377                               call 1 '((:element-type element-type)))))
378              `(lambda (length ,@parameters)
379                 (declare (ignorable ,@parameters))
380                 ,alloc-form))))))
381
382 (deftransform make-array ((dims &key
383                                 element-type initial-element initial-contents)
384                           (integer &key
385                                    (:element-type (constant-arg *))
386                                    (:initial-element *)
387                                    (:initial-contents *))
388                           *
389                           :node call)
390   (transform-make-array-vector dims
391                                element-type
392                                initial-element
393                                initial-contents
394                                call))
395
396 ;;; The list type restriction does not ensure that the result will be a
397 ;;; multi-dimensional array. But the lack of adjustable, fill-pointer,
398 ;;; and displaced-to keywords ensures that it will be simple.
399 ;;;
400 ;;; FIXME: should we generalize this transform to non-simple (though
401 ;;; non-displaced-to) arrays, given that we have %WITH-ARRAY-DATA to
402 ;;; deal with those? Maybe when the DEFTRANSFORM
403 ;;; %DATA-VECTOR-AND-INDEX in the VECTOR case problem is solved? --
404 ;;; CSR, 2002-07-01
405 (deftransform make-array ((dims &key
406                                 element-type initial-element initial-contents)
407                           (list &key
408                                 (:element-type (constant-arg *))
409                                 (:initial-element *)
410                                 (:initial-contents *))
411                           *
412                           :node call)
413   (block make-array
414     (when (lvar-matches dims :fun-names '(list) :arg-count 1)
415       (let ((length (car (splice-fun-args dims :any 1))))
416         (return-from make-array
417           (transform-make-array-vector length
418                                        element-type
419                                        initial-element
420                                        initial-contents
421                                        call))))
422     (unless (constant-lvar-p dims)
423       (give-up-ir1-transform
424        "The dimension list is not constant; cannot open code array creation."))
425     (let ((dims (lvar-value dims)))
426       (unless (every #'integerp dims)
427         (give-up-ir1-transform
428          "The dimension list contains something other than an integer: ~S"
429          dims))
430       (if (= (length dims) 1)
431           `(make-array ',(car dims)
432                        ,@(when element-type
433                                '(:element-type element-type))
434                        ,@(when initial-element
435                                '(:initial-element initial-element))
436                        ,@(when initial-contents
437                                '(:initial-contents initial-contents)))
438           (let* ((total-size (reduce #'* dims))
439                  (rank (length dims))
440                  (spec `(simple-array
441                          ,(cond ((null element-type) t)
442                                 ((and (constant-lvar-p element-type)
443                                       (ir1-transform-specifier-type
444                                        (lvar-value element-type)))
445                                  (sb!xc:upgraded-array-element-type
446                                   (lvar-value element-type)))
447                                 (t '*))
448                          ,(make-list rank :initial-element '*))))
449             `(let ((header (make-array-header sb!vm:simple-array-widetag ,rank))
450                    (data (make-array ,total-size
451                                      ,@(when element-type
452                                              '(:element-type element-type))
453                                      ,@(when initial-element
454                                              '(:initial-element initial-element)))))
455                ,@(when initial-contents
456                        ;; FIXME: This is could be open coded at least a bit too
457                        `((sb!impl::fill-data-vector data ',dims initial-contents)))
458                (setf (%array-fill-pointer header) ,total-size)
459                (setf (%array-fill-pointer-p header) nil)
460                (setf (%array-available-elements header) ,total-size)
461                (setf (%array-data-vector header) data)
462                (setf (%array-displaced-p header) nil)
463                (setf (%array-displaced-from header) nil)
464                ,@(let ((axis -1))
465                       (mapcar (lambda (dim)
466                                 `(setf (%array-dimension header ,(incf axis))
467                                        ,dim))
468                               dims))
469                (truly-the ,spec header)))))))
470
471 (deftransform make-array ((dims &key initial-element element-type
472                                      adjustable fill-pointer)
473                           (t &rest *))
474   (when (null initial-element)
475     (give-up-ir1-transform))
476   (let* ((eltype (cond ((not element-type) t)
477                        ((not (constant-lvar-p element-type))
478                         (give-up-ir1-transform
479                          "ELEMENT-TYPE is not constant."))
480                        (t
481                         (lvar-value element-type))))
482          (eltype-type (ir1-transform-specifier-type eltype))
483          (saetp (find-if (lambda (saetp)
484                            (csubtypep eltype-type (sb!vm:saetp-ctype saetp)))
485                          sb!vm:*specialized-array-element-type-properties*))
486          (creation-form `(make-array dims
487                           :element-type ',(type-specifier (sb!vm:saetp-ctype saetp))
488                           ,@(when fill-pointer
489                                   '(:fill-pointer fill-pointer))
490                           ,@(when adjustable
491                                   '(:adjustable adjustable)))))
492
493     (unless saetp
494       (give-up-ir1-transform "ELEMENT-TYPE not found in *SAETP*: ~S" eltype))
495
496     (cond ((and (constant-lvar-p initial-element)
497                 (eql (lvar-value initial-element)
498                      (sb!vm:saetp-initial-element-default saetp)))
499            creation-form)
500           (t
501            ;; error checking for target, disabled on the host because
502            ;; (CTYPE-OF #\Null) is not possible.
503            #-sb-xc-host
504            (when (constant-lvar-p initial-element)
505              (let ((value (lvar-value initial-element)))
506                (cond
507                  ((not (ctypep value (sb!vm:saetp-ctype saetp)))
508                   ;; this case will cause an error at runtime, so we'd
509                   ;; better WARN about it now.
510                   (warn 'array-initial-element-mismatch
511                         :format-control "~@<~S is not a ~S (which is the ~
512                                          ~S of ~S).~@:>"
513                         :format-arguments
514                         (list
515                          value
516                          (type-specifier (sb!vm:saetp-ctype saetp))
517                          'upgraded-array-element-type
518                          eltype)))
519                  ((not (ctypep value eltype-type))
520                   ;; this case will not cause an error at runtime, but
521                   ;; it's still worth STYLE-WARNing about.
522                   (compiler-style-warn "~S is not a ~S."
523                                        value eltype)))))
524            `(let ((array ,creation-form))
525              (multiple-value-bind (vector)
526                  (%data-vector-and-index array 0)
527                (fill vector (the ,(sb!vm:saetp-specifier saetp) initial-element)))
528              array)))))
529 \f
530 ;;;; miscellaneous properties of arrays
531
532 ;;; Transforms for various array properties. If the property is know
533 ;;; at compile time because of a type spec, use that constant value.
534
535 ;;; Most of this logic may end up belonging in code/late-type.lisp;
536 ;;; however, here we also need the -OR-GIVE-UP for the transforms, and
537 ;;; maybe this is just too sloppy for actual type logic.  -- CSR,
538 ;;; 2004-02-18
539 (defun array-type-dimensions-or-give-up (type)
540   (typecase type
541     (array-type (array-type-dimensions type))
542     (union-type
543      (let ((types (union-type-types type)))
544        ;; there are at least two types, right?
545        (aver (> (length types) 1))
546        (let ((result (array-type-dimensions-or-give-up (car types))))
547          (dolist (type (cdr types) result)
548            (unless (equal (array-type-dimensions-or-give-up type) result)
549              (give-up-ir1-transform))))))
550     ;; FIXME: intersection type [e.g. (and (array * (*)) (satisfies foo)) ]
551     (t (give-up-ir1-transform))))
552
553 (defun conservative-array-type-complexp (type)
554   (typecase type
555     (array-type (array-type-complexp type))
556     (union-type
557      (let ((types (union-type-types type)))
558        (aver (> (length types) 1))
559        (let ((result (conservative-array-type-complexp (car types))))
560          (dolist (type (cdr types) result)
561            (unless (eq (conservative-array-type-complexp type) result)
562              (return-from conservative-array-type-complexp :maybe))))))
563     ;; FIXME: intersection type
564     (t :maybe)))
565
566 ;;; If we can tell the rank from the type info, use it instead.
567 (deftransform array-rank ((array))
568   (let ((array-type (lvar-type array)))
569     (let ((dims (array-type-dimensions-or-give-up array-type)))
570       (cond ((listp dims)
571              (length dims))
572             ((eq t (array-type-complexp array-type))
573              '(%array-rank array))
574             (t
575              `(if (array-header-p array)
576                   (%array-rank array)
577                   1))))))
578
579 ;;; If we know the dimensions at compile time, just use it. Otherwise,
580 ;;; if we can tell that the axis is in bounds, convert to
581 ;;; %ARRAY-DIMENSION (which just indirects the array header) or length
582 ;;; (if it's simple and a vector).
583 (deftransform array-dimension ((array axis)
584                                (array index))
585   (unless (constant-lvar-p axis)
586     (give-up-ir1-transform "The axis is not constant."))
587   ;; Dimensions may change thanks to ADJUST-ARRAY, so we need the
588   ;; conservative type.
589   (let ((array-type (lvar-conservative-type array))
590         (axis (lvar-value axis)))
591     (let ((dims (array-type-dimensions-or-give-up array-type)))
592       (unless (listp dims)
593         (give-up-ir1-transform
594          "The array dimensions are unknown; must call ARRAY-DIMENSION at runtime."))
595       (unless (> (length dims) axis)
596         (abort-ir1-transform "The array has dimensions ~S, ~W is too large."
597                              dims
598                              axis))
599       (let ((dim (nth axis dims)))
600         (cond ((integerp dim)
601                dim)
602               ((= (length dims) 1)
603                (ecase (conservative-array-type-complexp array-type)
604                  ((t)
605                   '(%array-dimension array 0))
606                  ((nil)
607                   '(vector-length array))
608                  ((:maybe)
609                   `(if (array-header-p array)
610                        (%array-dimension array axis)
611                        (vector-length array)))))
612               (t
613                '(%array-dimension array axis)))))))
614
615 ;;; If the length has been declared and it's simple, just return it.
616 (deftransform length ((vector)
617                       ((simple-array * (*))))
618   (let ((type (lvar-type vector)))
619     (let ((dims (array-type-dimensions-or-give-up type)))
620       (unless (and (listp dims) (integerp (car dims)))
621         (give-up-ir1-transform
622          "Vector length is unknown, must call LENGTH at runtime."))
623       (car dims))))
624
625 ;;; All vectors can get their length by using VECTOR-LENGTH. If it's
626 ;;; simple, it will extract the length slot from the vector. It it's
627 ;;; complex, it will extract the fill pointer slot from the array
628 ;;; header.
629 (deftransform length ((vector) (vector))
630   '(vector-length vector))
631
632 ;;; If a simple array with known dimensions, then VECTOR-LENGTH is a
633 ;;; compile-time constant.
634 (deftransform vector-length ((vector))
635   (let ((vtype (lvar-type vector)))
636     (let ((dim (first (array-type-dimensions-or-give-up vtype))))
637       (when (eq dim '*)
638         (give-up-ir1-transform))
639       (when (conservative-array-type-complexp vtype)
640         (give-up-ir1-transform))
641       dim)))
642
643 ;;; Again, if we can tell the results from the type, just use it.
644 ;;; Otherwise, if we know the rank, convert into a computation based
645 ;;; on array-dimension. We can wrap a TRULY-THE INDEX around the
646 ;;; multiplications because we know that the total size must be an
647 ;;; INDEX.
648 (deftransform array-total-size ((array)
649                                 (array))
650   (let ((array-type (lvar-type array)))
651     (let ((dims (array-type-dimensions-or-give-up array-type)))
652       (unless (listp dims)
653         (give-up-ir1-transform "can't tell the rank at compile time"))
654       (if (member '* dims)
655           (do ((form 1 `(truly-the index
656                                    (* (array-dimension array ,i) ,form)))
657                (i 0 (1+ i)))
658               ((= i (length dims)) form))
659           (reduce #'* dims)))))
660
661 ;;; Only complex vectors have fill pointers.
662 (deftransform array-has-fill-pointer-p ((array))
663   (let ((array-type (lvar-type array)))
664     (let ((dims (array-type-dimensions-or-give-up array-type)))
665       (if (and (listp dims) (not (= (length dims) 1)))
666           nil
667           (ecase (conservative-array-type-complexp array-type)
668             ((t)
669              t)
670             ((nil)
671              nil)
672             ((:maybe)
673              (give-up-ir1-transform
674               "The array type is ambiguous; must call ~
675                ARRAY-HAS-FILL-POINTER-P at runtime.")))))))
676
677 ;;; Primitive used to verify indices into arrays. If we can tell at
678 ;;; compile-time or we are generating unsafe code, don't bother with
679 ;;; the VOP.
680 (deftransform %check-bound ((array dimension index) * * :node node)
681   (cond ((policy node (= insert-array-bounds-checks 0))
682          'index)
683         ((not (constant-lvar-p dimension))
684          (give-up-ir1-transform))
685         (t
686          (let ((dim (lvar-value dimension)))
687            ;; FIXME: Can SPEED > SAFETY weaken this check to INTEGER?
688            `(the (integer 0 (,dim)) index)))))
689 \f
690 ;;;; WITH-ARRAY-DATA
691
692 ;;; This checks to see whether the array is simple and the start and
693 ;;; end are in bounds. If so, it proceeds with those values.
694 ;;; Otherwise, it calls %WITH-ARRAY-DATA. Note that %WITH-ARRAY-DATA
695 ;;; may be further optimized.
696 ;;;
697 ;;; Given any ARRAY, bind DATA-VAR to the array's data vector and
698 ;;; START-VAR and END-VAR to the start and end of the designated
699 ;;; portion of the data vector. SVALUE and EVALUE are any start and
700 ;;; end specified to the original operation, and are factored into the
701 ;;; bindings of START-VAR and END-VAR. OFFSET-VAR is the cumulative
702 ;;; offset of all displacements encountered, and does not include
703 ;;; SVALUE.
704 ;;;
705 ;;; When FORCE-INLINE is set, the underlying %WITH-ARRAY-DATA form is
706 ;;; forced to be inline, overriding the ordinary judgment of the
707 ;;; %WITH-ARRAY-DATA DEFTRANSFORMs. Ordinarily the DEFTRANSFORMs are
708 ;;; fairly picky about their arguments, figuring that if you haven't
709 ;;; bothered to get all your ducks in a row, you probably don't care
710 ;;; that much about speed anyway! But in some cases it makes sense to
711 ;;; do type testing inside %WITH-ARRAY-DATA instead of outside, and
712 ;;; the DEFTRANSFORM can't tell that that's going on, so it can make
713 ;;; sense to use FORCE-INLINE option in that case.
714 (def!macro with-array-data (((data-var array &key offset-var)
715                              (start-var &optional (svalue 0))
716                              (end-var &optional (evalue nil))
717                              &key force-inline check-fill-pointer)
718                             &body forms
719                             &environment env)
720   (once-only ((n-array array)
721               (n-svalue `(the index ,svalue))
722               (n-evalue `(the (or index null) ,evalue)))
723     (let ((check-bounds (policy env (plusp insert-array-bounds-checks))))
724       `(multiple-value-bind (,data-var
725                              ,start-var
726                              ,end-var
727                              ,@(when offset-var `(,offset-var)))
728            (if (not (array-header-p ,n-array))
729                (let ((,n-array ,n-array))
730                  (declare (type (simple-array * (*)) ,n-array))
731                  ,(once-only ((n-len (if check-fill-pointer
732                                          `(length ,n-array)
733                                          `(array-total-size ,n-array)))
734                               (n-end `(or ,n-evalue ,n-len)))
735                              (if check-bounds
736                                  `(if (<= 0 ,n-svalue ,n-end ,n-len)
737                                       (values ,n-array ,n-svalue ,n-end 0)
738                                       ,(if check-fill-pointer
739                                            `(sequence-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)
740                                            `(array-bounding-indices-bad-error ,n-array ,n-svalue ,n-evalue)))
741                                  `(values ,n-array ,n-svalue ,n-end 0))))
742                ,(if force-inline
743                     `(%with-array-data-macro ,n-array ,n-svalue ,n-evalue
744                                              :check-bounds ,check-bounds
745                                              :check-fill-pointer ,check-fill-pointer)
746                     (if check-fill-pointer
747                         `(%with-array-data/fp ,n-array ,n-svalue ,n-evalue)
748                         `(%with-array-data ,n-array ,n-svalue ,n-evalue))))
749          ,@forms))))
750
751 ;;; This is the fundamental definition of %WITH-ARRAY-DATA, for use in
752 ;;; DEFTRANSFORMs and DEFUNs.
753 (def!macro %with-array-data-macro (array
754                                    start
755                                    end
756                                    &key
757                                    (element-type '*)
758                                    check-bounds
759                                    check-fill-pointer)
760   (with-unique-names (size defaulted-end data cumulative-offset)
761     `(let* ((,size ,(if check-fill-pointer
762                         `(length ,array)
763                         `(array-total-size ,array)))
764             (,defaulted-end (or ,end ,size)))
765        ,@(when check-bounds
766                `((unless (<= ,start ,defaulted-end ,size)
767                    ,(if check-fill-pointer
768                         `(sequence-bounding-indices-bad-error ,array ,start ,end)
769                         `(array-bounding-indices-bad-error ,array ,start ,end)))))
770        (do ((,data ,array (%array-data-vector ,data))
771             (,cumulative-offset 0
772                                 (+ ,cumulative-offset
773                                    (%array-displacement ,data))))
774            ((not (array-header-p ,data))
775             (values (the (simple-array ,element-type 1) ,data)
776                     (the index (+ ,cumulative-offset ,start))
777                     (the index (+ ,cumulative-offset ,defaulted-end))
778                     (the index ,cumulative-offset)))
779          (declare (type index ,cumulative-offset))))))
780
781 (defun transform-%with-array-data/muble (array node check-fill-pointer)
782   (let ((element-type (upgraded-element-type-specifier-or-give-up array))
783         (type (lvar-type array))
784         (check-bounds (policy node (plusp insert-array-bounds-checks))))
785     (if (and (array-type-p type)
786              (not (array-type-complexp type))
787              (listp (array-type-dimensions type))
788              (not (null (cdr (array-type-dimensions type)))))
789         ;; If it's a simple multidimensional array, then just return
790         ;; its data vector directly rather than going through
791         ;; %WITH-ARRAY-DATA-MACRO. SBCL doesn't generally generate
792         ;; code that would use this currently, but we have encouraged
793         ;; users to use WITH-ARRAY-DATA and we may use it ourselves at
794         ;; some point in the future for optimized libraries or
795         ;; similar.
796         (if check-bounds
797             `(let* ((data (truly-the (simple-array ,element-type (*))
798                                      (%array-data-vector array)))
799                     (len (length data))
800                     (real-end (or end len)))
801                (unless (<= 0 start data-end lend)
802                  (sequence-bounding-indices-bad-error array start end))
803                (values data 0 real-end 0))
804             `(let ((data (truly-the (simple-array ,element-type (*))
805                                     (%array-data-vector array))))
806                (values data 0 (or end (length data)) 0)))
807         `(%with-array-data-macro array start end
808                                  :check-fill-pointer ,check-fill-pointer
809                                  :check-bounds ,check-bounds
810                                  :element-type ,element-type))))
811
812 ;; It might very well be reasonable to allow general ARRAY here, I
813 ;; just haven't tried to understand the performance issues involved.
814 ;; -- WHN, and also CSR 2002-05-26
815 (deftransform %with-array-data ((array start end)
816                                 ((or vector simple-array) index (or index null) t)
817                                 *
818                                 :node node
819                                 :policy (> speed space))
820   "inline non-SIMPLE-vector-handling logic"
821   (transform-%with-array-data/muble array node nil))
822 (deftransform %with-array-data/fp ((array start end)
823                                 ((or vector simple-array) index (or index null) t)
824                                 *
825                                 :node node
826                                 :policy (> speed space))
827   "inline non-SIMPLE-vector-handling logic"
828   (transform-%with-array-data/muble array node t))
829 \f
830 ;;;; array accessors
831
832 ;;; We convert all typed array accessors into AREF and %ASET with type
833 ;;; assertions on the array.
834 (macrolet ((define-bit-frob (reffer setter simplep)
835              `(progn
836                 (define-source-transform ,reffer (a &rest i)
837                   `(aref (the (,',(if simplep 'simple-array 'array)
838                                   bit
839                                   ,(mapcar (constantly '*) i))
840                            ,a) ,@i))
841                 (define-source-transform ,setter (a &rest i)
842                   `(%aset (the (,',(if simplep 'simple-array 'array)
843                                    bit
844                                    ,(cdr (mapcar (constantly '*) i)))
845                             ,a) ,@i)))))
846   (define-bit-frob sbit %sbitset t)
847   (define-bit-frob bit %bitset nil))
848 (macrolet ((define-frob (reffer setter type)
849              `(progn
850                 (define-source-transform ,reffer (a i)
851                   `(aref (the ,',type ,a) ,i))
852                 (define-source-transform ,setter (a i v)
853                   `(%aset (the ,',type ,a) ,i ,v)))))
854   (define-frob svref %svset simple-vector)
855   (define-frob schar %scharset simple-string)
856   (define-frob char %charset string))
857
858 (macrolet (;; This is a handy macro for computing the row-major index
859            ;; given a set of indices. We wrap each index with a call
860            ;; to %CHECK-BOUND to ensure that everything works out
861            ;; correctly. We can wrap all the interior arithmetic with
862            ;; TRULY-THE INDEX because we know the resultant
863            ;; row-major index must be an index.
864            (with-row-major-index ((array indices index &optional new-value)
865                                   &rest body)
866              `(let (n-indices dims)
867                 (dotimes (i (length ,indices))
868                   (push (make-symbol (format nil "INDEX-~D" i)) n-indices)
869                   (push (make-symbol (format nil "DIM-~D" i)) dims))
870                 (setf n-indices (nreverse n-indices))
871                 (setf dims (nreverse dims))
872                 `(lambda (,',array ,@n-indices
873                                    ,@',(when new-value (list new-value)))
874                    (let* (,@(let ((,index -1))
875                               (mapcar (lambda (name)
876                                         `(,name (array-dimension
877                                                  ,',array
878                                                  ,(incf ,index))))
879                                       dims))
880                             (,',index
881                              ,(if (null dims)
882                                   0
883                                 (do* ((dims dims (cdr dims))
884                                       (indices n-indices (cdr indices))
885                                       (last-dim nil (car dims))
886                                       (form `(%check-bound ,',array
887                                                            ,(car dims)
888                                                            ,(car indices))
889                                             `(truly-the
890                                               index
891                                               (+ (truly-the index
892                                                             (* ,form
893                                                                ,last-dim))
894                                                  (%check-bound
895                                                   ,',array
896                                                   ,(car dims)
897                                                   ,(car indices))))))
898                                     ((null (cdr dims)) form)))))
899                      ,',@body)))))
900
901   ;; Just return the index after computing it.
902   (deftransform array-row-major-index ((array &rest indices))
903     (with-row-major-index (array indices index)
904       index))
905
906   ;; Convert AREF and %ASET into a HAIRY-DATA-VECTOR-REF (or
907   ;; HAIRY-DATA-VECTOR-SET) with the set of indices replaced with the an
908   ;; expression for the row major index.
909   (deftransform aref ((array &rest indices))
910     (with-row-major-index (array indices index)
911       (hairy-data-vector-ref array index)))
912
913   (deftransform %aset ((array &rest stuff))
914     (let ((indices (butlast stuff)))
915       (with-row-major-index (array indices index new-value)
916         (hairy-data-vector-set array index new-value)))))
917
918 ;; For AREF of vectors we do the bounds checking in the callee. This
919 ;; lets us do a significantly more efficient check for simple-arrays
920 ;; without bloating the code. If we already know the type of the array
921 ;; with sufficient precision, skip directly to DATA-VECTOR-REF.
922 (deftransform aref ((array index) (t t) * :node node)
923   (let* ((type (lvar-type array))
924          (element-ctype (extract-upgraded-element-type array)))
925     (cond
926       ((and (array-type-p type)
927             (null (array-type-complexp type))
928             (not (eql element-ctype *wild-type*))
929             (eql (length (array-type-dimensions type)) 1))
930        (let* ((declared-element-ctype (extract-declared-element-type array))
931               (bare-form
932                `(data-vector-ref array
933                  (%check-bound array (array-dimension array 0) index))))
934          (if (type= declared-element-ctype element-ctype)
935              bare-form
936              `(the ,(type-specifier declared-element-ctype) ,bare-form))))
937       ((policy node (zerop insert-array-bounds-checks))
938        `(hairy-data-vector-ref array index))
939       (t `(hairy-data-vector-ref/check-bounds array index)))))
940
941 (deftransform %aset ((array index new-value) (t t t) * :node node)
942   (if (policy node (zerop insert-array-bounds-checks))
943       `(hairy-data-vector-set array index new-value)
944       `(hairy-data-vector-set/check-bounds array index new-value)))
945
946 ;;; But if we find out later that there's some useful type information
947 ;;; available, switch back to the normal one to give other transforms
948 ;;; a stab at it.
949 (macrolet ((define (name transform-to extra extra-type)
950              (declare (ignore extra-type))
951              `(deftransform ,name ((array index ,@extra))
952                 (let ((type (lvar-type array))
953                       (element-type (extract-upgraded-element-type array))
954                       (declared-type (extract-declared-element-type array)))
955                   ;; If an element type has been declared, we want to
956                   ;; use that information it for type checking (even
957                   ;; if the access can't be optimized due to the array
958                   ;; not being simple).
959                   (when (and (eql element-type *wild-type*)
960                              ;; This type logic corresponds to the special
961                              ;; case for strings in HAIRY-DATA-VECTOR-REF
962                              ;; (generic/vm-tran.lisp)
963                              (not (csubtypep type (specifier-type 'simple-string))))
964                     (when (or (not (array-type-p type))
965                               ;; If it's a simple array, we might be able
966                               ;; to inline the access completely.
967                               (not (null (array-type-complexp type))))
968                       (give-up-ir1-transform
969                        "Upgraded element type of array is not known at compile time.")))
970                   ,(if extra
971                        ``(truly-the ,declared-type
972                                     (,',transform-to array
973                                                      (%check-bound array
974                                                                    (array-dimension array 0)
975                                                                    index)
976                                                      (the ,declared-type ,@',extra)))
977                        ``(the ,declared-type
978                            (,',transform-to array
979                                             (%check-bound array
980                                                           (array-dimension array 0)
981                                                           index))))))))
982   (define hairy-data-vector-ref/check-bounds
983       hairy-data-vector-ref nil nil)
984   (define hairy-data-vector-set/check-bounds
985       hairy-data-vector-set (new-value) (*)))
986
987 ;;; Just convert into a HAIRY-DATA-VECTOR-REF (or
988 ;;; HAIRY-DATA-VECTOR-SET) after checking that the index is inside the
989 ;;; array total size.
990 (deftransform row-major-aref ((array index))
991   `(hairy-data-vector-ref array
992                           (%check-bound array (array-total-size array) index)))
993 (deftransform %set-row-major-aref ((array index new-value))
994   `(hairy-data-vector-set array
995                           (%check-bound array (array-total-size array) index)
996                           new-value))
997 \f
998 ;;;; bit-vector array operation canonicalization
999 ;;;;
1000 ;;;; We convert all bit-vector operations to have the result array
1001 ;;;; specified. This allows any result allocation to be open-coded,
1002 ;;;; and eliminates the need for any VM-dependent transforms to handle
1003 ;;;; these cases.
1004
1005 (macrolet ((def (fun)
1006              `(progn
1007                (deftransform ,fun ((bit-array-1 bit-array-2
1008                                                 &optional result-bit-array)
1009                                    (bit-vector bit-vector &optional null) *
1010                                    :policy (>= speed space))
1011                  `(,',fun bit-array-1 bit-array-2
1012                    (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1013                ;; If result is T, make it the first arg.
1014                (deftransform ,fun ((bit-array-1 bit-array-2 result-bit-array)
1015                                    (bit-vector bit-vector (eql t)) *)
1016                  `(,',fun bit-array-1 bit-array-2 bit-array-1)))))
1017   (def bit-and)
1018   (def bit-ior)
1019   (def bit-xor)
1020   (def bit-eqv)
1021   (def bit-nand)
1022   (def bit-nor)
1023   (def bit-andc1)
1024   (def bit-andc2)
1025   (def bit-orc1)
1026   (def bit-orc2))
1027
1028 ;;; Similar for BIT-NOT, but there is only one arg...
1029 (deftransform bit-not ((bit-array-1 &optional result-bit-array)
1030                        (bit-vector &optional null) *
1031                        :policy (>= speed space))
1032   '(bit-not bit-array-1
1033             (make-array (array-dimension bit-array-1 0) :element-type 'bit)))
1034 (deftransform bit-not ((bit-array-1 result-bit-array)
1035                        (bit-vector (eql t)))
1036   '(bit-not bit-array-1 bit-array-1))
1037 \f
1038 ;;; Pick off some constant cases.
1039 (defoptimizer (array-header-p derive-type) ((array))
1040   (let ((type (lvar-type array)))
1041     (cond ((not (array-type-p type))
1042            ;; FIXME: use analogue of ARRAY-TYPE-DIMENSIONS-OR-GIVE-UP
1043            nil)
1044           (t
1045            (let ((dims (array-type-dimensions type)))
1046              (cond ((csubtypep type (specifier-type '(simple-array * (*))))
1047                     ;; no array header
1048                     (specifier-type 'null))
1049                    ((and (listp dims) (/= (length dims) 1))
1050                     ;; multi-dimensional array, will have a header
1051                     (specifier-type '(eql t)))
1052                    ((eql (array-type-complexp type) t)
1053                     (specifier-type '(eql t)))
1054                    (t
1055                     nil)))))))