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