461138e8ce18ca4bf64d20dfe4d0636b32f2ce85
[sbcl.git] / src / compiler / generic / vm-tran.lisp
1 ;;;; implementation-dependent 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
14 ;;; We need to define these predicates, since the TYPEP source
15 ;;; transform picks whichever predicate was defined last when there
16 ;;; are multiple predicates for equivalent types.
17 (define-source-transform short-float-p (x) `(single-float-p ,x))
18 #!-long-float
19 (define-source-transform long-float-p (x) `(double-float-p ,x))
20
21 (define-source-transform compiled-function-p (x)
22   `(functionp ,x))
23
24 (define-source-transform char-int (x)
25   `(char-code ,x))
26
27 (deftransform abs ((x) (rational))
28   '(if (< x 0) (- x) x))
29
30 ;;; The layout is stored in slot 0.
31 (define-source-transform %instance-layout (x)
32   `(truly-the layout (%instance-ref ,x 0)))
33 (define-source-transform %set-instance-layout (x val)
34   `(%instance-set ,x 0 (the layout ,val)))
35 \f
36 ;;;; character support
37
38 ;;; In our implementation there are really only BASE-CHARs.
39 (define-source-transform characterp (obj)
40   `(base-char-p ,obj))
41 \f
42 ;;;; simplifying HAIRY-DATA-VECTOR-REF and HAIRY-DATA-VECTOR-SET
43
44 (deftransform hairy-data-vector-ref ((string index) (simple-string t))
45   (let ((ctype (lvar-type string)))
46     (if (array-type-p ctype)
47         ;; the other transform will kick in, so that's OK
48         (give-up-ir1-transform)
49         `(etypecase string
50           ((simple-array character (*)) (data-vector-ref string index))
51           ((simple-array nil (*)) (data-vector-ref string index))))))
52
53 (deftransform hairy-data-vector-ref ((array index) (array t) *)
54   "avoid runtime dispatch on array element type"
55   (let ((element-ctype (extract-upgraded-element-type array))
56         (declared-element-ctype (extract-declared-element-type array)))
57     (declare (type ctype element-ctype))
58     (when (eq *wild-type* element-ctype)
59       (give-up-ir1-transform
60        "Upgraded element type of array is not known at compile time."))
61     ;; (The expansion here is basically a degenerate case of
62     ;; WITH-ARRAY-DATA. Since WITH-ARRAY-DATA is implemented as a
63     ;; macro, and macros aren't expanded in transform output, we have
64     ;; to hand-expand it ourselves.)
65     (let ((element-type-specifier (type-specifier element-ctype)))
66       `(multiple-value-bind (array index)
67            (%data-vector-and-index array index)
68          (declare (type (simple-array ,element-type-specifier 1) array))
69          ,(let ((bare-form '(data-vector-ref array index)))
70             (if (type= element-ctype declared-element-ctype)
71                 bare-form
72                 `(the ,(type-specifier declared-element-ctype)
73                       ,bare-form)))))))
74
75 (deftransform data-vector-ref ((array index)
76                                (simple-array t))
77   (let ((array-type (lvar-type array)))
78     (unless (array-type-p array-type)
79       (give-up-ir1-transform))
80     (let ((dims (array-type-dimensions array-type)))
81       (when (or (atom dims) (= (length dims) 1))
82         (give-up-ir1-transform))
83       (let ((el-type (array-type-specialized-element-type array-type))
84             (total-size (if (member '* dims)
85                             '*
86                             (reduce #'* dims))))
87         `(data-vector-ref (truly-the (simple-array ,(type-specifier el-type)
88                                                    (,total-size))
89                                      (%array-data-vector array))
90                           index)))))
91
92 (deftransform hairy-data-vector-set ((string index new-value)
93                                      (simple-string t t))
94   (let ((ctype (lvar-type string)))
95     (if (array-type-p ctype)
96         ;; the other transform will kick in, so that's OK
97         (give-up-ir1-transform)
98         `(etypecase string
99           ((simple-array character (*))
100            (data-vector-set string index new-value))
101           ((simple-array nil (*))
102            (data-vector-set string index new-value))))))
103
104 (deftransform hairy-data-vector-set ((array index new-value)
105                                      (array t t)
106                                      *)
107   "avoid runtime dispatch on array element type"
108   (let ((element-ctype (extract-upgraded-element-type array))
109         (declared-element-ctype (extract-declared-element-type array)))
110     (declare (type ctype element-ctype))
111     (when (eq *wild-type* element-ctype)
112       (give-up-ir1-transform
113        "Upgraded element type of array is not known at compile time."))
114     (let ((element-type-specifier (type-specifier element-ctype)))
115       `(multiple-value-bind (array index)
116            (%data-vector-and-index array index)
117          (declare (type (simple-array ,element-type-specifier 1) array)
118                   (type ,element-type-specifier new-value))
119          ,(if (type= element-ctype declared-element-ctype)
120               '(data-vector-set array index new-value)
121               `(truly-the ,(type-specifier declared-element-ctype)
122                  (data-vector-set array index
123                   (the ,(type-specifier declared-element-ctype)
124                        new-value))))))))
125
126 (deftransform data-vector-set ((array index new-value)
127                                (simple-array t t))
128   (let ((array-type (lvar-type array)))
129     (unless (array-type-p array-type)
130       (give-up-ir1-transform))
131     (let ((dims (array-type-dimensions array-type)))
132       (when (or (atom dims) (= (length dims) 1))
133         (give-up-ir1-transform))
134       (let ((el-type (array-type-specialized-element-type array-type))
135             (total-size (if (member '* dims)
136                             '*
137                             (reduce #'* dims))))
138         `(data-vector-set (truly-the (simple-array ,(type-specifier el-type)
139                                                    (,total-size))
140                                      (%array-data-vector array))
141                           index
142                           new-value)))))
143
144 (defoptimizer (%data-vector-and-index derive-type) ((array index))
145   (let ((atype (lvar-type array)))
146     (when (array-type-p atype)
147       (values-specifier-type
148        `(values (simple-array ,(type-specifier
149                                 (array-type-specialized-element-type atype))
150                               (*))
151                 index)))))
152
153 (deftransform %data-vector-and-index ((%array %index)
154                                       (simple-array t)
155                                       *)
156   ;; KLUDGE: why the percent signs?  Well, ARRAY and INDEX are
157   ;; respectively exported from the CL and SB!INT packages, which
158   ;; means that they're visible to all sorts of things.  If the
159   ;; compiler can prove that the call to ARRAY-HEADER-P, below, either
160   ;; returns T or NIL, it will delete the irrelevant branch.  However,
161   ;; user code might have got here with a variable named CL:ARRAY, and
162   ;; quite often compiler code with a variable named SB!INT:INDEX, so
163   ;; this can generate code deletion notes for innocuous user code:
164   ;; (DEFUN F (ARRAY I) (DECLARE (SIMPLE-VECTOR ARRAY)) (AREF ARRAY I))
165   ;; -- CSR, 2003-04-01
166
167   ;; We do this solely for the -OR-GIVE-UP side effect, since we want
168   ;; to know that the type can be figured out in the end before we
169   ;; proceed, but we don't care yet what the type will turn out to be.
170   (upgraded-element-type-specifier-or-give-up %array)
171
172   '(if (array-header-p %array)
173        (values (%array-data-vector %array) %index)
174        (values %array %index)))
175
176 ;;; transforms for getting at simple arrays of (UNSIGNED-BYTE N) when (< N 8)
177 ;;;
178 ;;; FIXME: In CMU CL, these were commented out with #+NIL. Why? Should
179 ;;; we fix them or should we delete them? (Perhaps these definitions
180 ;;; predate the various DATA-VECTOR-REF-FOO VOPs which have
181 ;;; (:TRANSLATE DATA-VECTOR-REF), and are redundant now?)
182 #+nil
183 (macrolet
184     ((frob (type bits)
185        (let ((elements-per-word (truncate sb!vm:n-word-bits bits)))
186          `(progn
187             (deftransform data-vector-ref ((vector index)
188                                            (,type *))
189               `(multiple-value-bind (word bit)
190                    (floor index ,',elements-per-word)
191                  (ldb ,(ecase sb!vm:target-byte-order
192                          (:little-endian '(byte ,bits (* bit ,bits)))
193                          (:big-endian '(byte ,bits (- sb!vm:n-word-bits
194                                                       (* (1+ bit) ,bits)))))
195                       (%raw-bits vector (+ word sb!vm:vector-data-offset)))))
196             (deftransform data-vector-set ((vector index new-value)
197                                            (,type * *))
198               `(multiple-value-bind (word bit)
199                    (floor index ,',elements-per-word)
200                  (setf (ldb ,(ecase sb!vm:target-byte-order
201                                (:little-endian '(byte ,bits (* bit ,bits)))
202                                (:big-endian
203                                 '(byte ,bits (- sb!vm:n-word-bits
204                                                 (* (1+ bit) ,bits)))))
205                             (%raw-bits vector (+ word sb!vm:vector-data-offset)))
206                        new-value)))))))
207   (frob simple-bit-vector 1)
208   (frob (simple-array (unsigned-byte 2) (*)) 2)
209   (frob (simple-array (unsigned-byte 4) (*)) 4))
210 \f
211 ;;;; BIT-VECTOR hackery
212
213 ;;; SIMPLE-BIT-VECTOR bit-array operations are transformed to a word
214 ;;; loop that does 32 bits at a time.
215 ;;;
216 ;;; FIXME: This is a lot of repeatedly macroexpanded code. It should
217 ;;; be a function call instead.
218 (macrolet ((def (bitfun wordfun)
219              `(deftransform ,bitfun ((bit-array-1 bit-array-2 result-bit-array)
220                                      (simple-bit-vector
221                                       simple-bit-vector
222                                       simple-bit-vector)
223                                      *
224                                      :node node :policy (>= speed space))
225                 `(progn
226                    ,@(unless (policy node (zerop safety))
227                              '((unless (= (length bit-array-1)
228                                           (length bit-array-2)
229                                           (length result-bit-array))
230                                  (error "Argument and/or result bit arrays are not the same length:~
231                          ~%  ~S~%  ~S  ~%  ~S"
232                                         bit-array-1
233                                         bit-array-2
234                                         result-bit-array))))
235                   (let ((length (length result-bit-array)))
236                     (if (= length 0)
237                         ;; We avoid doing anything to 0-length
238                         ;; bit-vectors, or rather, the memory that
239                         ;; follows them. Other divisible-by-32 cases
240                         ;; are handled by the (1- length), below.
241                         ;; CSR, 2002-04-24
242                         result-bit-array
243                         (do ((index sb!vm:vector-data-offset (1+ index))
244                              (end-1 (+ sb!vm:vector-data-offset
245                                        ;; bit-vectors of length 1-32
246                                        ;; need precisely one (SETF
247                                        ;; %RAW-BITS), done here in the
248                                        ;; epilogue. - CSR, 2002-04-24
249                                        (truncate (truly-the index (1- length))
250                                                  sb!vm:n-word-bits))))
251                             ((= index end-1)
252                              (setf (%raw-bits result-bit-array index)
253                                    (,',wordfun (%raw-bits bit-array-1 index)
254                                                (%raw-bits bit-array-2 index)))
255                              result-bit-array)
256                           (declare (optimize (speed 3) (safety 0))
257                                    (type index index end-1))
258                           (setf (%raw-bits result-bit-array index)
259                                 (,',wordfun (%raw-bits bit-array-1 index)
260                                             (%raw-bits bit-array-2 index))))))))))
261  (def bit-and 32bit-logical-and)
262  (def bit-ior 32bit-logical-or)
263  (def bit-xor 32bit-logical-xor)
264  (def bit-eqv 32bit-logical-eqv)
265  (def bit-nand 32bit-logical-nand)
266  (def bit-nor 32bit-logical-nor)
267  (def bit-andc1 32bit-logical-andc1)
268  (def bit-andc2 32bit-logical-andc2)
269  (def bit-orc1 32bit-logical-orc1)
270  (def bit-orc2 32bit-logical-orc2))
271
272 (deftransform bit-not
273               ((bit-array result-bit-array)
274                (simple-bit-vector simple-bit-vector) *
275                :node node :policy (>= speed space))
276   `(progn
277      ,@(unless (policy node (zerop safety))
278          '((unless (= (length bit-array)
279                       (length result-bit-array))
280              (error "Argument and result bit arrays are not the same length:~
281                      ~%  ~S~%  ~S"
282                     bit-array result-bit-array))))
283     (let ((length (length result-bit-array)))
284       (if (= length 0)
285           ;; We avoid doing anything to 0-length bit-vectors, or
286           ;; rather, the memory that follows them. Other
287           ;; divisible-by-32 cases are handled by the (1- length),
288           ;; below.  CSR, 2002-04-24
289           result-bit-array
290           (do ((index sb!vm:vector-data-offset (1+ index))
291                (end-1 (+ sb!vm:vector-data-offset
292                          ;; bit-vectors of length 1-32 need precisely
293                          ;; one (SETF %RAW-BITS), done here in the
294                          ;; epilogue. - CSR, 2002-04-24
295                          (truncate (truly-the index (1- length))
296                                    sb!vm:n-word-bits))))
297               ((= index end-1)
298                (setf (%raw-bits result-bit-array index)
299                      (32bit-logical-not (%raw-bits bit-array index)))
300                result-bit-array)
301             (declare (optimize (speed 3) (safety 0))
302                      (type index index end-1))
303             (setf (%raw-bits result-bit-array index)
304                   (32bit-logical-not (%raw-bits bit-array index))))))))
305
306 (deftransform bit-vector-= ((x y) (simple-bit-vector simple-bit-vector))
307   `(and (= (length x) (length y))
308         (let ((length (length x)))
309           (or (= length 0)
310               (do* ((i sb!vm:vector-data-offset (+ i 1))
311                     (end-1 (+ sb!vm:vector-data-offset
312                               (floor (1- length) sb!vm:n-word-bits))))
313                    ((= i end-1)
314                     (let* ((extra (mod length sb!vm:n-word-bits))
315                            (mask (1- (ash 1 extra)))
316                            (numx
317                             (logand
318                              (ash mask
319                                   ,(ecase sb!c:*backend-byte-order*
320                                      (:little-endian 0)
321                                      (:big-endian
322                                       '(- sb!vm:n-word-bits extra))))
323                              (%raw-bits x i)))
324                            (numy
325                             (logand
326                              (ash mask
327                                   ,(ecase sb!c:*backend-byte-order*
328                                      (:little-endian 0)
329                                      (:big-endian
330                                       '(- sb!vm:n-word-bits extra))))
331                              (%raw-bits y i))))
332                       (declare (type (integer 0 31) extra)
333                                (type sb!vm:word mask numx numy))
334                       (= numx numy)))
335                 (declare (type index i end-1))
336                 (let ((numx (%raw-bits x i))
337                       (numy (%raw-bits y i)))
338                   (declare (type sb!vm:word numx numy))
339                   (unless (= numx numy)
340                     (return nil))))))))
341
342 (deftransform count ((sequence item) (simple-bit-vector bit) *
343                      :policy (>= speed space))
344   `(let ((length (length sequence)))
345     (if (zerop length)
346         0
347         (do ((index sb!vm:vector-data-offset (1+ index))
348              (count 0)
349              (end-1 (+ sb!vm:vector-data-offset
350                        (truncate (truly-the index (1- length))
351                                  sb!vm:n-word-bits))))
352             ((= index end-1)
353              (let* ((extra (mod length sb!vm:n-word-bits))
354                     (mask (1- (ash 1 extra)))
355                     (bits (logand (ash mask
356                                        ,(ecase sb!c:*backend-byte-order*
357                                                (:little-endian 0)
358                                                (:big-endian
359                                                 '(- sb!vm:n-word-bits extra))))
360                                   (%raw-bits sequence index))))
361                (declare (type sb!vm:word mask bits))
362                ;; could consider LOGNOT for the zero case instead of
363                ;; doing the subtraction...
364                (incf count ,(if (constant-lvar-p item)
365                                 (if (zerop (lvar-value item))
366                                     '(- extra (logcount bits))
367                                     '(logcount bits))
368                                 '(if (zerop item)
369                                      (- extra (logcount bits))
370                                      (logcount bits))))))
371           (declare (type index index count end-1)
372                    (optimize (speed 3) (safety 0)))
373           (incf count ,(if (constant-lvar-p item)
374                            (if (zerop (lvar-value item))
375                                '(- sb!vm:n-word-bits (logcount (%raw-bits sequence index)))
376                                '(logcount (%raw-bits sequence index)))
377                            '(if (zerop item)
378                              (- sb!vm:n-word-bits (logcount (%raw-bits sequence index)))
379                              (logcount (%raw-bits sequence index)))))))))
380
381 (deftransform fill ((sequence item) (simple-bit-vector bit) *
382                     :policy (>= speed space))
383   (let ((value (if (constant-lvar-p item)
384                    (if (= (lvar-value item) 0)
385                        0
386                        #.(1- (ash 1 32)))
387                    `(if (= item 0) 0 #.(1- (ash 1 32))))))
388     `(let ((length (length sequence))
389            (value ,value))
390        (if (= length 0)
391            sequence
392            (do ((index sb!vm:vector-data-offset (1+ index))
393                 (end-1 (+ sb!vm:vector-data-offset
394                           ;; bit-vectors of length 1-32 need precisely
395                           ;; one (SETF %RAW-BITS), done here in the
396                           ;; epilogue. - CSR, 2002-04-24
397                           (truncate (truly-the index (1- length))
398                                     sb!vm:n-word-bits))))
399                ((= index end-1)
400                 (setf (%raw-bits sequence index) value)
401                 sequence)
402              (declare (optimize (speed 3) (safety 0))
403                       (type index index end-1))
404              (setf (%raw-bits sequence index) value))))))
405
406 (deftransform fill ((sequence item) (simple-base-string base-char) *
407                     :policy (>= speed space))
408   (let ((value (if (constant-lvar-p item)
409                    (let* ((char (lvar-value item))
410                           (code (sb!xc:char-code char)))
411                      (logior code (ash code 8) (ash code 16) (ash code 24)))
412                    `(let ((code (sb!xc:char-code item)))
413                      (logior code (ash code 8) (ash code 16) (ash code 24))))))
414     `(let ((length (length sequence))
415            (value ,value))
416       (multiple-value-bind (times rem)
417           (truncate length 4)
418         (do ((index sb!vm:vector-data-offset (1+ index))
419              (end (+ times sb!vm:vector-data-offset)))
420             ((= index end)
421              (let ((place (* times 4)))
422                (declare (fixnum place))
423                (dotimes (j rem sequence)
424                  (declare (index j))
425                  (setf (schar sequence (the index (+ place j))) item))))
426           (declare (optimize (speed 3) (safety 0))
427                    (type index index))
428           (setf (%raw-bits sequence index) value))))))
429 \f
430 ;;;; %BYTE-BLT
431
432 ;;; FIXME: The old CMU CL code used various COPY-TO/FROM-SYSTEM-AREA
433 ;;; stuff (with all the associated bit-index cruft and overflow
434 ;;; issues) even for byte moves. In SBCL, we're converting to byte
435 ;;; moves as problems are discovered with the old code, and this is
436 ;;; currently (ca. sbcl-0.6.12.30) the main interface for code in
437 ;;; SB!KERNEL and SB!SYS (e.g. i/o code). It's not clear that it's the
438 ;;; ideal interface, though, and it probably deserves some thought.
439 (deftransform %byte-blt ((src src-start dst dst-start dst-end)
440                          ((or (simple-unboxed-array (*)) system-area-pointer)
441                           index
442                           (or (simple-unboxed-array (*)) system-area-pointer)
443                           index
444                           index))
445   ;; FIXME: CMU CL had a hairier implementation of this (back when it
446   ;; was still called (%PRIMITIVE BYTE-BLT). It had the small problem
447   ;; that it didn't work for large (>16M) values of SRC-START or
448   ;; DST-START. However, it might have been more efficient. In
449   ;; particular, I don't really know how much the foreign function
450   ;; call costs us here. My guess is that if the overhead is
451   ;; acceptable for SQRT and COS, it's acceptable here, but this
452   ;; should probably be checked. -- WHN
453   '(flet ((sapify (thing)
454             (etypecase thing
455               (system-area-pointer thing)
456               ;; FIXME: The code here rather relies on the simple
457               ;; unboxed array here having byte-sized entries. That
458               ;; should be asserted explicitly, I just haven't found
459               ;; a concise way of doing it. (It would be nice to
460               ;; declare it in the DEFKNOWN too.)
461               ((simple-unboxed-array (*)) (vector-sap thing)))))
462      (declare (inline sapify))
463      (without-gcing
464       (memmove (sap+ (sapify dst) dst-start)
465                (sap+ (sapify src) src-start)
466                (- dst-end dst-start)))
467      (values)))
468 \f
469 ;;;; transforms for EQL of floating point values
470
471 (deftransform eql ((x y) (single-float single-float))
472   '(= (single-float-bits x) (single-float-bits y)))
473
474 (deftransform eql ((x y) (double-float double-float))
475   '(and (= (double-float-low-bits x) (double-float-low-bits y))
476         (= (double-float-high-bits x) (double-float-high-bits y))))
477
478 \f
479 ;;;; modular functions
480 (define-good-modular-fun logand)
481 (define-good-modular-fun logior)
482 ;;; FIXME: XOR? ANDC1, ANDC2?  -- CSR, 2003-09-16
483
484 (macrolet
485     ((def (name width)
486          `(progn
487             (defknown ,name (integer (integer 0)) (unsigned-byte ,width)
488                       (foldable flushable movable))
489             (define-modular-fun-optimizer ash ((integer count) :width width)
490               (when (and (<= width 32)
491                          (constant-lvar-p count) ;?
492                          (plusp (lvar-value count)))
493                 (cut-to-width integer width)
494                 ',name))
495             (setf (gethash ',name *modular-versions*) `(ash ,',width)))))
496   #!-alpha (def sb!vm::ash-left-mod32 32)
497   #!+alpha (def sb!vm::ash-left-mod64 64))
498 \f
499 ;;; There are two different ways the multiplier can be recoded. The
500 ;;; more obvious is to shift X by the correct amount for each bit set
501 ;;; in Y and to sum the results. But if there is a string of bits that
502 ;;; are all set, you can add X shifted by one more then the bit
503 ;;; position of the first set bit and subtract X shifted by the bit
504 ;;; position of the last set bit. We can't use this second method when
505 ;;; the high order bit is bit 31 because shifting by 32 doesn't work
506 ;;; too well.
507 (defun ub32-strength-reduce-constant-multiply (arg num)
508   (declare (type (unsigned-byte 32) num))
509   (let ((adds 0) (shifts 0)
510         (result nil) first-one)
511     (labels ((add (next-factor)
512                (setf result
513                      (if result
514                          (progn (incf adds) `(+ ,result ,next-factor))
515                          next-factor))))
516       (declare (inline add))
517       (dotimes (bitpos 32)
518         (if first-one
519             (when (not (logbitp bitpos num))
520               (add (if (= (1+ first-one) bitpos)
521                        ;; There is only a single bit in the string.
522                        (progn (incf shifts) `(ash ,arg ,first-one))
523                        ;; There are at least two.
524                        (progn
525                          (incf adds)
526                          (incf shifts 2)
527                          `(- (ash ,arg ,bitpos)
528                              (ash ,arg ,first-one)))))
529               (setf first-one nil))
530             (when (logbitp bitpos num)
531               (setf first-one bitpos))))
532       (when first-one
533         (cond ((= first-one 31))
534               ((= first-one 30) (incf shifts) (add `(ash ,arg 30)))
535               (t
536                (incf shifts 2)
537                (incf adds)
538                (add `(- (ash ,arg 31)
539                         (ash ,arg ,first-one)))))
540         (incf shifts)
541         (add `(ash ,arg 31))))
542     (values (if (plusp adds)
543                 `(logand ,result #.(1- (ash 1 32))) ; using modular arithmetic
544                 result)
545             adds
546             shifts)))