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