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