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