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