1.0.30.38: faster TRUNCATE on floats
[sbcl.git] / src / compiler / float-tran.lisp
1 ;;;; This file contains floating-point-specific transforms, and may be
2 ;;;; somewhat implementation-dependent in its assumptions of what the
3 ;;;; formats are.
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!C")
15 \f
16 ;;;; coercions
17
18 (defknown %single-float (real) single-float
19     (movable foldable))
20 (defknown %double-float (real) double-float
21     (movable foldable))
22
23 (deftransform float ((n f) (* single-float) *)
24   '(%single-float n))
25
26 (deftransform float ((n f) (* double-float) *)
27   '(%double-float n))
28
29 (deftransform float ((n) *)
30   '(if (floatp n)
31        n
32        (%single-float n)))
33
34 (deftransform %single-float ((n) (single-float) *)
35   'n)
36
37 (deftransform %double-float ((n) (double-float) *)
38   'n)
39
40 ;;; RANDOM
41 (macrolet ((frob (fun type)
42              `(deftransform random ((num &optional state)
43                                     (,type &optional *) *)
44                 "Use inline float operations."
45                 '(,fun num (or state *random-state*)))))
46   (frob %random-single-float single-float)
47   (frob %random-double-float double-float))
48
49 ;;; Mersenne Twister RNG
50 ;;;
51 ;;; FIXME: It's unpleasant to have RANDOM functionality scattered
52 ;;; through the code this way. It would be nice to move this into the
53 ;;; same file as the other RANDOM definitions.
54 (deftransform random ((num &optional state)
55                       ((integer 1 #.(expt 2 sb!vm::n-word-bits)) &optional *))
56   ;; FIXME: I almost conditionalized this as #!+sb-doc. Find some way
57   ;; of automatically finding #!+sb-doc in proximity to DEFTRANSFORM
58   ;; to let me scan for places that I made this mistake and didn't
59   ;; catch myself.
60   "use inline (UNSIGNED-BYTE 32) operations"
61   (let ((type (lvar-type num))
62         (limit (expt 2 sb!vm::n-word-bits))
63         (random-chunk (ecase sb!vm::n-word-bits
64                         (32 'random-chunk)
65                         (64 'sb!kernel::big-random-chunk))))
66     (if (numeric-type-p type)
67         (let ((num-high (numeric-type-high (lvar-type num))))
68           (aver num-high)
69           (cond ((constant-lvar-p num)
70                  ;; Check the worst case sum absolute error for the
71                  ;; random number expectations.
72                  (let ((rem (rem limit num-high)))
73                    (unless (< (/ (* 2 rem (- num-high rem))
74                                  num-high limit)
75                               (expt 2 (- sb!kernel::random-integer-extra-bits)))
76                      (give-up-ir1-transform
77                       "The random number expectations are inaccurate."))
78                    (if (= num-high limit)
79                        `(,random-chunk (or state *random-state*))
80                        #!-(or x86 x86-64)
81                        `(rem (,random-chunk (or state *random-state*)) num)
82                        #!+(or x86 x86-64)
83                        ;; Use multiplication, which is faster.
84                        `(values (sb!bignum::%multiply
85                                  (,random-chunk (or state *random-state*))
86                                  num)))))
87                 ((> num-high random-fixnum-max)
88                  (give-up-ir1-transform
89                   "The range is too large to ensure an accurate result."))
90                 #!+(or x86 x86-64)
91                 ((< num-high limit)
92                  `(values (sb!bignum::%multiply
93                            (,random-chunk (or state *random-state*))
94                            num)))
95                 (t
96                  `(rem (,random-chunk (or state *random-state*)) num))))
97         ;; KLUDGE: a relatively conservative treatment, but better
98         ;; than a bug (reported by PFD sbcl-devel towards the end of
99         ;; 2004-11.
100         '(rem (random-chunk (or state *random-state*)) num))))
101 \f
102 ;;;; float accessors
103
104 (defknown make-single-float ((signed-byte 32)) single-float
105   (movable foldable flushable))
106
107 (defknown make-double-float ((signed-byte 32) (unsigned-byte 32)) double-float
108   (movable foldable flushable))
109
110 (defknown single-float-bits (single-float) (signed-byte 32)
111   (movable foldable flushable))
112
113 (defknown double-float-high-bits (double-float) (signed-byte 32)
114   (movable foldable flushable))
115
116 (defknown double-float-low-bits (double-float) (unsigned-byte 32)
117   (movable foldable flushable))
118
119 (deftransform float-sign ((float &optional float2)
120                           (single-float &optional single-float) *)
121   (if float2
122       (let ((temp (gensym)))
123         `(let ((,temp (abs float2)))
124           (if (minusp (single-float-bits float)) (- ,temp) ,temp)))
125       '(if (minusp (single-float-bits float)) -1f0 1f0)))
126
127 (deftransform float-sign ((float &optional float2)
128                           (double-float &optional double-float) *)
129   (if float2
130       (let ((temp (gensym)))
131         `(let ((,temp (abs float2)))
132           (if (minusp (double-float-high-bits float)) (- ,temp) ,temp)))
133       '(if (minusp (double-float-high-bits float)) -1d0 1d0)))
134 \f
135 ;;;; DECODE-FLOAT, INTEGER-DECODE-FLOAT, and SCALE-FLOAT
136
137 (defknown decode-single-float (single-float)
138   (values single-float single-float-exponent (single-float -1f0 1f0))
139   (movable foldable flushable))
140
141 (defknown decode-double-float (double-float)
142   (values double-float double-float-exponent (double-float -1d0 1d0))
143   (movable foldable flushable))
144
145 (defknown integer-decode-single-float (single-float)
146   (values single-float-significand single-float-int-exponent (integer -1 1))
147   (movable foldable flushable))
148
149 (defknown integer-decode-double-float (double-float)
150   (values double-float-significand double-float-int-exponent (integer -1 1))
151   (movable foldable flushable))
152
153 (defknown scale-single-float (single-float integer) single-float
154   (movable foldable flushable))
155
156 (defknown scale-double-float (double-float integer) double-float
157   (movable foldable flushable))
158
159 (deftransform decode-float ((x) (single-float) *)
160   '(decode-single-float x))
161
162 (deftransform decode-float ((x) (double-float) *)
163   '(decode-double-float x))
164
165 (deftransform integer-decode-float ((x) (single-float) *)
166   '(integer-decode-single-float x))
167
168 (deftransform integer-decode-float ((x) (double-float) *)
169   '(integer-decode-double-float x))
170
171 (deftransform scale-float ((f ex) (single-float *) *)
172   (if (and #!+x86 t #!-x86 nil
173            (csubtypep (lvar-type ex)
174                       (specifier-type '(signed-byte 32))))
175       '(coerce (%scalbn (coerce f 'double-float) ex) 'single-float)
176       '(scale-single-float f ex)))
177
178 (deftransform scale-float ((f ex) (double-float *) *)
179   (if (and #!+x86 t #!-x86 nil
180            (csubtypep (lvar-type ex)
181                       (specifier-type '(signed-byte 32))))
182       '(%scalbn f ex)
183       '(scale-double-float f ex)))
184
185 ;;; What is the CROSS-FLOAT-INFINITY-KLUDGE?
186 ;;;
187 ;;; SBCL's own implementation of floating point supports floating
188 ;;; point infinities. Some of the old CMU CL :PROPAGATE-FLOAT-TYPE and
189 ;;; :PROPAGATE-FUN-TYPE code, like the DEFOPTIMIZERs below, uses this
190 ;;; floating point support. Thus, we have to avoid running it on the
191 ;;; cross-compilation host, since we're not guaranteed that the
192 ;;; cross-compilation host will support floating point infinities.
193 ;;;
194 ;;; If we wanted to live dangerously, we could conditionalize the code
195 ;;; with #+(OR SBCL SB-XC) instead. That way, if the cross-compilation
196 ;;; host happened to be SBCL, we'd be able to run the infinity-using
197 ;;; code. Pro:
198 ;;;   * SBCL itself gets built with more complete optimization.
199 ;;; Con:
200 ;;;   * You get a different SBCL depending on what your cross-compilation
201 ;;;     host is.
202 ;;; So far the pros and cons seem seem to be mostly academic, since
203 ;;; AFAIK (WHN 2001-08-28) the propagate-foo-type optimizations aren't
204 ;;; actually important in compiling SBCL itself. If this changes, then
205 ;;; we have to decide:
206 ;;;   * Go for simplicity, leaving things as they are.
207 ;;;   * Go for performance at the expense of conceptual clarity,
208 ;;;     using #+(OR SBCL SB-XC) and otherwise leaving the build
209 ;;;     process as is.
210 ;;;   * Go for performance at the expense of build time, using
211 ;;;     #+(OR SBCL SB-XC) and also making SBCL do not just
212 ;;;     make-host-1.sh and make-host-2.sh, but a third step
213 ;;;     make-host-3.sh where it builds itself under itself. (Such a
214 ;;;     3-step build process could also help with other things, e.g.
215 ;;;     using specialized arrays to represent debug information.)
216 ;;;   * Rewrite the code so that it doesn't depend on unportable
217 ;;;     floating point infinities.
218
219 ;;; optimizers for SCALE-FLOAT. If the float has bounds, new bounds
220 ;;; are computed for the result, if possible.
221 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
222 (progn
223
224 (defun scale-float-derive-type-aux (f ex same-arg)
225   (declare (ignore same-arg))
226   (flet ((scale-bound (x n)
227            ;; We need to be a bit careful here and catch any overflows
228            ;; that might occur. We can ignore underflows which become
229            ;; zeros.
230            (set-bound
231             (handler-case
232              (scale-float (type-bound-number x) n)
233              (floating-point-overflow ()
234                 nil))
235             (consp x))))
236     (when (and (numeric-type-p f) (numeric-type-p ex))
237       (let ((f-lo (numeric-type-low f))
238             (f-hi (numeric-type-high f))
239             (ex-lo (numeric-type-low ex))
240             (ex-hi (numeric-type-high ex))
241             (new-lo nil)
242             (new-hi nil))
243         (when f-hi
244           (if (< (float-sign (type-bound-number f-hi)) 0.0)
245               (when ex-lo
246                 (setf new-hi (scale-bound f-hi ex-lo)))
247               (when ex-hi
248                 (setf new-hi (scale-bound f-hi ex-hi)))))
249         (when f-lo
250           (if (< (float-sign (type-bound-number f-lo)) 0.0)
251               (when ex-hi
252                 (setf new-lo (scale-bound f-lo ex-hi)))
253               (when ex-lo
254                 (setf new-lo (scale-bound f-lo ex-lo)))))
255         (make-numeric-type :class (numeric-type-class f)
256                            :format (numeric-type-format f)
257                            :complexp :real
258                            :low new-lo
259                            :high new-hi)))))
260 (defoptimizer (scale-single-float derive-type) ((f ex))
261   (two-arg-derive-type f ex #'scale-float-derive-type-aux
262                        #'scale-single-float t))
263 (defoptimizer (scale-double-float derive-type) ((f ex))
264   (two-arg-derive-type f ex #'scale-float-derive-type-aux
265                        #'scale-double-float t))
266
267 ;;; DEFOPTIMIZERs for %SINGLE-FLOAT and %DOUBLE-FLOAT. This makes the
268 ;;; FLOAT function return the correct ranges if the input has some
269 ;;; defined range. Quite useful if we want to convert some type of
270 ;;; bounded integer into a float.
271 (macrolet
272     ((frob (fun type most-negative most-positive)
273        (let ((aux-name (symbolicate fun "-DERIVE-TYPE-AUX")))
274          `(progn
275             (defun ,aux-name (num)
276               ;; When converting a number to a float, the limits are
277               ;; the same.
278               (let* ((lo (bound-func (lambda (x)
279                                        (if (< x ,most-negative)
280                                            ,most-negative
281                                            (coerce x ',type)))
282                                      (numeric-type-low num)))
283                      (hi (bound-func (lambda (x)
284                                        (if (< ,most-positive x )
285                                            ,most-positive
286                                            (coerce x ',type)))
287                                      (numeric-type-high num))))
288                 (specifier-type `(,',type ,(or lo '*) ,(or hi '*)))))
289
290             (defoptimizer (,fun derive-type) ((num))
291               (handler-case
292                   (one-arg-derive-type num #',aux-name #',fun)
293                 (type-error ()
294                   nil)))))))
295   (frob %single-float single-float
296         most-negative-single-float most-positive-single-float)
297   (frob %double-float double-float
298         most-negative-double-float most-positive-double-float))
299 ) ; PROGN
300 \f
301 ;;;; float contagion
302
303 (defun safe-ctype-for-single-coercion-p (x)
304   ;; See comment in SAFE-SINGLE-COERCION-P -- this deals with the same
305   ;; problem, but in the context of evaluated and compiled (+ <int> <single>)
306   ;; giving different result if we fail to check for this.
307   (or (not (csubtypep x (specifier-type 'integer)))
308       (csubtypep x (specifier-type `(integer ,most-negative-exactly-single-float-fixnum
309                                              ,most-positive-exactly-single-float-fixnum)))))
310
311 ;;; Do some stuff to recognize when the loser is doing mixed float and
312 ;;; rational arithmetic, or different float types, and fix it up. If
313 ;;; we don't, he won't even get so much as an efficiency note.
314 (deftransform float-contagion-arg1 ((x y) * * :defun-only t :node node)
315   (if (or (not (types-equal-or-intersect (lvar-type y) (specifier-type 'single-float)))
316           (safe-ctype-for-single-coercion-p (lvar-type x)))
317       `(,(lvar-fun-name (basic-combination-fun node))
318          (float x y) y)
319       (give-up-ir1-transform)))
320 (deftransform float-contagion-arg2 ((x y) * * :defun-only t :node node)
321   (if (or (not (types-equal-or-intersect (lvar-type x) (specifier-type 'single-float)))
322           (safe-ctype-for-single-coercion-p (lvar-type y)))
323       `(,(lvar-fun-name (basic-combination-fun node))
324          x (float y x))
325       (give-up-ir1-transform)))
326
327 (dolist (x '(+ * / -))
328   (%deftransform x '(function (rational float) *) #'float-contagion-arg1)
329   (%deftransform x '(function (float rational) *) #'float-contagion-arg2))
330
331 (dolist (x '(= < > + * / -))
332   (%deftransform x '(function (single-float double-float) *)
333                  #'float-contagion-arg1)
334   (%deftransform x '(function (double-float single-float) *)
335                  #'float-contagion-arg2))
336
337 (macrolet ((def (type &rest args)
338              `(deftransform * ((x y) (,type (constant-arg (member ,@args))) *
339                                ;; Beware the SNaN!
340                                :policy (zerop float-accuracy))
341                 "optimize multiplication by one"
342                 (let ((y (lvar-value y)))
343                   (if (minusp y)
344                       '(%negate x)
345                       'x)))))
346   (def * single-float 1.0 -1.0)
347   (def * double-float 1.0d0 -1.0d0))
348
349 ;;; Return the reciprocal of X if it can be represented exactly, NIL otherwise.
350 (defun maybe-exact-reciprocal (x)
351   (unless (zerop x)
352     (multiple-value-bind (significand exponent sign)
353         ;; Signals an error for NaNs and infinities.
354         (handler-case (integer-decode-float x)
355           (error () (return-from maybe-exact-reciprocal nil)))
356       (let ((expected (/ sign significand (expt 2 exponent))))
357         (let ((reciprocal (/ 1 x)))
358           (multiple-value-bind (significand exponent sign) (integer-decode-float reciprocal)
359             (when (eql expected (* sign significand (expt 2 exponent)))
360               reciprocal)))))))
361
362 ;;; Replace constant division by multiplication with exact reciprocal,
363 ;;; if one exists.
364 (macrolet ((def (type)
365              `(deftransform / ((x y) (,type (constant-arg ,type)) *
366                                :node node)
367                 "convert to multiplication by reciprocal"
368                 (let ((n (lvar-value y)))
369                   (if (policy node (zerop float-accuracy))
370                       `(* x ,(/ n))
371                       (let ((r (maybe-exact-reciprocal n)))
372                         (if r
373                             `(* x ,r)
374                             (give-up-ir1-transform
375                              "~S does not have an exact reciprocal"
376                              n))))))))
377   (def single-float)
378   (def double-float))
379
380 ;;; Optimize addition and subsctraction of zero
381 (macrolet ((def (op type &rest args)
382              `(deftransform ,op ((x y) (,type (constant-arg (member ,@args))) *
383                                  ;; Beware the SNaN!
384                                  :policy (zerop float-accuracy))
385                 'x)))
386   ;; No signed zeros, thanks.
387   (def + single-float 0 0.0)
388   (def - single-float 0 0.0)
389   (def + double-float 0 0.0 0.0d0)
390   (def - double-float 0 0.0 0.0d0))
391
392 ;;; On most platforms (+ x x) is faster than (* x 2)
393 (macrolet ((def (type &rest args)
394              `(deftransform * ((x y) (,type (constant-arg (member ,@args))))
395                 '(+ x x))))
396   (def single-float 2 2.0)
397   (def double-float 2 2.0 2.0d0))
398
399 ;;; Prevent ZEROP, PLUSP, and MINUSP from losing horribly. We can't in
400 ;;; general float rational args to comparison, since Common Lisp
401 ;;; semantics says we are supposed to compare as rationals, but we can
402 ;;; do it for any rational that has a precise representation as a
403 ;;; float (such as 0).
404 (macrolet ((frob (op)
405              `(deftransform ,op ((x y) (float rational) *)
406                 "open-code FLOAT to RATIONAL comparison"
407                 (unless (constant-lvar-p y)
408                   (give-up-ir1-transform
409                    "The RATIONAL value isn't known at compile time."))
410                 (let ((val (lvar-value y)))
411                   (unless (eql (rational (float val)) val)
412                     (give-up-ir1-transform
413                      "~S doesn't have a precise float representation."
414                      val)))
415                 `(,',op x (float y x)))))
416   (frob <)
417   (frob >)
418   (frob =))
419 \f
420 ;;;; irrational derive-type methods
421
422 ;;; Derive the result to be float for argument types in the
423 ;;; appropriate domain.
424 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
425 (dolist (stuff '((asin (real -1.0 1.0))
426                  (acos (real -1.0 1.0))
427                  (acosh (real 1.0))
428                  (atanh (real -1.0 1.0))
429                  (sqrt (real 0.0))))
430   (destructuring-bind (name type) stuff
431     (let ((type (specifier-type type)))
432       (setf (fun-info-derive-type (fun-info-or-lose name))
433             (lambda (call)
434               (declare (type combination call))
435               (when (csubtypep (lvar-type
436                                 (first (combination-args call)))
437                                type)
438                 (specifier-type 'float)))))))
439
440 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
441 (defoptimizer (log derive-type) ((x &optional y))
442   (when (and (csubtypep (lvar-type x)
443                         (specifier-type '(real 0.0)))
444              (or (null y)
445                  (csubtypep (lvar-type y)
446                             (specifier-type '(real 0.0)))))
447     (specifier-type 'float)))
448 \f
449 ;;;; irrational transforms
450
451 (defknown (%tan %sinh %asinh %atanh %log %logb %log10 %tan-quick)
452           (double-float) double-float
453   (movable foldable flushable))
454
455 (defknown (%sin %cos %tanh %sin-quick %cos-quick)
456   (double-float) (double-float -1.0d0 1.0d0)
457   (movable foldable flushable))
458
459 (defknown (%asin %atan)
460   (double-float)
461   (double-float #.(coerce (- (/ pi 2)) 'double-float)
462                 #.(coerce (/ pi 2) 'double-float))
463   (movable foldable flushable))
464
465 (defknown (%acos)
466   (double-float) (double-float 0.0d0 #.(coerce pi 'double-float))
467   (movable foldable flushable))
468
469 (defknown (%cosh)
470   (double-float) (double-float 1.0d0)
471   (movable foldable flushable))
472
473 (defknown (%acosh %exp %sqrt)
474   (double-float) (double-float 0.0d0)
475   (movable foldable flushable))
476
477 (defknown %expm1
478   (double-float) (double-float -1d0)
479   (movable foldable flushable))
480
481 (defknown (%hypot)
482   (double-float double-float) (double-float 0d0)
483   (movable foldable flushable))
484
485 (defknown (%pow)
486   (double-float double-float) double-float
487   (movable foldable flushable))
488
489 (defknown (%atan2)
490   (double-float double-float)
491   (double-float #.(coerce (- pi) 'double-float)
492                 #.(coerce pi 'double-float))
493   (movable foldable flushable))
494
495 (defknown (%scalb)
496   (double-float double-float) double-float
497   (movable foldable flushable))
498
499 (defknown (%scalbn)
500   (double-float (signed-byte 32)) double-float
501   (movable foldable flushable))
502
503 (defknown (%log1p)
504   (double-float) double-float
505   (movable foldable flushable))
506
507 (macrolet ((def (name prim rtype)
508              `(progn
509                (deftransform ,name ((x) (single-float) ,rtype)
510                  `(coerce (,',prim (coerce x 'double-float)) 'single-float))
511                (deftransform ,name ((x) (double-float) ,rtype)
512                  `(,',prim x)))))
513   (def exp %exp *)
514   (def log %log float)
515   (def sqrt %sqrt float)
516   (def asin %asin float)
517   (def acos %acos float)
518   (def atan %atan *)
519   (def sinh %sinh *)
520   (def cosh %cosh *)
521   (def tanh %tanh *)
522   (def asinh %asinh *)
523   (def acosh %acosh float)
524   (def atanh %atanh float))
525
526 ;;; The argument range is limited on the x86 FP trig. functions. A
527 ;;; post-test can detect a failure (and load a suitable result), but
528 ;;; this test is avoided if possible.
529 (macrolet ((def (name prim prim-quick)
530              (declare (ignorable prim-quick))
531              `(progn
532                 (deftransform ,name ((x) (single-float) *)
533                   #!+x86 (cond ((csubtypep (lvar-type x)
534                                            (specifier-type '(single-float
535                                                              (#.(- (expt 2f0 64)))
536                                                              (#.(expt 2f0 64)))))
537                                 `(coerce (,',prim-quick (coerce x 'double-float))
538                                   'single-float))
539                                (t
540                                 (compiler-notify
541                                  "unable to avoid inline argument range check~@
542                                   because the argument range (~S) was not within 2^64"
543                                  (type-specifier (lvar-type x)))
544                                 `(coerce (,',prim (coerce x 'double-float)) 'single-float)))
545                   #!-x86 `(coerce (,',prim (coerce x 'double-float)) 'single-float))
546                (deftransform ,name ((x) (double-float) *)
547                  #!+x86 (cond ((csubtypep (lvar-type x)
548                                           (specifier-type '(double-float
549                                                             (#.(- (expt 2d0 64)))
550                                                             (#.(expt 2d0 64)))))
551                                `(,',prim-quick x))
552                               (t
553                                (compiler-notify
554                                 "unable to avoid inline argument range check~@
555                                  because the argument range (~S) was not within 2^64"
556                                 (type-specifier (lvar-type x)))
557                                `(,',prim x)))
558                  #!-x86 `(,',prim x)))))
559   (def sin %sin %sin-quick)
560   (def cos %cos %cos-quick)
561   (def tan %tan %tan-quick))
562
563 (deftransform atan ((x y) (single-float single-float) *)
564   `(coerce (%atan2 (coerce x 'double-float) (coerce y 'double-float))
565     'single-float))
566 (deftransform atan ((x y) (double-float double-float) *)
567   `(%atan2 x y))
568
569 (deftransform expt ((x y) ((single-float 0f0) single-float) *)
570   `(coerce (%pow (coerce x 'double-float) (coerce y 'double-float))
571     'single-float))
572 (deftransform expt ((x y) ((double-float 0d0) double-float) *)
573   `(%pow x y))
574 (deftransform expt ((x y) ((single-float 0f0) (signed-byte 32)) *)
575   `(coerce (%pow (coerce x 'double-float) (coerce y 'double-float))
576     'single-float))
577 (deftransform expt ((x y) ((double-float 0d0) (signed-byte 32)) *)
578   `(%pow x (coerce y 'double-float)))
579
580 ;;; ANSI says log with base zero returns zero.
581 (deftransform log ((x y) (float float) float)
582   '(if (zerop y) y (/ (log x) (log y))))
583 \f
584 ;;; Handle some simple transformations.
585
586 (deftransform abs ((x) ((complex double-float)) double-float)
587   '(%hypot (realpart x) (imagpart x)))
588
589 (deftransform abs ((x) ((complex single-float)) single-float)
590   '(coerce (%hypot (coerce (realpart x) 'double-float)
591                    (coerce (imagpart x) 'double-float))
592           'single-float))
593
594 (deftransform phase ((x) ((complex double-float)) double-float)
595   '(%atan2 (imagpart x) (realpart x)))
596
597 (deftransform phase ((x) ((complex single-float)) single-float)
598   '(coerce (%atan2 (coerce (imagpart x) 'double-float)
599                    (coerce (realpart x) 'double-float))
600           'single-float))
601
602 (deftransform phase ((x) ((float)) float)
603   '(if (minusp (float-sign x))
604        (float pi x)
605        (float 0 x)))
606
607 ;;; The number is of type REAL.
608 (defun numeric-type-real-p (type)
609   (and (numeric-type-p type)
610        (eq (numeric-type-complexp type) :real)))
611
612 ;;; Coerce a numeric type bound to the given type while handling
613 ;;; exclusive bounds.
614 (defun coerce-numeric-bound (bound type)
615   (when bound
616     (if (consp bound)
617         (list (coerce (car bound) type))
618         (coerce bound type))))
619
620 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
621 (progn
622
623 ;;;; optimizers for elementary functions
624 ;;;;
625 ;;;; These optimizers compute the output range of the elementary
626 ;;;; function, based on the domain of the input.
627
628 ;;; Generate a specifier for a complex type specialized to the same
629 ;;; type as the argument.
630 (defun complex-float-type (arg)
631   (declare (type numeric-type arg))
632   (let* ((format (case (numeric-type-class arg)
633                    ((integer rational) 'single-float)
634                    (t (numeric-type-format arg))))
635          (float-type (or format 'float)))
636     (specifier-type `(complex ,float-type))))
637
638 ;;; Compute a specifier like '(OR FLOAT (COMPLEX FLOAT)), except float
639 ;;; should be the right kind of float. Allow bounds for the float
640 ;;; part too.
641 (defun float-or-complex-float-type (arg &optional lo hi)
642   (declare (type numeric-type arg))
643   (let* ((format (case (numeric-type-class arg)
644                    ((integer rational) 'single-float)
645                    (t (numeric-type-format arg))))
646          (float-type (or format 'float))
647          (lo (coerce-numeric-bound lo float-type))
648          (hi (coerce-numeric-bound hi float-type)))
649     (specifier-type `(or (,float-type ,(or lo '*) ,(or hi '*))
650                          (complex ,float-type)))))
651
652 ) ; PROGN
653
654 (eval-when (:compile-toplevel :execute)
655   ;; So the problem with this hack is that it's actually broken.  If
656   ;; the host does not have long floats, then setting *R-D-F-F* to
657   ;; LONG-FLOAT doesn't actually buy us anything.  FIXME.
658   (setf *read-default-float-format*
659         #!+long-float 'long-float #!-long-float 'double-float))
660 ;;; Test whether the numeric-type ARG is within in domain specified by
661 ;;; DOMAIN-LOW and DOMAIN-HIGH, consider negative and positive zero to
662 ;;; be distinct.
663 #-sb-xc-host  ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
664 (defun domain-subtypep (arg domain-low domain-high)
665   (declare (type numeric-type arg)
666            (type (or real null) domain-low domain-high))
667   (let* ((arg-lo (numeric-type-low arg))
668          (arg-lo-val (type-bound-number arg-lo))
669          (arg-hi (numeric-type-high arg))
670          (arg-hi-val (type-bound-number arg-hi)))
671     ;; Check that the ARG bounds are correctly canonicalized.
672     (when (and arg-lo (floatp arg-lo-val) (zerop arg-lo-val) (consp arg-lo)
673                (minusp (float-sign arg-lo-val)))
674       (compiler-notify "float zero bound ~S not correctly canonicalized?" arg-lo)
675       (setq arg-lo 0e0 arg-lo-val arg-lo))
676     (when (and arg-hi (zerop arg-hi-val) (floatp arg-hi-val) (consp arg-hi)
677                (plusp (float-sign arg-hi-val)))
678       (compiler-notify "float zero bound ~S not correctly canonicalized?" arg-hi)
679       (setq arg-hi (ecase *read-default-float-format*
680                      (double-float (load-time-value (make-unportable-float :double-float-negative-zero)))
681                      #!+long-float
682                      (long-float (load-time-value (make-unportable-float :long-float-negative-zero))))
683             arg-hi-val arg-hi))
684     (flet ((fp-neg-zero-p (f)           ; Is F -0.0?
685              (and (floatp f) (zerop f) (minusp (float-sign f))))
686            (fp-pos-zero-p (f)           ; Is F +0.0?
687              (and (floatp f) (zerop f) (plusp (float-sign f)))))
688       (and (or (null domain-low)
689                (and arg-lo (>= arg-lo-val domain-low)
690                     (not (and (fp-pos-zero-p domain-low)
691                               (fp-neg-zero-p arg-lo)))))
692            (or (null domain-high)
693                (and arg-hi (<= arg-hi-val domain-high)
694                     (not (and (fp-neg-zero-p domain-high)
695                               (fp-pos-zero-p arg-hi)))))))))
696 (eval-when (:compile-toplevel :execute)
697   (setf *read-default-float-format* 'single-float))
698
699 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
700 (progn
701
702 ;;; Handle monotonic functions of a single variable whose domain is
703 ;;; possibly part of the real line. ARG is the variable, FUN is the
704 ;;; function, and DOMAIN is a specifier that gives the (real) domain
705 ;;; of the function. If ARG is a subset of the DOMAIN, we compute the
706 ;;; bounds directly. Otherwise, we compute the bounds for the
707 ;;; intersection between ARG and DOMAIN, and then append a complex
708 ;;; result, which occurs for the parts of ARG not in the DOMAIN.
709 ;;;
710 ;;; Negative and positive zero are considered distinct within
711 ;;; DOMAIN-LOW and DOMAIN-HIGH.
712 ;;;
713 ;;; DEFAULT-LOW and DEFAULT-HIGH are the lower and upper bounds if we
714 ;;; can't compute the bounds using FUN.
715 (defun elfun-derive-type-simple (arg fun domain-low domain-high
716                                      default-low default-high
717                                      &optional (increasingp t))
718   (declare (type (or null real) domain-low domain-high))
719   (etypecase arg
720     (numeric-type
721      (cond ((eq (numeric-type-complexp arg) :complex)
722             (complex-float-type arg))
723            ((numeric-type-real-p arg)
724             ;; The argument is real, so let's find the intersection
725             ;; between the argument and the domain of the function.
726             ;; We compute the bounds on the intersection, and for
727             ;; everything else, we return a complex number of the
728             ;; appropriate type.
729             (multiple-value-bind (intersection difference)
730                 (interval-intersection/difference (numeric-type->interval arg)
731                                                   (make-interval
732                                                    :low domain-low
733                                                    :high domain-high))
734               (cond
735                 (intersection
736                  ;; Process the intersection.
737                  (let* ((low (interval-low intersection))
738                         (high (interval-high intersection))
739                         (res-lo (or (bound-func fun (if increasingp low high))
740                                     default-low))
741                         (res-hi (or (bound-func fun (if increasingp high low))
742                                     default-high))
743                         (format (case (numeric-type-class arg)
744                                   ((integer rational) 'single-float)
745                                   (t (numeric-type-format arg))))
746                         (bound-type (or format 'float))
747                         (result-type
748                          (make-numeric-type
749                           :class 'float
750                           :format format
751                           :low (coerce-numeric-bound res-lo bound-type)
752                           :high (coerce-numeric-bound res-hi bound-type))))
753                    ;; If the ARG is a subset of the domain, we don't
754                    ;; have to worry about the difference, because that
755                    ;; can't occur.
756                    (if (or (null difference)
757                            ;; Check whether the arg is within the domain.
758                            (domain-subtypep arg domain-low domain-high))
759                        result-type
760                        (list result-type
761                              (specifier-type `(complex ,bound-type))))))
762                 (t
763                  ;; No intersection so the result must be purely complex.
764                  (complex-float-type arg)))))
765            (t
766             (float-or-complex-float-type arg default-low default-high))))))
767
768 (macrolet
769     ((frob (name domain-low domain-high def-low-bnd def-high-bnd
770                  &key (increasingp t))
771        (let ((num (gensym)))
772          `(defoptimizer (,name derive-type) ((,num))
773            (one-arg-derive-type
774             ,num
775             (lambda (arg)
776               (elfun-derive-type-simple arg #',name
777                                         ,domain-low ,domain-high
778                                         ,def-low-bnd ,def-high-bnd
779                                         ,increasingp))
780             #',name)))))
781   ;; These functions are easy because they are defined for the whole
782   ;; real line.
783   (frob exp nil nil 0 nil)
784   (frob sinh nil nil nil nil)
785   (frob tanh nil nil -1 1)
786   (frob asinh nil nil nil nil)
787
788   ;; These functions are only defined for part of the real line. The
789   ;; condition selects the desired part of the line.
790   (frob asin -1d0 1d0 (- (/ pi 2)) (/ pi 2))
791   ;; Acos is monotonic decreasing, so we need to swap the function
792   ;; values at the lower and upper bounds of the input domain.
793   (frob acos -1d0 1d0 0 pi :increasingp nil)
794   (frob acosh 1d0 nil nil nil)
795   (frob atanh -1d0 1d0 -1 1)
796   ;; Kahan says that (sqrt -0.0) is -0.0, so use a specifier that
797   ;; includes -0.0.
798   (frob sqrt (load-time-value (make-unportable-float :double-float-negative-zero)) nil 0 nil))
799
800 ;;; Compute bounds for (expt x y). This should be easy since (expt x
801 ;;; y) = (exp (* y (log x))). However, computations done this way
802 ;;; have too much roundoff. Thus we have to do it the hard way.
803 (defun safe-expt (x y)
804   (handler-case
805       (when (< (abs y) 10000)
806         (expt x y))
807     (error ()
808       nil)))
809
810 ;;; Handle the case when x >= 1.
811 (defun interval-expt-> (x y)
812   (case (sb!c::interval-range-info y 0d0)
813     (+
814      ;; Y is positive and log X >= 0. The range of exp(y * log(x)) is
815      ;; obviously non-negative. We just have to be careful for
816      ;; infinite bounds (given by nil).
817      (let ((lo (safe-expt (type-bound-number (sb!c::interval-low x))
818                           (type-bound-number (sb!c::interval-low y))))
819            (hi (safe-expt (type-bound-number (sb!c::interval-high x))
820                           (type-bound-number (sb!c::interval-high y)))))
821        (list (sb!c::make-interval :low (or lo 1) :high hi))))
822     (-
823      ;; Y is negative and log x >= 0. The range of exp(y * log(x)) is
824      ;; obviously [0, 1]. However, underflow (nil) means 0 is the
825      ;; result.
826      (let ((lo (safe-expt (type-bound-number (sb!c::interval-high x))
827                           (type-bound-number (sb!c::interval-low y))))
828            (hi (safe-expt (type-bound-number (sb!c::interval-low x))
829                           (type-bound-number (sb!c::interval-high y)))))
830        (list (sb!c::make-interval :low (or lo 0) :high (or hi 1)))))
831     (t
832      ;; Split the interval in half.
833      (destructuring-bind (y- y+)
834          (sb!c::interval-split 0 y t)
835        (list (interval-expt-> x y-)
836              (interval-expt-> x y+))))))
837
838 ;;; Handle the case when x <= 1
839 (defun interval-expt-< (x y)
840   (case (sb!c::interval-range-info x 0d0)
841     (+
842      ;; The case of 0 <= x <= 1 is easy
843      (case (sb!c::interval-range-info y)
844        (+
845         ;; Y is positive and log X <= 0. The range of exp(y * log(x)) is
846         ;; obviously [0, 1]. We just have to be careful for infinite bounds
847         ;; (given by nil).
848         (let ((lo (safe-expt (type-bound-number (sb!c::interval-low x))
849                              (type-bound-number (sb!c::interval-high y))))
850               (hi (safe-expt (type-bound-number (sb!c::interval-high x))
851                              (type-bound-number (sb!c::interval-low y)))))
852           (list (sb!c::make-interval :low (or lo 0) :high (or hi 1)))))
853        (-
854         ;; Y is negative and log x <= 0. The range of exp(y * log(x)) is
855         ;; obviously [1, inf].
856         (let ((hi (safe-expt (type-bound-number (sb!c::interval-low x))
857                              (type-bound-number (sb!c::interval-low y))))
858               (lo (safe-expt (type-bound-number (sb!c::interval-high x))
859                              (type-bound-number (sb!c::interval-high y)))))
860           (list (sb!c::make-interval :low (or lo 1) :high hi))))
861        (t
862         ;; Split the interval in half
863         (destructuring-bind (y- y+)
864             (sb!c::interval-split 0 y t)
865           (list (interval-expt-< x y-)
866                 (interval-expt-< x y+))))))
867     (-
868      ;; The case where x <= 0. Y MUST be an INTEGER for this to work!
869      ;; The calling function must insure this! For now we'll just
870      ;; return the appropriate unbounded float type.
871      (list (sb!c::make-interval :low nil :high nil)))
872     (t
873      (destructuring-bind (neg pos)
874          (interval-split 0 x t t)
875        (list (interval-expt-< neg y)
876              (interval-expt-< pos y))))))
877
878 ;;; Compute bounds for (expt x y).
879 (defun interval-expt (x y)
880   (case (interval-range-info x 1)
881     (+
882      ;; X >= 1
883          (interval-expt-> x y))
884     (-
885      ;; X <= 1
886      (interval-expt-< x y))
887     (t
888      (destructuring-bind (left right)
889          (interval-split 1 x t t)
890        (list (interval-expt left y)
891              (interval-expt right y))))))
892
893 (defun fixup-interval-expt (bnd x-int y-int x-type y-type)
894   (declare (ignore x-int))
895   ;; Figure out what the return type should be, given the argument
896   ;; types and bounds and the result type and bounds.
897   (cond ((csubtypep x-type (specifier-type 'integer))
898          ;; an integer to some power
899          (case (numeric-type-class y-type)
900            (integer
901             ;; Positive integer to an integer power is either an
902             ;; integer or a rational.
903             (let ((lo (or (interval-low bnd) '*))
904                   (hi (or (interval-high bnd) '*)))
905               (if (and (interval-low y-int)
906                        (>= (type-bound-number (interval-low y-int)) 0))
907                   (specifier-type `(integer ,lo ,hi))
908                   (specifier-type `(rational ,lo ,hi)))))
909            (rational
910             ;; Positive integer to rational power is either a rational
911             ;; or a single-float.
912             (let* ((lo (interval-low bnd))
913                    (hi (interval-high bnd))
914                    (int-lo (if lo
915                                (floor (type-bound-number lo))
916                                '*))
917                    (int-hi (if hi
918                                (ceiling (type-bound-number hi))
919                                '*))
920                    (f-lo (if lo
921                              (bound-func #'float lo)
922                              '*))
923                    (f-hi (if hi
924                              (bound-func #'float hi)
925                              '*)))
926               (specifier-type `(or (rational ,int-lo ,int-hi)
927                                 (single-float ,f-lo, f-hi)))))
928            (float
929             ;; A positive integer to a float power is a float.
930             (modified-numeric-type y-type
931                                    :low (interval-low bnd)
932                                    :high (interval-high bnd)))
933            (t
934             ;; A positive integer to a number is a number (for now).
935             (specifier-type 'number))))
936         ((csubtypep x-type (specifier-type 'rational))
937          ;; a rational to some power
938          (case (numeric-type-class y-type)
939            (integer
940             ;; A positive rational to an integer power is always a rational.
941             (specifier-type `(rational ,(or (interval-low bnd) '*)
942                                        ,(or (interval-high bnd) '*))))
943            (rational
944             ;; A positive rational to rational power is either a rational
945             ;; or a single-float.
946             (let* ((lo (interval-low bnd))
947                    (hi (interval-high bnd))
948                    (int-lo (if lo
949                                (floor (type-bound-number lo))
950                                '*))
951                    (int-hi (if hi
952                                (ceiling (type-bound-number hi))
953                                '*))
954                    (f-lo (if lo
955                              (bound-func #'float lo)
956                              '*))
957                    (f-hi (if hi
958                              (bound-func #'float hi)
959                              '*)))
960               (specifier-type `(or (rational ,int-lo ,int-hi)
961                                 (single-float ,f-lo, f-hi)))))
962            (float
963             ;; A positive rational to a float power is a float.
964             (modified-numeric-type y-type
965                                    :low (interval-low bnd)
966                                    :high (interval-high bnd)))
967            (t
968             ;; A positive rational to a number is a number (for now).
969             (specifier-type 'number))))
970         ((csubtypep x-type (specifier-type 'float))
971          ;; a float to some power
972          (case (numeric-type-class y-type)
973            ((or integer rational)
974             ;; A positive float to an integer or rational power is
975             ;; always a float.
976             (make-numeric-type
977              :class 'float
978              :format (numeric-type-format x-type)
979              :low (interval-low bnd)
980              :high (interval-high bnd)))
981            (float
982             ;; A positive float to a float power is a float of the
983             ;; higher type.
984             (make-numeric-type
985              :class 'float
986              :format (float-format-max (numeric-type-format x-type)
987                                        (numeric-type-format y-type))
988              :low (interval-low bnd)
989              :high (interval-high bnd)))
990            (t
991             ;; A positive float to a number is a number (for now)
992             (specifier-type 'number))))
993         (t
994          ;; A number to some power is a number.
995          (specifier-type 'number))))
996
997 (defun merged-interval-expt (x y)
998   (let* ((x-int (numeric-type->interval x))
999          (y-int (numeric-type->interval y)))
1000     (mapcar (lambda (type)
1001               (fixup-interval-expt type x-int y-int x y))
1002             (flatten-list (interval-expt x-int y-int)))))
1003
1004 (defun expt-derive-type-aux (x y same-arg)
1005   (declare (ignore same-arg))
1006   (cond ((or (not (numeric-type-real-p x))
1007              (not (numeric-type-real-p y)))
1008          ;; Use numeric contagion if either is not real.
1009          (numeric-contagion x y))
1010         ((csubtypep y (specifier-type 'integer))
1011          ;; A real raised to an integer power is well-defined.
1012          (merged-interval-expt x y))
1013         ;; A real raised to a non-integral power can be a float or a
1014         ;; complex number.
1015         ((or (csubtypep x (specifier-type '(rational 0)))
1016              (csubtypep x (specifier-type '(float (0d0)))))
1017          ;; But a positive real to any power is well-defined.
1018          (merged-interval-expt x y))
1019         ((and (csubtypep x (specifier-type 'rational))
1020               (csubtypep x (specifier-type 'rational)))
1021          ;; A rational to the power of a rational could be a rational
1022          ;; or a possibly-complex single float
1023          (specifier-type '(or rational single-float (complex single-float))))
1024         (t
1025          ;; a real to some power. The result could be a real or a
1026          ;; complex.
1027          (float-or-complex-float-type (numeric-contagion x y)))))
1028
1029 (defoptimizer (expt derive-type) ((x y))
1030   (two-arg-derive-type x y #'expt-derive-type-aux #'expt))
1031
1032 ;;; Note we must assume that a type including 0.0 may also include
1033 ;;; -0.0 and thus the result may be complex -infinity + i*pi.
1034 (defun log-derive-type-aux-1 (x)
1035   (elfun-derive-type-simple x #'log 0d0 nil nil nil))
1036
1037 (defun log-derive-type-aux-2 (x y same-arg)
1038   (let ((log-x (log-derive-type-aux-1 x))
1039         (log-y (log-derive-type-aux-1 y))
1040         (accumulated-list nil))
1041     ;; LOG-X or LOG-Y might be union types. We need to run through
1042     ;; the union types ourselves because /-DERIVE-TYPE-AUX doesn't.
1043     (dolist (x-type (prepare-arg-for-derive-type log-x))
1044       (dolist (y-type (prepare-arg-for-derive-type log-y))
1045         (push (/-derive-type-aux x-type y-type same-arg) accumulated-list)))
1046     (apply #'type-union (flatten-list accumulated-list))))
1047
1048 (defoptimizer (log derive-type) ((x &optional y))
1049   (if y
1050       (two-arg-derive-type x y #'log-derive-type-aux-2 #'log)
1051       (one-arg-derive-type x #'log-derive-type-aux-1 #'log)))
1052
1053 (defun atan-derive-type-aux-1 (y)
1054   (elfun-derive-type-simple y #'atan nil nil (- (/ pi 2)) (/ pi 2)))
1055
1056 (defun atan-derive-type-aux-2 (y x same-arg)
1057   (declare (ignore same-arg))
1058   ;; The hard case with two args. We just return the max bounds.
1059   (let ((result-type (numeric-contagion y x)))
1060     (cond ((and (numeric-type-real-p x)
1061                 (numeric-type-real-p y))
1062            (let* (;; FIXME: This expression for FORMAT seems to
1063                   ;; appear multiple times, and should be factored out.
1064                   (format (case (numeric-type-class result-type)
1065                             ((integer rational) 'single-float)
1066                             (t (numeric-type-format result-type))))
1067                   (bound-format (or format 'float)))
1068              (make-numeric-type :class 'float
1069                                 :format format
1070                                 :complexp :real
1071                                 :low (coerce (- pi) bound-format)
1072                                 :high (coerce pi bound-format))))
1073           (t
1074            ;; The result is a float or a complex number
1075            (float-or-complex-float-type result-type)))))
1076
1077 (defoptimizer (atan derive-type) ((y &optional x))
1078   (if x
1079       (two-arg-derive-type y x #'atan-derive-type-aux-2 #'atan)
1080       (one-arg-derive-type y #'atan-derive-type-aux-1 #'atan)))
1081
1082 (defun cosh-derive-type-aux (x)
1083   ;; We note that cosh x = cosh |x| for all real x.
1084   (elfun-derive-type-simple
1085    (if (numeric-type-real-p x)
1086        (abs-derive-type-aux x)
1087        x)
1088    #'cosh nil nil 0 nil))
1089
1090 (defoptimizer (cosh derive-type) ((num))
1091   (one-arg-derive-type num #'cosh-derive-type-aux #'cosh))
1092
1093 (defun phase-derive-type-aux (arg)
1094   (let* ((format (case (numeric-type-class arg)
1095                    ((integer rational) 'single-float)
1096                    (t (numeric-type-format arg))))
1097          (bound-type (or format 'float)))
1098     (cond ((numeric-type-real-p arg)
1099            (case (interval-range-info (numeric-type->interval arg) 0.0)
1100              (+
1101               ;; The number is positive, so the phase is 0.
1102               (make-numeric-type :class 'float
1103                                  :format format
1104                                  :complexp :real
1105                                  :low (coerce 0 bound-type)
1106                                  :high (coerce 0 bound-type)))
1107              (-
1108               ;; The number is always negative, so the phase is pi.
1109               (make-numeric-type :class 'float
1110                                  :format format
1111                                  :complexp :real
1112                                  :low (coerce pi bound-type)
1113                                  :high (coerce pi bound-type)))
1114              (t
1115               ;; We can't tell. The result is 0 or pi. Use a union
1116               ;; type for this.
1117               (list
1118                (make-numeric-type :class 'float
1119                                   :format format
1120                                   :complexp :real
1121                                   :low (coerce 0 bound-type)
1122                                   :high (coerce 0 bound-type))
1123                (make-numeric-type :class 'float
1124                                   :format format
1125                                   :complexp :real
1126                                   :low (coerce pi bound-type)
1127                                   :high (coerce pi bound-type))))))
1128           (t
1129            ;; We have a complex number. The answer is the range -pi
1130            ;; to pi. (-pi is included because we have -0.)
1131            (make-numeric-type :class 'float
1132                               :format format
1133                               :complexp :real
1134                               :low (coerce (- pi) bound-type)
1135                               :high (coerce pi bound-type))))))
1136
1137 (defoptimizer (phase derive-type) ((num))
1138   (one-arg-derive-type num #'phase-derive-type-aux #'phase))
1139
1140 ) ; PROGN
1141
1142 (deftransform realpart ((x) ((complex rational)) *)
1143   '(sb!kernel:%realpart x))
1144 (deftransform imagpart ((x) ((complex rational)) *)
1145   '(sb!kernel:%imagpart x))
1146
1147 ;;; Make REALPART and IMAGPART return the appropriate types. This
1148 ;;; should help a lot in optimized code.
1149 (defun realpart-derive-type-aux (type)
1150   (let ((class (numeric-type-class type))
1151         (format (numeric-type-format type)))
1152     (cond ((numeric-type-real-p type)
1153            ;; The realpart of a real has the same type and range as
1154            ;; the input.
1155            (make-numeric-type :class class
1156                               :format format
1157                               :complexp :real
1158                               :low (numeric-type-low type)
1159                               :high (numeric-type-high type)))
1160           (t
1161            ;; We have a complex number. The result has the same type
1162            ;; as the real part, except that it's real, not complex,
1163            ;; obviously.
1164            (make-numeric-type :class class
1165                               :format format
1166                               :complexp :real
1167                               :low (numeric-type-low type)
1168                               :high (numeric-type-high type))))))
1169 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1170 (defoptimizer (realpart derive-type) ((num))
1171   (one-arg-derive-type num #'realpart-derive-type-aux #'realpart))
1172 (defun imagpart-derive-type-aux (type)
1173   (let ((class (numeric-type-class type))
1174         (format (numeric-type-format type)))
1175     (cond ((numeric-type-real-p type)
1176            ;; The imagpart of a real has the same type as the input,
1177            ;; except that it's zero.
1178            (let ((bound-format (or format class 'real)))
1179              (make-numeric-type :class class
1180                                 :format format
1181                                 :complexp :real
1182                                 :low (coerce 0 bound-format)
1183                                 :high (coerce 0 bound-format))))
1184           (t
1185            ;; We have a complex number. The result has the same type as
1186            ;; the imaginary part, except that it's real, not complex,
1187            ;; obviously.
1188            (make-numeric-type :class class
1189                               :format format
1190                               :complexp :real
1191                               :low (numeric-type-low type)
1192                               :high (numeric-type-high type))))))
1193 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1194 (defoptimizer (imagpart derive-type) ((num))
1195   (one-arg-derive-type num #'imagpart-derive-type-aux #'imagpart))
1196
1197 (defun complex-derive-type-aux-1 (re-type)
1198   (if (numeric-type-p re-type)
1199       (make-numeric-type :class (numeric-type-class re-type)
1200                          :format (numeric-type-format re-type)
1201                          :complexp (if (csubtypep re-type
1202                                                   (specifier-type 'rational))
1203                                        :real
1204                                        :complex)
1205                          :low (numeric-type-low re-type)
1206                          :high (numeric-type-high re-type))
1207       (specifier-type 'complex)))
1208
1209 (defun complex-derive-type-aux-2 (re-type im-type same-arg)
1210   (declare (ignore same-arg))
1211   (if (and (numeric-type-p re-type)
1212            (numeric-type-p im-type))
1213       ;; Need to check to make sure numeric-contagion returns the
1214       ;; right type for what we want here.
1215
1216       ;; Also, what about rational canonicalization, like (complex 5 0)
1217       ;; is 5?  So, if the result must be complex, we make it so.
1218       ;; If the result might be complex, which happens only if the
1219       ;; arguments are rational, we make it a union type of (or
1220       ;; rational (complex rational)).
1221       (let* ((element-type (numeric-contagion re-type im-type))
1222              (rat-result-p (csubtypep element-type
1223                                       (specifier-type 'rational))))
1224         (if rat-result-p
1225             (type-union element-type
1226                         (specifier-type
1227                          `(complex ,(numeric-type-class element-type))))
1228             (make-numeric-type :class (numeric-type-class element-type)
1229                                :format (numeric-type-format element-type)
1230                                :complexp (if rat-result-p
1231                                              :real
1232                                              :complex))))
1233       (specifier-type 'complex)))
1234
1235 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1236 (defoptimizer (complex derive-type) ((re &optional im))
1237   (if im
1238       (two-arg-derive-type re im #'complex-derive-type-aux-2 #'complex)
1239       (one-arg-derive-type re #'complex-derive-type-aux-1 #'complex)))
1240
1241 ;;; Define some transforms for complex operations. We do this in lieu
1242 ;;; of complex operation VOPs.
1243 (macrolet ((frob (type)
1244              `(progn
1245                 (deftransform complex ((r) (,type))
1246                   '(complex r ,(coerce 0 type)))
1247                 (deftransform complex ((r i) (,type (and real (not ,type))))
1248                   '(complex r (truly-the ,type (coerce i ',type))))
1249                 (deftransform complex ((r i) ((and real (not ,type)) ,type))
1250                   '(complex (truly-the ,type (coerce r ',type)) i))
1251                ;; negation
1252                 #!-complex-float-vops
1253                (deftransform %negate ((z) ((complex ,type)) *)
1254                  '(complex (%negate (realpart z)) (%negate (imagpart z))))
1255                ;; complex addition and subtraction
1256                #!-complex-float-vops
1257                (deftransform + ((w z) ((complex ,type) (complex ,type)) *)
1258                  '(complex (+ (realpart w) (realpart z))
1259                            (+ (imagpart w) (imagpart z))))
1260                #!-complex-float-vops
1261                (deftransform - ((w z) ((complex ,type) (complex ,type)) *)
1262                  '(complex (- (realpart w) (realpart z))
1263                            (- (imagpart w) (imagpart z))))
1264                ;; Add and subtract a complex and a real.
1265                #!-complex-float-vops
1266                (deftransform + ((w z) ((complex ,type) real) *)
1267                  `(complex (+ (realpart w) z)
1268                            (+ (imagpart w) ,(coerce 0 ',type))))
1269                #!-complex-float-vops
1270                (deftransform + ((z w) (real (complex ,type)) *)
1271                  `(complex (+ (realpart w) z)
1272                            (+ (imagpart w) ,(coerce 0 ',type))))
1273                ;; Add and subtract a real and a complex number.
1274                #!-complex-float-vops
1275                (deftransform - ((w z) ((complex ,type) real) *)
1276                  `(complex (- (realpart w) z)
1277                            (- (imagpart w) ,(coerce 0 ',type))))
1278                #!-complex-float-vops
1279                (deftransform - ((z w) (real (complex ,type)) *)
1280                  `(complex (- z (realpart w))
1281                            (- ,(coerce 0 ',type) (imagpart w))))
1282                ;; Multiply and divide two complex numbers.
1283                #!-complex-float-vops
1284                (deftransform * ((x y) ((complex ,type) (complex ,type)) *)
1285                  '(let* ((rx (realpart x))
1286                          (ix (imagpart x))
1287                          (ry (realpart y))
1288                          (iy (imagpart y)))
1289                     (complex (- (* rx ry) (* ix iy))
1290                              (+ (* rx iy) (* ix ry)))))
1291                (deftransform / ((x y) ((complex ,type) (complex ,type)) *)
1292                  #!-complex-float-vops
1293                  '(let* ((rx (realpart x))
1294                          (ix (imagpart x))
1295                          (ry (realpart y))
1296                          (iy (imagpart y)))
1297                     (if (> (abs ry) (abs iy))
1298                         (let* ((r (/ iy ry))
1299                                (dn (+ ry (* r iy))))
1300                           (complex (/ (+ rx (* ix r)) dn)
1301                                    (/ (- ix (* rx r)) dn)))
1302                         (let* ((r (/ ry iy))
1303                                (dn (+ iy (* r ry))))
1304                           (complex (/ (+ (* rx r) ix) dn)
1305                                    (/ (- (* ix r) rx) dn)))))
1306                  #!+complex-float-vops
1307                  `(let* ((cs (conjugate (sb!vm::swap-complex x)))
1308                          (ry (realpart y))
1309                          (iy (imagpart y)))
1310                     (if (> (abs ry) (abs iy))
1311                         (let* ((r (/ iy ry))
1312                                (dn (+ ry (* r iy))))
1313                           (/ (+ x (* cs r)) dn))
1314                         (let* ((r (/ ry iy))
1315                                (dn (+ iy (* r ry))))
1316                           (/ (+ (* x r) cs) dn)))))
1317                ;; Multiply a complex by a real or vice versa.
1318                #!-complex-float-vops
1319                (deftransform * ((w z) ((complex ,type) real) *)
1320                  '(complex (* (realpart w) z) (* (imagpart w) z)))
1321                #!-complex-float-vops
1322                (deftransform * ((z w) (real (complex ,type)) *)
1323                  '(complex (* (realpart w) z) (* (imagpart w) z)))
1324                ;; Divide a complex by a real or vice versa.
1325                #!-complex-float-vops
1326                (deftransform / ((w z) ((complex ,type) real) *)
1327                  '(complex (/ (realpart w) z) (/ (imagpart w) z)))
1328                (deftransform / ((x y) (,type (complex ,type)) *)
1329                  #!-complex-float-vops
1330                  '(let* ((ry (realpart y))
1331                          (iy (imagpart y)))
1332                     (if (> (abs ry) (abs iy))
1333                         (let* ((r (/ iy ry))
1334                                (dn (+ ry (* r iy))))
1335                           (complex (/ x dn)
1336                                    (/ (- (* x r)) dn)))
1337                         (let* ((r (/ ry iy))
1338                                (dn (+ iy (* r ry))))
1339                           (complex (/ (* x r) dn)
1340                                    (/ (- x) dn)))))
1341                  #!+complex-float-vops
1342                  '(let* ((ry (realpart y))
1343                          (iy (imagpart y)))
1344                    (if (> (abs ry) (abs iy))
1345                        (let* ((r (/ iy ry))
1346                               (dn (+ ry (* r iy))))
1347                          (/ (complex x (- (* x r))) dn))
1348                        (let* ((r (/ ry iy))
1349                               (dn (+ iy (* r ry))))
1350                          (/ (complex (* x r) (- x)) dn)))))
1351                ;; conjugate of complex number
1352                #!-complex-float-vops
1353                (deftransform conjugate ((z) ((complex ,type)) *)
1354                  '(complex (realpart z) (- (imagpart z))))
1355                ;; CIS
1356                (deftransform cis ((z) ((,type)) *)
1357                  '(complex (cos z) (sin z)))
1358                ;; comparison
1359                #!-complex-float-vops
1360                (deftransform = ((w z) ((complex ,type) (complex ,type)) *)
1361                  '(and (= (realpart w) (realpart z))
1362                        (= (imagpart w) (imagpart z))))
1363                #!-complex-float-vops
1364                (deftransform = ((w z) ((complex ,type) real) *)
1365                  '(and (= (realpart w) z) (zerop (imagpart w))))
1366                #!-complex-float-vops
1367                (deftransform = ((w z) (real (complex ,type)) *)
1368                  '(and (= (realpart z) w) (zerop (imagpart z)))))))
1369
1370   (frob single-float)
1371   (frob double-float))
1372
1373 ;;; Here are simple optimizers for SIN, COS, and TAN. They do not
1374 ;;; produce a minimal range for the result; the result is the widest
1375 ;;; possible answer. This gets around the problem of doing range
1376 ;;; reduction correctly but still provides useful results when the
1377 ;;; inputs are union types.
1378 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1379 (progn
1380 (defun trig-derive-type-aux (arg domain fun
1381                                  &optional def-lo def-hi (increasingp t))
1382   (etypecase arg
1383     (numeric-type
1384      (cond ((eq (numeric-type-complexp arg) :complex)
1385             (make-numeric-type :class (numeric-type-class arg)
1386                                :format (numeric-type-format arg)
1387                                :complexp :complex))
1388            ((numeric-type-real-p arg)
1389             (let* ((format (case (numeric-type-class arg)
1390                              ((integer rational) 'single-float)
1391                              (t (numeric-type-format arg))))
1392                    (bound-type (or format 'float)))
1393               ;; If the argument is a subset of the "principal" domain
1394               ;; of the function, we can compute the bounds because
1395               ;; the function is monotonic. We can't do this in
1396               ;; general for these periodic functions because we can't
1397               ;; (and don't want to) do the argument reduction in
1398               ;; exactly the same way as the functions themselves do
1399               ;; it.
1400               (if (csubtypep arg domain)
1401                   (let ((res-lo (bound-func fun (numeric-type-low arg)))
1402                         (res-hi (bound-func fun (numeric-type-high arg))))
1403                     (unless increasingp
1404                       (rotatef res-lo res-hi))
1405                     (make-numeric-type
1406                      :class 'float
1407                      :format format
1408                      :low (coerce-numeric-bound res-lo bound-type)
1409                      :high (coerce-numeric-bound res-hi bound-type)))
1410                   (make-numeric-type
1411                    :class 'float
1412                    :format format
1413                    :low (and def-lo (coerce def-lo bound-type))
1414                    :high (and def-hi (coerce def-hi bound-type))))))
1415            (t
1416             (float-or-complex-float-type arg def-lo def-hi))))))
1417
1418 (defoptimizer (sin derive-type) ((num))
1419   (one-arg-derive-type
1420    num
1421    (lambda (arg)
1422      ;; Derive the bounds if the arg is in [-pi/2, pi/2].
1423      (trig-derive-type-aux
1424       arg
1425       (specifier-type `(float ,(- (/ pi 2)) ,(/ pi 2)))
1426       #'sin
1427       -1 1))
1428    #'sin))
1429
1430 (defoptimizer (cos derive-type) ((num))
1431   (one-arg-derive-type
1432    num
1433    (lambda (arg)
1434      ;; Derive the bounds if the arg is in [0, pi].
1435      (trig-derive-type-aux arg
1436                            (specifier-type `(float 0d0 ,pi))
1437                            #'cos
1438                            -1 1
1439                            nil))
1440    #'cos))
1441
1442 (defoptimizer (tan derive-type) ((num))
1443   (one-arg-derive-type
1444    num
1445    (lambda (arg)
1446      ;; Derive the bounds if the arg is in [-pi/2, pi/2].
1447      (trig-derive-type-aux arg
1448                            (specifier-type `(float ,(- (/ pi 2)) ,(/ pi 2)))
1449                            #'tan
1450                            nil nil))
1451    #'tan))
1452
1453 (defoptimizer (conjugate derive-type) ((num))
1454   (one-arg-derive-type num
1455     (lambda (arg)
1456       (flet ((most-negative-bound (l h)
1457                (and l h
1458                     (if (< (type-bound-number l) (- (type-bound-number h)))
1459                         l
1460                         (set-bound (- (type-bound-number h)) (consp h)))))
1461              (most-positive-bound (l h)
1462                (and l h
1463                     (if (> (type-bound-number h) (- (type-bound-number l)))
1464                         h
1465                         (set-bound (- (type-bound-number l)) (consp l))))))
1466         (if (numeric-type-real-p arg)
1467             (lvar-type num)
1468             (let ((low (numeric-type-low arg))
1469                   (high (numeric-type-high arg)))
1470               (let ((new-low (most-negative-bound low high))
1471                     (new-high (most-positive-bound low high)))
1472               (modified-numeric-type arg :low new-low :high new-high))))))
1473     #'conjugate))
1474
1475 (defoptimizer (cis derive-type) ((num))
1476   (one-arg-derive-type num
1477     (lambda (arg)
1478       (sb!c::specifier-type
1479        `(complex ,(or (numeric-type-format arg) 'float))))
1480     #'cis))
1481
1482 ) ; PROGN
1483 \f
1484 ;;;; TRUNCATE, FLOOR, CEILING, and ROUND
1485
1486 (macrolet ((define-frobs (fun ufun)
1487              `(progn
1488                 (defknown ,ufun (real) integer (movable foldable flushable))
1489                 (deftransform ,fun ((x &optional by)
1490                                     (* &optional
1491                                        (constant-arg (member 1))))
1492                   '(let ((res (,ufun x)))
1493                      (values res (- x res)))))))
1494   (define-frobs truncate %unary-truncate)
1495   (define-frobs round %unary-round))
1496
1497 (deftransform %unary-truncate ((x) (single-float))
1498   `(%unary-truncate/single-float x))
1499 (deftransform %unary-truncate ((x) (double-float))
1500   `(%unary-truncate/double-float x))
1501
1502 ;;; Convert (TRUNCATE x y) to the obvious implementation.
1503 ;;;
1504 ;;; ...plus hair: Insert explicit coercions to appropriate float types: Python
1505 ;;; is reluctant it generate explicit integer->float coercions due to
1506 ;;; precision issues (see SAFE-SINGLE-COERCION-P &co), but this is not an
1507 ;;; issue here as there is no DERIVE-TYPE optimizer on specialized versions of
1508 ;;; %UNARY-TRUNCATE, so the derived type of TRUNCATE remains the best we can
1509 ;;; do here -- which is fine. Also take care not to add unnecassary division
1510 ;;; or multiplication by 1, since we are not able to always eliminate them,
1511 ;;; depending on FLOAT-ACCURACY. Finally, leave out the secondary value when
1512 ;;; we know it is unused: COERCE is not flushable.
1513 (macrolet ((def (type other-float-arg-types)
1514              (let ((unary (symbolicate "%UNARY-TRUNCATE/" type))
1515                    (coerce (symbolicate "%" type)))
1516                `(deftransform truncate ((x &optional y)
1517                                         (,type
1518                                          &optional (or ,type ,@other-float-arg-types integer))
1519                                         * :result result)
1520                   (let ((result-type (lvar-type result)))
1521                     (if (or (not y)
1522                             (and (constant-lvar-p y) (= 1 (lvar-value y))))
1523                         (if (values-type-p result-type)
1524                             `(let ((res (,',unary x)))
1525                                (values res (- x (,',coerce res))))
1526                             `(let ((res (,',unary x)))
1527                                ;; Dummy secondary value!
1528                                (values res x)))
1529                         (if (values-type-p result-type)
1530                             `(let* ((f (,',coerce y))
1531                                     (res (,',unary (/ x f))))
1532                                (values res (- x (* f (,',coerce res)))))
1533                             `(let* ((f (,',coerce y))
1534                                     (res (,',unary (/ x f))))
1535                                ;; Dummy secondary value!
1536                                (values res x)))))))))
1537   (def single-float ())
1538   (def double-float (single-float)))
1539
1540 (deftransform floor ((number &optional divisor)
1541                      (float &optional (or integer float)))
1542   (let ((defaulted-divisor (if divisor 'divisor 1)))
1543     `(multiple-value-bind (tru rem) (truncate number ,defaulted-divisor)
1544        (if (and (not (zerop rem))
1545                 (if (minusp ,defaulted-divisor)
1546                     (plusp number)
1547                     (minusp number)))
1548            (values (1- tru) (+ rem ,defaulted-divisor))
1549            (values tru rem)))))
1550
1551 (deftransform ceiling ((number &optional divisor)
1552                        (float &optional (or integer float)))
1553   (let ((defaulted-divisor (if divisor 'divisor 1)))
1554     `(multiple-value-bind (tru rem) (truncate number ,defaulted-divisor)
1555        (if (and (not (zerop rem))
1556                 (if (minusp ,defaulted-divisor)
1557                     (minusp number)
1558                     (plusp number)))
1559            (values (1+ tru) (- rem ,defaulted-divisor))
1560            (values tru rem)))))
1561
1562 (defknown %unary-ftruncate (real) float (movable foldable flushable))
1563 (defknown %unary-ftruncate/single (single-float) single-float
1564   (movable foldable flushable))
1565 (defknown %unary-ftruncate/double (double-float) double-float
1566   (movable foldable flushable))
1567
1568 (defun %unary-ftruncate/single (x)
1569   (declare (type single-float x))
1570   (declare (optimize speed (safety 0)))
1571   (let* ((bits (single-float-bits x))
1572          (exp (ldb sb!vm:single-float-exponent-byte bits))
1573          (biased (the single-float-exponent
1574                    (- exp sb!vm:single-float-bias))))
1575     (declare (type (signed-byte 32) bits))
1576     (cond
1577       ((= exp sb!vm:single-float-normal-exponent-max) x)
1578       ((<= biased 0) (* x 0f0))
1579       ((>= biased (float-digits x)) x)
1580       (t
1581        (let ((frac-bits (- (float-digits x) biased)))
1582          (setf bits (logandc2 bits (- (ash 1 frac-bits) 1)))
1583          (make-single-float bits))))))
1584
1585 (defun %unary-ftruncate/double (x)
1586   (declare (type double-float x))
1587   (declare (optimize speed (safety 0)))
1588   (let* ((high (double-float-high-bits x))
1589          (low (double-float-low-bits x))
1590          (exp (ldb sb!vm:double-float-exponent-byte high))
1591          (biased (the double-float-exponent
1592                    (- exp sb!vm:double-float-bias))))
1593     (declare (type (signed-byte 32) high)
1594              (type (unsigned-byte 32) low))
1595     (cond
1596       ((= exp sb!vm:double-float-normal-exponent-max) x)
1597       ((<= biased 0) (* x 0d0))
1598       ((>= biased (float-digits x)) x)
1599       (t
1600        (let ((frac-bits (- (float-digits x) biased)))
1601          (cond ((< frac-bits 32)
1602                 (setf low (logandc2 low (- (ash 1 frac-bits) 1))))
1603                (t
1604                 (setf low 0)
1605                 (setf high (logandc2 high (- (ash 1 (- frac-bits 32)) 1)))))
1606          (make-double-float high low))))))
1607
1608 (macrolet
1609     ((def (float-type fun)
1610          `(deftransform %unary-ftruncate ((x) (,float-type))
1611             '(,fun x))))
1612   (def single-float %unary-ftruncate/single)
1613   (def double-float %unary-ftruncate/double))