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