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