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