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