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