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