9fa22a2f024ff0e350c3709c55ef16b77126b5eb
[sbcl.git] / src / compiler / srctran.lisp
1 ;;;; This file contains macro-like source transformations which
2 ;;;; convert uses of certain functions into the canonical form desired
3 ;;;; within the compiler. FIXME: and other IR1 transforms and stuff.
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
16 ;;; Convert into an IF so that IF optimizations will eliminate redundant
17 ;;; negations.
18 (define-source-transform not (x) `(if ,x nil t))
19 (define-source-transform null (x) `(if ,x nil t))
20
21 ;;; ENDP is just NULL with a LIST assertion. The assertion will be
22 ;;; optimized away when SAFETY optimization is low; hopefully that
23 ;;; is consistent with ANSI's "should return an error".
24 (define-source-transform endp (x) `(null (the list ,x)))
25
26 ;;; We turn IDENTITY into PROG1 so that it is obvious that it just
27 ;;; returns the first value of its argument. Ditto for VALUES with one
28 ;;; arg.
29 (define-source-transform identity (x) `(prog1 ,x))
30 (define-source-transform values (x) `(prog1 ,x))
31
32 ;;; Bind the value and make a closure that returns it.
33 (define-source-transform constantly (value)
34   (with-unique-names (rest n-value)
35     `(let ((,n-value ,value))
36       (lambda (&rest ,rest)
37         (declare (ignore ,rest))
38         ,n-value))))
39
40 ;;; If the function has a known number of arguments, then return a
41 ;;; lambda with the appropriate fixed number of args. If the
42 ;;; destination is a FUNCALL, then do the &REST APPLY thing, and let
43 ;;; MV optimization figure things out.
44 (deftransform complement ((fun) * * :node node)
45   "open code"
46   (multiple-value-bind (min max)
47       (fun-type-nargs (continuation-type fun))
48     (cond
49      ((and min (eql min max))
50       (let ((dums (make-gensym-list min)))
51         `#'(lambda ,dums (not (funcall fun ,@dums)))))
52      ((let* ((cont (node-cont node))
53              (dest (continuation-dest cont)))
54         (and (combination-p dest)
55              (eq (combination-fun dest) cont)))
56       '#'(lambda (&rest args)
57            (not (apply fun args))))
58      (t
59       (give-up-ir1-transform
60        "The function doesn't have a fixed argument count.")))))
61 \f
62 ;;;; list hackery
63
64 ;;; Translate CxR into CAR/CDR combos.
65 (defun source-transform-cxr (form)
66   (if (/= (length form) 2)
67       (values nil t)
68       (let ((name (symbol-name (car form))))
69         (do ((i (- (length name) 2) (1- i))
70              (res (cadr form)
71                   `(,(ecase (char name i)
72                        (#\A 'car)
73                        (#\D 'cdr))
74                     ,res)))
75             ((zerop i) res)))))
76
77 ;;; Make source transforms to turn CxR forms into combinations of CAR
78 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
79 ;;; defined.
80 (/show0 "about to set CxR source transforms")
81 (loop for i of-type index from 2 upto 4 do
82       ;; Iterate over BUF = all names CxR where x = an I-element
83       ;; string of #\A or #\D characters.
84       (let ((buf (make-string (+ 2 i))))
85         (setf (aref buf 0) #\C
86               (aref buf (1+ i)) #\R)
87         (dotimes (j (ash 2 i))
88           (declare (type index j))
89           (dotimes (k i)
90             (declare (type index k))
91             (setf (aref buf (1+ k))
92                   (if (logbitp k j) #\A #\D)))
93           (setf (info :function :source-transform (intern buf))
94                 #'source-transform-cxr))))
95 (/show0 "done setting CxR source transforms")
96
97 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
98 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
99 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
100 ;;; favors it.
101 (define-source-transform first (x) `(car ,x))
102 (define-source-transform rest (x) `(cdr ,x))
103 (define-source-transform second (x) `(cadr ,x))
104 (define-source-transform third (x) `(caddr ,x))
105 (define-source-transform fourth (x) `(cadddr ,x))
106 (define-source-transform fifth (x) `(nth 4 ,x))
107 (define-source-transform sixth (x) `(nth 5 ,x))
108 (define-source-transform seventh (x) `(nth 6 ,x))
109 (define-source-transform eighth (x) `(nth 7 ,x))
110 (define-source-transform ninth (x) `(nth 8 ,x))
111 (define-source-transform tenth (x) `(nth 9 ,x))
112
113 ;;; Translate RPLACx to LET and SETF.
114 (define-source-transform rplaca (x y)
115   (once-only ((n-x x))
116     `(progn
117        (setf (car ,n-x) ,y)
118        ,n-x)))
119 (define-source-transform rplacd (x y)
120   (once-only ((n-x x))
121     `(progn
122        (setf (cdr ,n-x) ,y)
123        ,n-x)))
124
125 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
126
127 (defvar *default-nthcdr-open-code-limit* 6)
128 (defvar *extreme-nthcdr-open-code-limit* 20)
129
130 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
131   "convert NTHCDR to CAxxR"
132   (unless (constant-continuation-p n)
133     (give-up-ir1-transform))
134   (let ((n (continuation-value n)))
135     (when (> n
136              (if (policy node (and (= speed 3) (= space 0)))
137                  *extreme-nthcdr-open-code-limit*
138                  *default-nthcdr-open-code-limit*))
139       (give-up-ir1-transform))
140
141     (labels ((frob (n)
142                (if (zerop n)
143                    'l
144                    `(cdr ,(frob (1- n))))))
145       (frob n))))
146 \f
147 ;;;; arithmetic and numerology
148
149 (define-source-transform plusp (x) `(> ,x 0))
150 (define-source-transform minusp (x) `(< ,x 0))
151 (define-source-transform zerop (x) `(= ,x 0))
152
153 (define-source-transform 1+ (x) `(+ ,x 1))
154 (define-source-transform 1- (x) `(- ,x 1))
155
156 (define-source-transform oddp (x) `(not (zerop (logand ,x 1))))
157 (define-source-transform evenp (x) `(zerop (logand ,x 1)))
158
159 ;;; Note that all the integer division functions are available for
160 ;;; inline expansion.
161
162 (macrolet ((deffrob (fun)
163              `(define-source-transform ,fun (x &optional (y nil y-p))
164                 (declare (ignore y))
165                 (if y-p
166                     (values nil t)
167                     `(,',fun ,x 1)))))
168   (deffrob truncate)
169   (deffrob round)
170   #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
171   (deffrob floor)
172   #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
173   (deffrob ceiling))
174
175 (define-source-transform lognand (x y) `(lognot (logand ,x ,y)))
176 (define-source-transform lognor (x y) `(lognot (logior ,x ,y)))
177 (define-source-transform logandc1 (x y) `(logand (lognot ,x) ,y))
178 (define-source-transform logandc2 (x y) `(logand ,x (lognot ,y)))
179 (define-source-transform logorc1 (x y) `(logior (lognot ,x) ,y))
180 (define-source-transform logorc2 (x y) `(logior ,x (lognot ,y)))
181 (define-source-transform logtest (x y) `(not (zerop (logand ,x ,y))))
182 (define-source-transform logbitp (index integer)
183   `(not (zerop (logand (ash 1 ,index) ,integer))))
184 (define-source-transform byte (size position)
185   `(cons ,size ,position))
186 (define-source-transform byte-size (spec) `(car ,spec))
187 (define-source-transform byte-position (spec) `(cdr ,spec))
188 (define-source-transform ldb-test (bytespec integer)
189   `(not (zerop (mask-field ,bytespec ,integer))))
190
191 ;;; With the ratio and complex accessors, we pick off the "identity"
192 ;;; case, and use a primitive to handle the cell access case.
193 (define-source-transform numerator (num)
194   (once-only ((n-num `(the rational ,num)))
195     `(if (ratiop ,n-num)
196          (%numerator ,n-num)
197          ,n-num)))
198 (define-source-transform denominator (num)
199   (once-only ((n-num `(the rational ,num)))
200     `(if (ratiop ,n-num)
201          (%denominator ,n-num)
202          1)))
203 \f
204 ;;;; interval arithmetic for computing bounds
205 ;;;;
206 ;;;; This is a set of routines for operating on intervals. It
207 ;;;; implements a simple interval arithmetic package. Although SBCL
208 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
209 ;;;; for two reasons:
210 ;;;;
211 ;;;;   1. This package is simpler than NUMERIC-TYPE.
212 ;;;;
213 ;;;;   2. It makes debugging much easier because you can just strip
214 ;;;;   out these routines and test them independently of SBCL. (This is a
215 ;;;;   big win!)
216 ;;;;
217 ;;;; One disadvantage is a probable increase in consing because we
218 ;;;; have to create these new interval structures even though
219 ;;;; numeric-type has everything we want to know. Reason 2 wins for
220 ;;;; now.
221
222 ;;; The basic interval type. It can handle open and closed intervals.
223 ;;; A bound is open if it is a list containing a number, just like
224 ;;; Lisp says. NIL means unbounded.
225 (defstruct (interval (:constructor %make-interval)
226                      (:copier nil))
227   low high)
228
229 (defun make-interval (&key low high)
230   (labels ((normalize-bound (val)
231              (cond ((and (floatp val)
232                          (float-infinity-p val))
233                     ;; Handle infinities.
234                     nil)
235                    ((or (numberp val)
236                         (eq val nil))
237                     ;; Handle any closed bounds.
238                     val)
239                    ((listp val)
240                     ;; We have an open bound. Normalize the numeric
241                     ;; bound. If the normalized bound is still a number
242                     ;; (not nil), keep the bound open. Otherwise, the
243                     ;; bound is really unbounded, so drop the openness.
244                     (let ((new-val (normalize-bound (first val))))
245                       (when new-val
246                         ;; The bound exists, so keep it open still.
247                         (list new-val))))
248                    (t
249                     (error "unknown bound type in MAKE-INTERVAL")))))
250     (%make-interval :low (normalize-bound low)
251                     :high (normalize-bound high))))
252
253 ;;; Given a number X, create a form suitable as a bound for an
254 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
255 #!-sb-fluid (declaim (inline set-bound))
256 (defun set-bound (x open-p)
257   (if (and x open-p) (list x) x))
258
259 ;;; Apply the function F to a bound X. If X is an open bound, then
260 ;;; the result will be open. IF X is NIL, the result is NIL.
261 (defun bound-func (f x)
262   (declare (type function f))
263   (and x
264        (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
265          ;; With these traps masked, we might get things like infinity
266          ;; or negative infinity returned. Check for this and return
267          ;; NIL to indicate unbounded.
268          (let ((y (funcall f (type-bound-number x))))
269            (if (and (floatp y)
270                     (float-infinity-p y))
271                nil
272                (set-bound (funcall f (type-bound-number x)) (consp x)))))))
273
274 ;;; Apply a binary operator OP to two bounds X and Y. The result is
275 ;;; NIL if either is NIL. Otherwise bound is computed and the result
276 ;;; is open if either X or Y is open.
277 ;;;
278 ;;; FIXME: only used in this file, not needed in target runtime
279 (defmacro bound-binop (op x y)
280   `(and ,x ,y
281        (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
282          (set-bound (,op (type-bound-number ,x)
283                          (type-bound-number ,y))
284                     (or (consp ,x) (consp ,y))))))
285
286 ;;; Convert a numeric-type object to an interval object.
287 (defun numeric-type->interval (x)
288   (declare (type numeric-type x))
289   (make-interval :low (numeric-type-low x)
290                  :high (numeric-type-high x)))
291
292 (defun copy-interval-limit (limit)
293   (if (numberp limit)
294       limit
295       (copy-list limit)))
296
297 (defun copy-interval (x)
298   (declare (type interval x))
299   (make-interval :low (copy-interval-limit (interval-low x))
300                  :high (copy-interval-limit (interval-high x))))
301
302 ;;; Given a point P contained in the interval X, split X into two
303 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
304 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
305 ;;; contains P. You can specify both to be T or NIL.
306 (defun interval-split (p x &optional close-lower close-upper)
307   (declare (type number p)
308            (type interval x))
309   (list (make-interval :low (copy-interval-limit (interval-low x))
310                        :high (if close-lower p (list p)))
311         (make-interval :low (if close-upper (list p) p)
312                        :high (copy-interval-limit (interval-high x)))))
313
314 ;;; Return the closure of the interval. That is, convert open bounds
315 ;;; to closed bounds.
316 (defun interval-closure (x)
317   (declare (type interval x))
318   (make-interval :low (type-bound-number (interval-low x))
319                  :high (type-bound-number (interval-high x))))
320
321 (defun signed-zero->= (x y)
322   (declare (real x y))
323   (or (> x y)
324       (and (= x y)
325            (>= (float-sign (float x))
326                (float-sign (float y))))))
327
328 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
329 ;;; '-. Otherwise return NIL.
330 #+nil
331 (defun interval-range-info (x &optional (point 0))
332   (declare (type interval x))
333   (let ((lo (interval-low x))
334         (hi (interval-high x)))
335     (cond ((and lo (signed-zero->= (type-bound-number lo) point))
336            '+)
337           ((and hi (signed-zero->= point (type-bound-number hi)))
338            '-)
339           (t
340            nil))))
341 (defun interval-range-info (x &optional (point 0))
342   (declare (type interval x))
343   (labels ((signed->= (x y)
344              (if (and (zerop x) (zerop y) (floatp x) (floatp y))
345                  (>= (float-sign x) (float-sign y))
346                  (>= x y))))
347     (let ((lo (interval-low x))
348           (hi (interval-high x)))
349       (cond ((and lo (signed->= (type-bound-number lo) point))
350              '+)
351             ((and hi (signed->= point (type-bound-number hi)))
352              '-)
353             (t
354              nil)))))
355
356 ;;; Test to see whether the interval X is bounded. HOW determines the
357 ;;; test, and should be either ABOVE, BELOW, or BOTH.
358 (defun interval-bounded-p (x how)
359   (declare (type interval x))
360   (ecase how
361     (above
362      (interval-high x))
363     (below
364      (interval-low x))
365     (both
366      (and (interval-low x) (interval-high x)))))
367
368 ;;; signed zero comparison functions. Use these functions if we need
369 ;;; to distinguish between signed zeroes.
370 (defun signed-zero-< (x y)
371   (declare (real x y))
372   (or (< x y)
373       (and (= x y)
374            (< (float-sign (float x))
375               (float-sign (float y))))))
376 (defun signed-zero-> (x y)
377   (declare (real x y))
378   (or (> x y)
379       (and (= x y)
380            (> (float-sign (float x))
381               (float-sign (float y))))))
382 (defun signed-zero-= (x y)
383   (declare (real x y))
384   (and (= x y)
385        (= (float-sign (float x))
386           (float-sign (float y)))))
387 (defun signed-zero-<= (x y)
388   (declare (real x y))
389   (or (< x y)
390       (and (= x y)
391            (<= (float-sign (float x))
392                (float-sign (float y))))))
393
394 ;;; See whether the interval X contains the number P, taking into
395 ;;; account that the interval might not be closed.
396 (defun interval-contains-p (p x)
397   (declare (type number p)
398            (type interval x))
399   ;; Does the interval X contain the number P?  This would be a lot
400   ;; easier if all intervals were closed!
401   (let ((lo (interval-low x))
402         (hi (interval-high x)))
403     (cond ((and lo hi)
404            ;; The interval is bounded
405            (if (and (signed-zero-<= (type-bound-number lo) p)
406                     (signed-zero-<= p (type-bound-number hi)))
407                ;; P is definitely in the closure of the interval.
408                ;; We just need to check the end points now.
409                (cond ((signed-zero-= p (type-bound-number lo))
410                       (numberp lo))
411                      ((signed-zero-= p (type-bound-number hi))
412                       (numberp hi))
413                      (t t))
414                nil))
415           (hi
416            ;; Interval with upper bound
417            (if (signed-zero-< p (type-bound-number hi))
418                t
419                (and (numberp hi) (signed-zero-= p hi))))
420           (lo
421            ;; Interval with lower bound
422            (if (signed-zero-> p (type-bound-number lo))
423                t
424                (and (numberp lo) (signed-zero-= p lo))))
425           (t
426            ;; Interval with no bounds
427            t))))
428
429 ;;; Determine whether two intervals X and Y intersect. Return T if so.
430 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
431 ;;; were closed. Otherwise the intervals are treated as they are.
432 ;;;
433 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
434 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
435 ;;; is T, then they do intersect because we use the closure of X = [0,
436 ;;; 1] and Y = [1, 2] to determine intersection.
437 (defun interval-intersect-p (x y &optional closed-intervals-p)
438   (declare (type interval x y))
439   (multiple-value-bind (intersect diff)
440       (interval-intersection/difference (if closed-intervals-p
441                                             (interval-closure x)
442                                             x)
443                                         (if closed-intervals-p
444                                             (interval-closure y)
445                                             y))
446     (declare (ignore diff))
447     intersect))
448
449 ;;; Are the two intervals adjacent?  That is, is there a number
450 ;;; between the two intervals that is not an element of either
451 ;;; interval?  If so, they are not adjacent. For example [0, 1) and
452 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
453 ;;; between both intervals.
454 (defun interval-adjacent-p (x y)
455   (declare (type interval x y))
456   (flet ((adjacent (lo hi)
457            ;; Check to see whether lo and hi are adjacent. If either is
458            ;; nil, they can't be adjacent.
459            (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
460              ;; The bounds are equal. They are adjacent if one of
461              ;; them is closed (a number). If both are open (consp),
462              ;; then there is a number that lies between them.
463              (or (numberp lo) (numberp hi)))))
464     (or (adjacent (interval-low y) (interval-high x))
465         (adjacent (interval-low x) (interval-high y)))))
466
467 ;;; Compute the intersection and difference between two intervals.
468 ;;; Two values are returned: the intersection and the difference.
469 ;;;
470 ;;; Let the two intervals be X and Y, and let I and D be the two
471 ;;; values returned by this function. Then I = X intersect Y. If I
472 ;;; is NIL (the empty set), then D is X union Y, represented as the
473 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
474 ;;; - I, which is a list of two intervals.
475 ;;;
476 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
477 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
478 (defun interval-intersection/difference (x y)
479   (declare (type interval x y))
480   (let ((x-lo (interval-low x))
481         (x-hi (interval-high x))
482         (y-lo (interval-low y))
483         (y-hi (interval-high y)))
484     (labels
485         ((opposite-bound (p)
486            ;; If p is an open bound, make it closed. If p is a closed
487            ;; bound, make it open.
488            (if (listp p)
489                (first p)
490                (list p)))
491          (test-number (p int)
492            ;; Test whether P is in the interval.
493            (when (interval-contains-p (type-bound-number p)
494                                       (interval-closure int))
495              (let ((lo (interval-low int))
496                    (hi (interval-high int)))
497                ;; Check for endpoints.
498                (cond ((and lo (= (type-bound-number p) (type-bound-number lo)))
499                       (not (and (consp p) (numberp lo))))
500                      ((and hi (= (type-bound-number p) (type-bound-number hi)))
501                       (not (and (numberp p) (consp hi))))
502                      (t t)))))
503          (test-lower-bound (p int)
504            ;; P is a lower bound of an interval.
505            (if p
506                (test-number p int)
507                (not (interval-bounded-p int 'below))))
508          (test-upper-bound (p int)
509            ;; P is an upper bound of an interval.
510            (if p
511                (test-number p int)
512                (not (interval-bounded-p int 'above)))))
513       (let ((x-lo-in-y (test-lower-bound x-lo y))
514             (x-hi-in-y (test-upper-bound x-hi y))
515             (y-lo-in-x (test-lower-bound y-lo x))
516             (y-hi-in-x (test-upper-bound y-hi x)))
517         (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
518                ;; Intervals intersect. Let's compute the intersection
519                ;; and the difference.
520                (multiple-value-bind (lo left-lo left-hi)
521                    (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
522                          (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
523                  (multiple-value-bind (hi right-lo right-hi)
524                      (cond (x-hi-in-y
525                             (values x-hi (opposite-bound x-hi) y-hi))
526                            (y-hi-in-x
527                             (values y-hi (opposite-bound y-hi) x-hi)))
528                    (values (make-interval :low lo :high hi)
529                            (list (make-interval :low left-lo
530                                                 :high left-hi)
531                                  (make-interval :low right-lo
532                                                 :high right-hi))))))
533               (t
534                (values nil (list x y))))))))
535
536 ;;; If intervals X and Y intersect, return a new interval that is the
537 ;;; union of the two. If they do not intersect, return NIL.
538 (defun interval-merge-pair (x y)
539   (declare (type interval x y))
540   ;; If x and y intersect or are adjacent, create the union.
541   ;; Otherwise return nil
542   (when (or (interval-intersect-p x y)
543             (interval-adjacent-p x y))
544     (flet ((select-bound (x1 x2 min-op max-op)
545              (let ((x1-val (type-bound-number x1))
546                    (x2-val (type-bound-number x2)))
547                (cond ((and x1 x2)
548                       ;; Both bounds are finite. Select the right one.
549                       (cond ((funcall min-op x1-val x2-val)
550                              ;; x1 is definitely better.
551                              x1)
552                             ((funcall max-op x1-val x2-val)
553                              ;; x2 is definitely better.
554                              x2)
555                             (t
556                              ;; Bounds are equal. Select either
557                              ;; value and make it open only if
558                              ;; both were open.
559                              (set-bound x1-val (and (consp x1) (consp x2))))))
560                      (t
561                       ;; At least one bound is not finite. The
562                       ;; non-finite bound always wins.
563                       nil)))))
564       (let* ((x-lo (copy-interval-limit (interval-low x)))
565              (x-hi (copy-interval-limit (interval-high x)))
566              (y-lo (copy-interval-limit (interval-low y)))
567              (y-hi (copy-interval-limit (interval-high y))))
568         (make-interval :low (select-bound x-lo y-lo #'< #'>)
569                        :high (select-bound x-hi y-hi #'> #'<))))))
570
571 ;;; basic arithmetic operations on intervals. We probably should do
572 ;;; true interval arithmetic here, but it's complicated because we
573 ;;; have float and integer types and bounds can be open or closed.
574
575 ;;; the negative of an interval
576 (defun interval-neg (x)
577   (declare (type interval x))
578   (make-interval :low (bound-func #'- (interval-high x))
579                  :high (bound-func #'- (interval-low x))))
580
581 ;;; Add two intervals.
582 (defun interval-add (x y)
583   (declare (type interval x y))
584   (make-interval :low (bound-binop + (interval-low x) (interval-low y))
585                  :high (bound-binop + (interval-high x) (interval-high y))))
586
587 ;;; Subtract two intervals.
588 (defun interval-sub (x y)
589   (declare (type interval x y))
590   (make-interval :low (bound-binop - (interval-low x) (interval-high y))
591                  :high (bound-binop - (interval-high x) (interval-low y))))
592
593 ;;; Multiply two intervals.
594 (defun interval-mul (x y)
595   (declare (type interval x y))
596   (flet ((bound-mul (x y)
597            (cond ((or (null x) (null y))
598                   ;; Multiply by infinity is infinity
599                   nil)
600                  ((or (and (numberp x) (zerop x))
601                       (and (numberp y) (zerop y)))
602                   ;; Multiply by closed zero is special. The result
603                   ;; is always a closed bound. But don't replace this
604                   ;; with zero; we want the multiplication to produce
605                   ;; the correct signed zero, if needed.
606                   (* (type-bound-number x) (type-bound-number y)))
607                  ((or (and (floatp x) (float-infinity-p x))
608                       (and (floatp y) (float-infinity-p y)))
609                   ;; Infinity times anything is infinity
610                   nil)
611                  (t
612                   ;; General multiply. The result is open if either is open.
613                   (bound-binop * x y)))))
614     (let ((x-range (interval-range-info x))
615           (y-range (interval-range-info y)))
616       (cond ((null x-range)
617              ;; Split x into two and multiply each separately
618              (destructuring-bind (x- x+) (interval-split 0 x t t)
619                (interval-merge-pair (interval-mul x- y)
620                                     (interval-mul x+ y))))
621             ((null y-range)
622              ;; Split y into two and multiply each separately
623              (destructuring-bind (y- y+) (interval-split 0 y t t)
624                (interval-merge-pair (interval-mul x y-)
625                                     (interval-mul x y+))))
626             ((eq x-range '-)
627              (interval-neg (interval-mul (interval-neg x) y)))
628             ((eq y-range '-)
629              (interval-neg (interval-mul x (interval-neg y))))
630             ((and (eq x-range '+) (eq y-range '+))
631              ;; If we are here, X and Y are both positive.
632              (make-interval
633               :low (bound-mul (interval-low x) (interval-low y))
634               :high (bound-mul (interval-high x) (interval-high y))))
635             (t
636              (bug "excluded case in INTERVAL-MUL"))))))
637
638 ;;; Divide two intervals.
639 (defun interval-div (top bot)
640   (declare (type interval top bot))
641   (flet ((bound-div (x y y-low-p)
642            ;; Compute x/y
643            (cond ((null y)
644                   ;; Divide by infinity means result is 0. However,
645                   ;; we need to watch out for the sign of the result,
646                   ;; to correctly handle signed zeros. We also need
647                   ;; to watch out for positive or negative infinity.
648                   (if (floatp (type-bound-number x))
649                       (if y-low-p
650                           (- (float-sign (type-bound-number x) 0.0))
651                           (float-sign (type-bound-number x) 0.0))
652                       0))
653                  ((zerop (type-bound-number y))
654                   ;; Divide by zero means result is infinity
655                   nil)
656                  ((and (numberp x) (zerop x))
657                   ;; Zero divided by anything is zero.
658                   x)
659                  (t
660                   (bound-binop / x y)))))
661     (let ((top-range (interval-range-info top))
662           (bot-range (interval-range-info bot)))
663       (cond ((null bot-range)
664              ;; The denominator contains zero, so anything goes!
665              (make-interval :low nil :high nil))
666             ((eq bot-range '-)
667              ;; Denominator is negative so flip the sign, compute the
668              ;; result, and flip it back.
669              (interval-neg (interval-div top (interval-neg bot))))
670             ((null top-range)
671              ;; Split top into two positive and negative parts, and
672              ;; divide each separately
673              (destructuring-bind (top- top+) (interval-split 0 top t t)
674                (interval-merge-pair (interval-div top- bot)
675                                     (interval-div top+ bot))))
676             ((eq top-range '-)
677              ;; Top is negative so flip the sign, divide, and flip the
678              ;; sign of the result.
679              (interval-neg (interval-div (interval-neg top) bot)))
680             ((and (eq top-range '+) (eq bot-range '+))
681              ;; the easy case
682              (make-interval
683               :low (bound-div (interval-low top) (interval-high bot) t)
684               :high (bound-div (interval-high top) (interval-low bot) nil)))
685             (t
686              (bug "excluded case in INTERVAL-DIV"))))))
687
688 ;;; Apply the function F to the interval X. If X = [a, b], then the
689 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
690 ;;; result makes sense. It will if F is monotonic increasing (or
691 ;;; non-decreasing).
692 (defun interval-func (f x)
693   (declare (type function f)
694            (type interval x))
695   (let ((lo (bound-func f (interval-low x)))
696         (hi (bound-func f (interval-high x))))
697     (make-interval :low lo :high hi)))
698
699 ;;; Return T if X < Y. That is every number in the interval X is
700 ;;; always less than any number in the interval Y.
701 (defun interval-< (x y)
702   (declare (type interval x y))
703   ;; X < Y only if X is bounded above, Y is bounded below, and they
704   ;; don't overlap.
705   (when (and (interval-bounded-p x 'above)
706              (interval-bounded-p y 'below))
707     ;; Intervals are bounded in the appropriate way. Make sure they
708     ;; don't overlap.
709     (let ((left (interval-high x))
710           (right (interval-low y)))
711       (cond ((> (type-bound-number left)
712                 (type-bound-number right))
713              ;; The intervals definitely overlap, so result is NIL.
714              nil)
715             ((< (type-bound-number left)
716                 (type-bound-number right))
717              ;; The intervals definitely don't touch, so result is T.
718              t)
719             (t
720              ;; Limits are equal. Check for open or closed bounds.
721              ;; Don't overlap if one or the other are open.
722              (or (consp left) (consp right)))))))
723
724 ;;; Return T if X >= Y. That is, every number in the interval X is
725 ;;; always greater than any number in the interval Y.
726 (defun interval->= (x y)
727   (declare (type interval x y))
728   ;; X >= Y if lower bound of X >= upper bound of Y
729   (when (and (interval-bounded-p x 'below)
730              (interval-bounded-p y 'above))
731     (>= (type-bound-number (interval-low x))
732         (type-bound-number (interval-high y)))))
733
734 ;;; Return an interval that is the absolute value of X. Thus, if
735 ;;; X = [-1 10], the result is [0, 10].
736 (defun interval-abs (x)
737   (declare (type interval x))
738   (case (interval-range-info x)
739     (+
740      (copy-interval x))
741     (-
742      (interval-neg x))
743     (t
744      (destructuring-bind (x- x+) (interval-split 0 x t t)
745        (interval-merge-pair (interval-neg x-) x+)))))
746
747 ;;; Compute the square of an interval.
748 (defun interval-sqr (x)
749   (declare (type interval x))
750   (interval-func (lambda (x) (* x x))
751                  (interval-abs x)))
752 \f
753 ;;;; numeric DERIVE-TYPE methods
754
755 ;;; a utility for defining derive-type methods of integer operations. If
756 ;;; the types of both X and Y are integer types, then we compute a new
757 ;;; integer type with bounds determined Fun when applied to X and Y.
758 ;;; Otherwise, we use Numeric-Contagion.
759 (defun derive-integer-type (x y fun)
760   (declare (type continuation x y) (type function fun))
761   (let ((x (continuation-type x))
762         (y (continuation-type y)))
763     (if (and (numeric-type-p x) (numeric-type-p y)
764              (eq (numeric-type-class x) 'integer)
765              (eq (numeric-type-class y) 'integer)
766              (eq (numeric-type-complexp x) :real)
767              (eq (numeric-type-complexp y) :real))
768         (multiple-value-bind (low high) (funcall fun x y)
769           (make-numeric-type :class 'integer
770                              :complexp :real
771                              :low low
772                              :high high))
773         (numeric-contagion x y))))
774
775 ;;; simple utility to flatten a list
776 (defun flatten-list (x)
777   (labels ((flatten-helper (x r);; 'r' is the stuff to the 'right'.
778              (cond ((null x) r)
779                    ((atom x)
780                     (cons x r))
781                    (t (flatten-helper (car x)
782                                       (flatten-helper (cdr x) r))))))
783     (flatten-helper x nil)))
784
785 ;;; Take some type of continuation and massage it so that we get a
786 ;;; list of the constituent types. If ARG is *EMPTY-TYPE*, return NIL
787 ;;; to indicate failure.
788 (defun prepare-arg-for-derive-type (arg)
789   (flet ((listify (arg)
790            (typecase arg
791              (numeric-type
792               (list arg))
793              (union-type
794               (union-type-types arg))
795              (t
796               (list arg)))))
797     (unless (eq arg *empty-type*)
798       ;; Make sure all args are some type of numeric-type. For member
799       ;; types, convert the list of members into a union of equivalent
800       ;; single-element member-type's.
801       (let ((new-args nil))
802         (dolist (arg (listify arg))
803           (if (member-type-p arg)
804               ;; Run down the list of members and convert to a list of
805               ;; member types.
806               (dolist (member (member-type-members arg))
807                 (push (if (numberp member)
808                           (make-member-type :members (list member))
809                           *empty-type*)
810                       new-args))
811               (push arg new-args)))
812         (unless (member *empty-type* new-args)
813           new-args)))))
814
815 ;;; Convert from the standard type convention for which -0.0 and 0.0
816 ;;; are equal to an intermediate convention for which they are
817 ;;; considered different which is more natural for some of the
818 ;;; optimisers.
819 (defun convert-numeric-type (type)
820   (declare (type numeric-type type))
821   ;;; Only convert real float interval delimiters types.
822   (if (eq (numeric-type-complexp type) :real)
823       (let* ((lo (numeric-type-low type))
824              (lo-val (type-bound-number lo))
825              (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
826              (hi (numeric-type-high type))
827              (hi-val (type-bound-number hi))
828              (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
829         (if (or lo-float-zero-p hi-float-zero-p)
830             (make-numeric-type
831              :class (numeric-type-class type)
832              :format (numeric-type-format type)
833              :complexp :real
834              :low (if lo-float-zero-p
835                       (if (consp lo)
836                           (list (float 0.0 lo-val))
837                           (float (load-time-value (make-unportable-float :single-float-negative-zero)) lo-val))
838                       lo)
839              :high (if hi-float-zero-p
840                        (if (consp hi)
841                            (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val))
842                            (float 0.0 hi-val))
843                        hi))
844             type))
845       ;; Not real float.
846       type))
847
848 ;;; Convert back from the intermediate convention for which -0.0 and
849 ;;; 0.0 are considered different to the standard type convention for
850 ;;; which and equal.
851 (defun convert-back-numeric-type (type)
852   (declare (type numeric-type type))
853   ;;; Only convert real float interval delimiters types.
854   (if (eq (numeric-type-complexp type) :real)
855       (let* ((lo (numeric-type-low type))
856              (lo-val (type-bound-number lo))
857              (lo-float-zero-p
858               (and lo (floatp lo-val) (= lo-val 0.0)
859                    (float-sign lo-val)))
860              (hi (numeric-type-high type))
861              (hi-val (type-bound-number hi))
862              (hi-float-zero-p
863               (and hi (floatp hi-val) (= hi-val 0.0)
864                    (float-sign hi-val))))
865         (cond
866           ;; (float +0.0 +0.0) => (member 0.0)
867           ;; (float -0.0 -0.0) => (member -0.0)
868           ((and lo-float-zero-p hi-float-zero-p)
869            ;; shouldn't have exclusive bounds here..
870            (aver (and (not (consp lo)) (not (consp hi))))
871            (if (= lo-float-zero-p hi-float-zero-p)
872                ;; (float +0.0 +0.0) => (member 0.0)
873                ;; (float -0.0 -0.0) => (member -0.0)
874                (specifier-type `(member ,lo-val))
875                ;; (float -0.0 +0.0) => (float 0.0 0.0)
876                ;; (float +0.0 -0.0) => (float 0.0 0.0)
877                (make-numeric-type :class (numeric-type-class type)
878                                   :format (numeric-type-format type)
879                                   :complexp :real
880                                   :low hi-val
881                                   :high hi-val)))
882           (lo-float-zero-p
883            (cond
884              ;; (float -0.0 x) => (float 0.0 x)
885              ((and (not (consp lo)) (minusp lo-float-zero-p))
886               (make-numeric-type :class (numeric-type-class type)
887                                  :format (numeric-type-format type)
888                                  :complexp :real
889                                  :low (float 0.0 lo-val)
890                                  :high hi))
891              ;; (float (+0.0) x) => (float (0.0) x)
892              ((and (consp lo) (plusp lo-float-zero-p))
893               (make-numeric-type :class (numeric-type-class type)
894                                  :format (numeric-type-format type)
895                                  :complexp :real
896                                  :low (list (float 0.0 lo-val))
897                                  :high hi))
898              (t
899               ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
900               ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
901               (list (make-member-type :members (list (float 0.0 lo-val)))
902                     (make-numeric-type :class (numeric-type-class type)
903                                        :format (numeric-type-format type)
904                                        :complexp :real
905                                        :low (list (float 0.0 lo-val))
906                                        :high hi)))))
907           (hi-float-zero-p
908            (cond
909              ;; (float x +0.0) => (float x 0.0)
910              ((and (not (consp hi)) (plusp hi-float-zero-p))
911               (make-numeric-type :class (numeric-type-class type)
912                                  :format (numeric-type-format type)
913                                  :complexp :real
914                                  :low lo
915                                  :high (float 0.0 hi-val)))
916              ;; (float x (-0.0)) => (float x (0.0))
917              ((and (consp hi) (minusp hi-float-zero-p))
918               (make-numeric-type :class (numeric-type-class type)
919                                  :format (numeric-type-format type)
920                                  :complexp :real
921                                  :low lo
922                                  :high (list (float 0.0 hi-val))))
923              (t
924               ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
925               ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
926               (list (make-member-type :members (list (float -0.0 hi-val)))
927                     (make-numeric-type :class (numeric-type-class type)
928                                        :format (numeric-type-format type)
929                                        :complexp :real
930                                        :low lo
931                                        :high (list (float 0.0 hi-val)))))))
932           (t
933            type)))
934       ;; not real float
935       type))
936
937 ;;; Convert back a possible list of numeric types.
938 (defun convert-back-numeric-type-list (type-list)
939   (typecase type-list
940     (list
941      (let ((results '()))
942        (dolist (type type-list)
943          (if (numeric-type-p type)
944              (let ((result (convert-back-numeric-type type)))
945                (if (listp result)
946                    (setf results (append results result))
947                    (push result results)))
948              (push type results)))
949        results))
950     (numeric-type
951      (convert-back-numeric-type type-list))
952     (union-type
953      (convert-back-numeric-type-list (union-type-types type-list)))
954     (t
955      type-list)))
956
957 ;;; FIXME: MAKE-CANONICAL-UNION-TYPE and CONVERT-MEMBER-TYPE probably
958 ;;; belong in the kernel's type logic, invoked always, instead of in
959 ;;; the compiler, invoked only during some type optimizations. (In
960 ;;; fact, as of 0.pre8.100 or so they probably are, under
961 ;;; MAKE-MEMBER-TYPE, so probably this code can be deleted)
962
963 ;;; Take a list of types and return a canonical type specifier,
964 ;;; combining any MEMBER types together. If both positive and negative
965 ;;; MEMBER types are present they are converted to a float type.
966 ;;; XXX This would be far simpler if the type-union methods could handle
967 ;;; member/number unions.
968 (defun make-canonical-union-type (type-list)
969   (let ((members '())
970         (misc-types '()))
971     (dolist (type type-list)
972       (if (member-type-p type)
973           (setf members (union members (member-type-members type)))
974           (push type misc-types)))
975     #!+long-float
976     (when (null (set-difference `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0) members))
977       (push (specifier-type '(long-float 0.0l0 0.0l0)) misc-types)
978       (setf members (set-difference members `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0))))
979     (when (null (set-difference `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0) members))
980       (push (specifier-type '(double-float 0.0d0 0.0d0)) misc-types)
981       (setf members (set-difference members `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0))))
982     (when (null (set-difference `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0) members))
983       (push (specifier-type '(single-float 0.0f0 0.0f0)) misc-types)
984       (setf members (set-difference members `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0))))
985     (if members
986         (apply #'type-union (make-member-type :members members) misc-types)
987         (apply #'type-union misc-types))))
988
989 ;;; Convert a member type with a single member to a numeric type.
990 (defun convert-member-type (arg)
991   (let* ((members (member-type-members arg))
992          (member (first members))
993          (member-type (type-of member)))
994     (aver (not (rest members)))
995     (specifier-type (cond ((typep member 'integer)
996                            `(integer ,member ,member))
997                           ((memq member-type '(short-float single-float
998                                                double-float long-float))
999                            `(,member-type ,member ,member))
1000                           (t
1001                            member-type)))))
1002
1003 ;;; This is used in defoptimizers for computing the resulting type of
1004 ;;; a function.
1005 ;;;
1006 ;;; Given the continuation ARG, derive the resulting type using the
1007 ;;; DERIVE-FUN. DERIVE-FUN takes exactly one argument which is some
1008 ;;; "atomic" continuation type like numeric-type or member-type
1009 ;;; (containing just one element). It should return the resulting
1010 ;;; type, which can be a list of types.
1011 ;;;
1012 ;;; For the case of member types, if a MEMBER-FUN is given it is
1013 ;;; called to compute the result otherwise the member type is first
1014 ;;; converted to a numeric type and the DERIVE-FUN is called.
1015 (defun one-arg-derive-type (arg derive-fun member-fun
1016                                 &optional (convert-type t))
1017   (declare (type function derive-fun)
1018            (type (or null function) member-fun))
1019   (let ((arg-list (prepare-arg-for-derive-type (continuation-type arg))))
1020     (when arg-list
1021       (flet ((deriver (x)
1022                (typecase x
1023                  (member-type
1024                   (if member-fun
1025                       (with-float-traps-masked
1026                           (:underflow :overflow :divide-by-zero)
1027                         (make-member-type
1028                          :members (list
1029                                    (funcall member-fun
1030                                             (first (member-type-members x))))))
1031                       ;; Otherwise convert to a numeric type.
1032                       (let ((result-type-list
1033                              (funcall derive-fun (convert-member-type x))))
1034                         (if convert-type
1035                             (convert-back-numeric-type-list result-type-list)
1036                             result-type-list))))
1037                  (numeric-type
1038                   (if convert-type
1039                       (convert-back-numeric-type-list
1040                        (funcall derive-fun (convert-numeric-type x)))
1041                       (funcall derive-fun x)))
1042                  (t
1043                   *universal-type*))))
1044         ;; Run down the list of args and derive the type of each one,
1045         ;; saving all of the results in a list.
1046         (let ((results nil))
1047           (dolist (arg arg-list)
1048             (let ((result (deriver arg)))
1049               (if (listp result)
1050                   (setf results (append results result))
1051                   (push result results))))
1052           (if (rest results)
1053               (make-canonical-union-type results)
1054               (first results)))))))
1055
1056 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1057 ;;; two arguments. DERIVE-FUN takes 3 args in this case: the two
1058 ;;; original args and a third which is T to indicate if the two args
1059 ;;; really represent the same continuation. This is useful for
1060 ;;; deriving the type of things like (* x x), which should always be
1061 ;;; positive. If we didn't do this, we wouldn't be able to tell.
1062 (defun two-arg-derive-type (arg1 arg2 derive-fun fun
1063                                  &optional (convert-type t))
1064   (declare (type function derive-fun fun))
1065   (flet ((deriver (x y same-arg)
1066            (cond ((and (member-type-p x) (member-type-p y))
1067                   (let* ((x (first (member-type-members x)))
1068                          (y (first (member-type-members y)))
1069                          (result (with-float-traps-masked
1070                                      (:underflow :overflow :divide-by-zero
1071                                       :invalid)
1072                                    (funcall fun x y))))
1073                     (cond ((null result))
1074                           ((and (floatp result) (float-nan-p result))
1075                            (make-numeric-type :class 'float
1076                                               :format (type-of result)
1077                                               :complexp :real))
1078                           (t
1079                            (make-member-type :members (list result))))))
1080                  ((and (member-type-p x) (numeric-type-p y))
1081                   (let* ((x (convert-member-type x))
1082                          (y (if convert-type (convert-numeric-type y) y))
1083                          (result (funcall derive-fun x y same-arg)))
1084                     (if convert-type
1085                         (convert-back-numeric-type-list result)
1086                         result)))
1087                  ((and (numeric-type-p x) (member-type-p y))
1088                   (let* ((x (if convert-type (convert-numeric-type x) x))
1089                          (y (convert-member-type y))
1090                          (result (funcall derive-fun x y same-arg)))
1091                     (if convert-type
1092                         (convert-back-numeric-type-list result)
1093                         result)))
1094                  ((and (numeric-type-p x) (numeric-type-p y))
1095                   (let* ((x (if convert-type (convert-numeric-type x) x))
1096                          (y (if convert-type (convert-numeric-type y) y))
1097                          (result (funcall derive-fun x y same-arg)))
1098                     (if convert-type
1099                         (convert-back-numeric-type-list result)
1100                         result)))
1101                  (t
1102                   *universal-type*))))
1103     (let ((same-arg (same-leaf-ref-p arg1 arg2))
1104           (a1 (prepare-arg-for-derive-type (continuation-type arg1)))
1105           (a2 (prepare-arg-for-derive-type (continuation-type arg2))))
1106       (when (and a1 a2)
1107         (let ((results nil))
1108           (if same-arg
1109               ;; Since the args are the same continuation, just run
1110               ;; down the lists.
1111               (dolist (x a1)
1112                 (let ((result (deriver x x same-arg)))
1113                   (if (listp result)
1114                       (setf results (append results result))
1115                       (push result results))))
1116               ;; Try all pairwise combinations.
1117               (dolist (x a1)
1118                 (dolist (y a2)
1119                   (let ((result (or (deriver x y same-arg)
1120                                     (numeric-contagion x y))))
1121                     (if (listp result)
1122                         (setf results (append results result))
1123                         (push result results))))))
1124           (if (rest results)
1125               (make-canonical-union-type results)
1126               (first results)))))))
1127 \f
1128 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1129 (progn
1130 (defoptimizer (+ derive-type) ((x y))
1131   (derive-integer-type
1132    x y
1133    #'(lambda (x y)
1134        (flet ((frob (x y)
1135                 (if (and x y)
1136                     (+ x y)
1137                     nil)))
1138          (values (frob (numeric-type-low x) (numeric-type-low y))
1139                  (frob (numeric-type-high x) (numeric-type-high y)))))))
1140
1141 (defoptimizer (- derive-type) ((x y))
1142   (derive-integer-type
1143    x y
1144    #'(lambda (x y)
1145        (flet ((frob (x y)
1146                 (if (and x y)
1147                     (- x y)
1148                     nil)))
1149          (values (frob (numeric-type-low x) (numeric-type-high y))
1150                  (frob (numeric-type-high x) (numeric-type-low y)))))))
1151
1152 (defoptimizer (* derive-type) ((x y))
1153   (derive-integer-type
1154    x y
1155    #'(lambda (x y)
1156        (let ((x-low (numeric-type-low x))
1157              (x-high (numeric-type-high x))
1158              (y-low (numeric-type-low y))
1159              (y-high (numeric-type-high y)))
1160          (cond ((not (and x-low y-low))
1161                 (values nil nil))
1162                ((or (minusp x-low) (minusp y-low))
1163                 (if (and x-high y-high)
1164                     (let ((max (* (max (abs x-low) (abs x-high))
1165                                   (max (abs y-low) (abs y-high)))))
1166                       (values (- max) max))
1167                     (values nil nil)))
1168                (t
1169                 (values (* x-low y-low)
1170                         (if (and x-high y-high)
1171                             (* x-high y-high)
1172                             nil))))))))
1173
1174 (defoptimizer (/ derive-type) ((x y))
1175   (numeric-contagion (continuation-type x) (continuation-type y)))
1176
1177 ) ; PROGN
1178
1179 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1180 (progn
1181 (defun +-derive-type-aux (x y same-arg)
1182   (if (and (numeric-type-real-p x)
1183            (numeric-type-real-p y))
1184       (let ((result
1185              (if same-arg
1186                  (let ((x-int (numeric-type->interval x)))
1187                    (interval-add x-int x-int))
1188                  (interval-add (numeric-type->interval x)
1189                                (numeric-type->interval y))))
1190             (result-type (numeric-contagion x y)))
1191         ;; If the result type is a float, we need to be sure to coerce
1192         ;; the bounds into the correct type.
1193         (when (eq (numeric-type-class result-type) 'float)
1194           (setf result (interval-func
1195                         #'(lambda (x)
1196                             (coerce x (or (numeric-type-format result-type)
1197                                           'float)))
1198                         result)))
1199         (make-numeric-type
1200          :class (if (and (eq (numeric-type-class x) 'integer)
1201                          (eq (numeric-type-class y) 'integer))
1202                     ;; The sum of integers is always an integer.
1203                     'integer
1204                     (numeric-type-class result-type))
1205          :format (numeric-type-format result-type)
1206          :low (interval-low result)
1207          :high (interval-high result)))
1208       ;; general contagion
1209       (numeric-contagion x y)))
1210
1211 (defoptimizer (+ derive-type) ((x y))
1212   (two-arg-derive-type x y #'+-derive-type-aux #'+))
1213
1214 (defun --derive-type-aux (x y same-arg)
1215   (if (and (numeric-type-real-p x)
1216            (numeric-type-real-p y))
1217       (let ((result
1218              ;; (- X X) is always 0.
1219              (if same-arg
1220                  (make-interval :low 0 :high 0)
1221                  (interval-sub (numeric-type->interval x)
1222                                (numeric-type->interval y))))
1223             (result-type (numeric-contagion x y)))
1224         ;; If the result type is a float, we need to be sure to coerce
1225         ;; the bounds into the correct type.
1226         (when (eq (numeric-type-class result-type) 'float)
1227           (setf result (interval-func
1228                         #'(lambda (x)
1229                             (coerce x (or (numeric-type-format result-type)
1230                                           'float)))
1231                         result)))
1232         (make-numeric-type
1233          :class (if (and (eq (numeric-type-class x) 'integer)
1234                          (eq (numeric-type-class y) 'integer))
1235                     ;; The difference of integers is always an integer.
1236                     'integer
1237                     (numeric-type-class result-type))
1238          :format (numeric-type-format result-type)
1239          :low (interval-low result)
1240          :high (interval-high result)))
1241       ;; general contagion
1242       (numeric-contagion x y)))
1243
1244 (defoptimizer (- derive-type) ((x y))
1245   (two-arg-derive-type x y #'--derive-type-aux #'-))
1246
1247 (defun *-derive-type-aux (x y same-arg)
1248   (if (and (numeric-type-real-p x)
1249            (numeric-type-real-p y))
1250       (let ((result
1251              ;; (* X X) is always positive, so take care to do it right.
1252              (if same-arg
1253                  (interval-sqr (numeric-type->interval x))
1254                  (interval-mul (numeric-type->interval x)
1255                                (numeric-type->interval y))))
1256             (result-type (numeric-contagion x y)))
1257         ;; If the result type is a float, we need to be sure to coerce
1258         ;; the bounds into the correct type.
1259         (when (eq (numeric-type-class result-type) 'float)
1260           (setf result (interval-func
1261                         #'(lambda (x)
1262                             (coerce x (or (numeric-type-format result-type)
1263                                           'float)))
1264                         result)))
1265         (make-numeric-type
1266          :class (if (and (eq (numeric-type-class x) 'integer)
1267                          (eq (numeric-type-class y) 'integer))
1268                     ;; The product of integers is always an integer.
1269                     'integer
1270                     (numeric-type-class result-type))
1271          :format (numeric-type-format result-type)
1272          :low (interval-low result)
1273          :high (interval-high result)))
1274       (numeric-contagion x y)))
1275
1276 (defoptimizer (* derive-type) ((x y))
1277   (two-arg-derive-type x y #'*-derive-type-aux #'*))
1278
1279 (defun /-derive-type-aux (x y same-arg)
1280   (if (and (numeric-type-real-p x)
1281            (numeric-type-real-p y))
1282       (let ((result
1283              ;; (/ X X) is always 1, except if X can contain 0. In
1284              ;; that case, we shouldn't optimize the division away
1285              ;; because we want 0/0 to signal an error.
1286              (if (and same-arg
1287                       (not (interval-contains-p
1288                             0 (interval-closure (numeric-type->interval y)))))
1289                  (make-interval :low 1 :high 1)
1290                  (interval-div (numeric-type->interval x)
1291                                (numeric-type->interval y))))
1292             (result-type (numeric-contagion x y)))
1293         ;; If the result type is a float, we need to be sure to coerce
1294         ;; the bounds into the correct type.
1295         (when (eq (numeric-type-class result-type) 'float)
1296           (setf result (interval-func
1297                         #'(lambda (x)
1298                             (coerce x (or (numeric-type-format result-type)
1299                                           'float)))
1300                         result)))
1301         (make-numeric-type :class (numeric-type-class result-type)
1302                            :format (numeric-type-format result-type)
1303                            :low (interval-low result)
1304                            :high (interval-high result)))
1305       (numeric-contagion x y)))
1306
1307 (defoptimizer (/ derive-type) ((x y))
1308   (two-arg-derive-type x y #'/-derive-type-aux #'/))
1309
1310 ) ; PROGN
1311
1312 (defun ash-derive-type-aux (n-type shift same-arg)
1313   (declare (ignore same-arg))
1314   ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1315   ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1316   ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1317   ;; two bignums yielding zero) and it's hard to avoid that
1318   ;; calculation in here.
1319   #+(and cmu sb-xc-host)
1320   (when (and (or (typep (numeric-type-low n-type) 'bignum)
1321                  (typep (numeric-type-high n-type) 'bignum))
1322              (or (typep (numeric-type-low shift) 'bignum)
1323                  (typep (numeric-type-high shift) 'bignum)))
1324     (return-from ash-derive-type-aux *universal-type*))
1325   (flet ((ash-outer (n s)
1326            (when (and (fixnump s)
1327                       (<= s 64)
1328                       (> s sb!xc:most-negative-fixnum))
1329              (ash n s)))
1330          ;; KLUDGE: The bare 64's here should be related to
1331          ;; symbolic machine word size values somehow.
1332
1333          (ash-inner (n s)
1334            (if (and (fixnump s)
1335                     (> s sb!xc:most-negative-fixnum))
1336              (ash n (min s 64))
1337              (if (minusp n) -1 0))))
1338     (or (and (csubtypep n-type (specifier-type 'integer))
1339              (csubtypep shift (specifier-type 'integer))
1340              (let ((n-low (numeric-type-low n-type))
1341                    (n-high (numeric-type-high n-type))
1342                    (s-low (numeric-type-low shift))
1343                    (s-high (numeric-type-high shift)))
1344                (make-numeric-type :class 'integer  :complexp :real
1345                                   :low (when n-low
1346                                          (if (minusp n-low)
1347                                            (ash-outer n-low s-high)
1348                                            (ash-inner n-low s-low)))
1349                                   :high (when n-high
1350                                           (if (minusp n-high)
1351                                             (ash-inner n-high s-low)
1352                                             (ash-outer n-high s-high))))))
1353         *universal-type*)))
1354
1355 (defoptimizer (ash derive-type) ((n shift))
1356   (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1357
1358 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1359 (macrolet ((frob (fun)
1360              `#'(lambda (type type2)
1361                   (declare (ignore type2))
1362                   (let ((lo (numeric-type-low type))
1363                         (hi (numeric-type-high type)))
1364                     (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1365
1366   (defoptimizer (%negate derive-type) ((num))
1367     (derive-integer-type num num (frob -))))
1368
1369 (defoptimizer (lognot derive-type) ((int))
1370   (derive-integer-type int int
1371                        (lambda (type type2)
1372                          (declare (ignore type2))
1373                          (let ((lo (numeric-type-low type))
1374                                (hi (numeric-type-high type)))
1375                            (values (if hi (lognot hi) nil)
1376                                    (if lo (lognot lo) nil)
1377                                    (numeric-type-class type)
1378                                    (numeric-type-format type))))))
1379
1380 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1381 (defoptimizer (%negate derive-type) ((num))
1382   (flet ((negate-bound (b)
1383            (and b
1384                 (set-bound (- (type-bound-number b))
1385                            (consp b)))))
1386     (one-arg-derive-type num
1387                          (lambda (type)
1388                            (modified-numeric-type
1389                             type
1390                             :low (negate-bound (numeric-type-high type))
1391                             :high (negate-bound (numeric-type-low type))))
1392                          #'-)))
1393
1394 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1395 (defoptimizer (abs derive-type) ((num))
1396   (let ((type (continuation-type num)))
1397     (if (and (numeric-type-p type)
1398              (eq (numeric-type-class type) 'integer)
1399              (eq (numeric-type-complexp type) :real))
1400         (let ((lo (numeric-type-low type))
1401               (hi (numeric-type-high type)))
1402           (make-numeric-type :class 'integer :complexp :real
1403                              :low (cond ((and hi (minusp hi))
1404                                          (abs hi))
1405                                         (lo
1406                                          (max 0 lo))
1407                                         (t
1408                                          0))
1409                              :high (if (and hi lo)
1410                                        (max (abs hi) (abs lo))
1411                                        nil)))
1412         (numeric-contagion type type))))
1413
1414 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1415 (defun abs-derive-type-aux (type)
1416   (cond ((eq (numeric-type-complexp type) :complex)
1417          ;; The absolute value of a complex number is always a
1418          ;; non-negative float.
1419          (let* ((format (case (numeric-type-class type)
1420                           ((integer rational) 'single-float)
1421                           (t (numeric-type-format type))))
1422                 (bound-format (or format 'float)))
1423            (make-numeric-type :class 'float
1424                               :format format
1425                               :complexp :real
1426                               :low (coerce 0 bound-format)
1427                               :high nil)))
1428         (t
1429          ;; The absolute value of a real number is a non-negative real
1430          ;; of the same type.
1431          (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1432                 (class (numeric-type-class type))
1433                 (format (numeric-type-format type))
1434                 (bound-type (or format class 'real)))
1435            (make-numeric-type
1436             :class class
1437             :format format
1438             :complexp :real
1439             :low (coerce-numeric-bound (interval-low abs-bnd) bound-type)
1440             :high (coerce-numeric-bound
1441                    (interval-high abs-bnd) bound-type))))))
1442
1443 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1444 (defoptimizer (abs derive-type) ((num))
1445   (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1446
1447 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1448 (defoptimizer (truncate derive-type) ((number divisor))
1449   (let ((number-type (continuation-type number))
1450         (divisor-type (continuation-type divisor))
1451         (integer-type (specifier-type 'integer)))
1452     (if (and (numeric-type-p number-type)
1453              (csubtypep number-type integer-type)
1454              (numeric-type-p divisor-type)
1455              (csubtypep divisor-type integer-type))
1456         (let ((number-low (numeric-type-low number-type))
1457               (number-high (numeric-type-high number-type))
1458               (divisor-low (numeric-type-low divisor-type))
1459               (divisor-high (numeric-type-high divisor-type)))
1460           (values-specifier-type
1461            `(values ,(integer-truncate-derive-type number-low number-high
1462                                                    divisor-low divisor-high)
1463                     ,(integer-rem-derive-type number-low number-high
1464                                               divisor-low divisor-high))))
1465         *universal-type*)))
1466
1467 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1468 (progn
1469
1470 (defun rem-result-type (number-type divisor-type)
1471   ;; Figure out what the remainder type is. The remainder is an
1472   ;; integer if both args are integers; a rational if both args are
1473   ;; rational; and a float otherwise.
1474   (cond ((and (csubtypep number-type (specifier-type 'integer))
1475               (csubtypep divisor-type (specifier-type 'integer)))
1476          'integer)
1477         ((and (csubtypep number-type (specifier-type 'rational))
1478               (csubtypep divisor-type (specifier-type 'rational)))
1479          'rational)
1480         ((and (csubtypep number-type (specifier-type 'float))
1481               (csubtypep divisor-type (specifier-type 'float)))
1482          ;; Both are floats so the result is also a float, of
1483          ;; the largest type.
1484          (or (float-format-max (numeric-type-format number-type)
1485                                (numeric-type-format divisor-type))
1486              'float))
1487         ((and (csubtypep number-type (specifier-type 'float))
1488               (csubtypep divisor-type (specifier-type 'rational)))
1489          ;; One of the arguments is a float and the other is a
1490          ;; rational. The remainder is a float of the same
1491          ;; type.
1492          (or (numeric-type-format number-type) 'float))
1493         ((and (csubtypep divisor-type (specifier-type 'float))
1494               (csubtypep number-type (specifier-type 'rational)))
1495          ;; One of the arguments is a float and the other is a
1496          ;; rational. The remainder is a float of the same
1497          ;; type.
1498          (or (numeric-type-format divisor-type) 'float))
1499         (t
1500          ;; Some unhandled combination. This usually means both args
1501          ;; are REAL so the result is a REAL.
1502          'real)))
1503
1504 (defun truncate-derive-type-quot (number-type divisor-type)
1505   (let* ((rem-type (rem-result-type number-type divisor-type))
1506          (number-interval (numeric-type->interval number-type))
1507          (divisor-interval (numeric-type->interval divisor-type)))
1508     ;;(declare (type (member '(integer rational float)) rem-type))
1509     ;; We have real numbers now.
1510     (cond ((eq rem-type 'integer)
1511            ;; Since the remainder type is INTEGER, both args are
1512            ;; INTEGERs.
1513            (let* ((res (integer-truncate-derive-type
1514                         (interval-low number-interval)
1515                         (interval-high number-interval)
1516                         (interval-low divisor-interval)
1517                         (interval-high divisor-interval))))
1518              (specifier-type (if (listp res) res 'integer))))
1519           (t
1520            (let ((quot (truncate-quotient-bound
1521                         (interval-div number-interval
1522                                       divisor-interval))))
1523              (specifier-type `(integer ,(or (interval-low quot) '*)
1524                                        ,(or (interval-high quot) '*))))))))
1525
1526 (defun truncate-derive-type-rem (number-type divisor-type)
1527   (let* ((rem-type (rem-result-type number-type divisor-type))
1528          (number-interval (numeric-type->interval number-type))
1529          (divisor-interval (numeric-type->interval divisor-type))
1530          (rem (truncate-rem-bound number-interval divisor-interval)))
1531     ;;(declare (type (member '(integer rational float)) rem-type))
1532     ;; We have real numbers now.
1533     (cond ((eq rem-type 'integer)
1534            ;; Since the remainder type is INTEGER, both args are
1535            ;; INTEGERs.
1536            (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1537                                        ,(or (interval-high rem) '*))))
1538           (t
1539            (multiple-value-bind (class format)
1540                (ecase rem-type
1541                  (integer
1542                   (values 'integer nil))
1543                  (rational
1544                   (values 'rational nil))
1545                  ((or single-float double-float #!+long-float long-float)
1546                   (values 'float rem-type))
1547                  (float
1548                   (values 'float nil))
1549                  (real
1550                   (values nil nil)))
1551              (when (member rem-type '(float single-float double-float
1552                                             #!+long-float long-float))
1553                (setf rem (interval-func #'(lambda (x)
1554                                             (coerce x rem-type))
1555                                         rem)))
1556              (make-numeric-type :class class
1557                                 :format format
1558                                 :low (interval-low rem)
1559                                 :high (interval-high rem)))))))
1560
1561 (defun truncate-derive-type-quot-aux (num div same-arg)
1562   (declare (ignore same-arg))
1563   (if (and (numeric-type-real-p num)
1564            (numeric-type-real-p div))
1565       (truncate-derive-type-quot num div)
1566       *empty-type*))
1567
1568 (defun truncate-derive-type-rem-aux (num div same-arg)
1569   (declare (ignore same-arg))
1570   (if (and (numeric-type-real-p num)
1571            (numeric-type-real-p div))
1572       (truncate-derive-type-rem num div)
1573       *empty-type*))
1574
1575 (defoptimizer (truncate derive-type) ((number divisor))
1576   (let ((quot (two-arg-derive-type number divisor
1577                                    #'truncate-derive-type-quot-aux #'truncate))
1578         (rem (two-arg-derive-type number divisor
1579                                   #'truncate-derive-type-rem-aux #'rem)))
1580     (when (and quot rem)
1581       (make-values-type :required (list quot rem)))))
1582
1583 (defun ftruncate-derive-type-quot (number-type divisor-type)
1584   ;; The bounds are the same as for truncate. However, the first
1585   ;; result is a float of some type. We need to determine what that
1586   ;; type is. Basically it's the more contagious of the two types.
1587   (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1588         (res-type (numeric-contagion number-type divisor-type)))
1589     (make-numeric-type :class 'float
1590                        :format (numeric-type-format res-type)
1591                        :low (numeric-type-low q-type)
1592                        :high (numeric-type-high q-type))))
1593
1594 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1595   (declare (ignore same-arg))
1596   (if (and (numeric-type-real-p n)
1597            (numeric-type-real-p d))
1598       (ftruncate-derive-type-quot n d)
1599       *empty-type*))
1600
1601 (defoptimizer (ftruncate derive-type) ((number divisor))
1602   (let ((quot
1603          (two-arg-derive-type number divisor
1604                               #'ftruncate-derive-type-quot-aux #'ftruncate))
1605         (rem (two-arg-derive-type number divisor
1606                                   #'truncate-derive-type-rem-aux #'rem)))
1607     (when (and quot rem)
1608       (make-values-type :required (list quot rem)))))
1609
1610 (defun %unary-truncate-derive-type-aux (number)
1611   (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1612
1613 (defoptimizer (%unary-truncate derive-type) ((number))
1614   (one-arg-derive-type number
1615                        #'%unary-truncate-derive-type-aux
1616                        #'%unary-truncate))
1617
1618 ;;; Define optimizers for FLOOR and CEILING.
1619 (macrolet
1620     ((def (name q-name r-name)
1621        (let ((q-aux (symbolicate q-name "-AUX"))
1622              (r-aux (symbolicate r-name "-AUX")))
1623          `(progn
1624            ;; Compute type of quotient (first) result.
1625            (defun ,q-aux (number-type divisor-type)
1626              (let* ((number-interval
1627                      (numeric-type->interval number-type))
1628                     (divisor-interval
1629                      (numeric-type->interval divisor-type))
1630                     (quot (,q-name (interval-div number-interval
1631                                                  divisor-interval))))
1632                (specifier-type `(integer ,(or (interval-low quot) '*)
1633                                          ,(or (interval-high quot) '*)))))
1634            ;; Compute type of remainder.
1635            (defun ,r-aux (number-type divisor-type)
1636              (let* ((divisor-interval
1637                      (numeric-type->interval divisor-type))
1638                     (rem (,r-name divisor-interval))
1639                     (result-type (rem-result-type number-type divisor-type)))
1640                (multiple-value-bind (class format)
1641                    (ecase result-type
1642                      (integer
1643                       (values 'integer nil))
1644                      (rational
1645                       (values 'rational nil))
1646                      ((or single-float double-float #!+long-float long-float)
1647                       (values 'float result-type))
1648                      (float
1649                       (values 'float nil))
1650                      (real
1651                       (values nil nil)))
1652                  (when (member result-type '(float single-float double-float
1653                                              #!+long-float long-float))
1654                    ;; Make sure that the limits on the interval have
1655                    ;; the right type.
1656                    (setf rem (interval-func (lambda (x)
1657                                               (coerce x result-type))
1658                                             rem)))
1659                  (make-numeric-type :class class
1660                                     :format format
1661                                     :low (interval-low rem)
1662                                     :high (interval-high rem)))))
1663            ;; the optimizer itself
1664            (defoptimizer (,name derive-type) ((number divisor))
1665              (flet ((derive-q (n d same-arg)
1666                       (declare (ignore same-arg))
1667                       (if (and (numeric-type-real-p n)
1668                                (numeric-type-real-p d))
1669                           (,q-aux n d)
1670                           *empty-type*))
1671                     (derive-r (n d same-arg)
1672                       (declare (ignore same-arg))
1673                       (if (and (numeric-type-real-p n)
1674                                (numeric-type-real-p d))
1675                           (,r-aux n d)
1676                           *empty-type*)))
1677                (let ((quot (two-arg-derive-type
1678                             number divisor #'derive-q #',name))
1679                      (rem (two-arg-derive-type
1680                            number divisor #'derive-r #'mod)))
1681                  (when (and quot rem)
1682                    (make-values-type :required (list quot rem))))))))))
1683
1684   (def floor floor-quotient-bound floor-rem-bound)
1685   (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1686
1687 ;;; Define optimizers for FFLOOR and FCEILING
1688 (macrolet ((def (name q-name r-name)
1689              (let ((q-aux (symbolicate "F" q-name "-AUX"))
1690                    (r-aux (symbolicate r-name "-AUX")))
1691                `(progn
1692                   ;; Compute type of quotient (first) result.
1693                   (defun ,q-aux (number-type divisor-type)
1694                     (let* ((number-interval
1695                             (numeric-type->interval number-type))
1696                            (divisor-interval
1697                             (numeric-type->interval divisor-type))
1698                            (quot (,q-name (interval-div number-interval
1699                                                         divisor-interval)))
1700                            (res-type (numeric-contagion number-type
1701                                                         divisor-type)))
1702                       (make-numeric-type
1703                        :class (numeric-type-class res-type)
1704                        :format (numeric-type-format res-type)
1705                        :low  (interval-low quot)
1706                        :high (interval-high quot))))
1707
1708                   (defoptimizer (,name derive-type) ((number divisor))
1709                     (flet ((derive-q (n d same-arg)
1710                              (declare (ignore same-arg))
1711                              (if (and (numeric-type-real-p n)
1712                                       (numeric-type-real-p d))
1713                                  (,q-aux n d)
1714                                  *empty-type*))
1715                            (derive-r (n d same-arg)
1716                              (declare (ignore same-arg))
1717                              (if (and (numeric-type-real-p n)
1718                                       (numeric-type-real-p d))
1719                                  (,r-aux n d)
1720                                  *empty-type*)))
1721                       (let ((quot (two-arg-derive-type
1722                                    number divisor #'derive-q #',name))
1723                             (rem (two-arg-derive-type
1724                                   number divisor #'derive-r #'mod)))
1725                         (when (and quot rem)
1726                           (make-values-type :required (list quot rem))))))))))
1727
1728   (def ffloor floor-quotient-bound floor-rem-bound)
1729   (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1730
1731 ;;; functions to compute the bounds on the quotient and remainder for
1732 ;;; the FLOOR function
1733 (defun floor-quotient-bound (quot)
1734   ;; Take the floor of the quotient and then massage it into what we
1735   ;; need.
1736   (let ((lo (interval-low quot))
1737         (hi (interval-high quot)))
1738     ;; Take the floor of the lower bound. The result is always a
1739     ;; closed lower bound.
1740     (setf lo (if lo
1741                  (floor (type-bound-number lo))
1742                  nil))
1743     ;; For the upper bound, we need to be careful.
1744     (setf hi
1745           (cond ((consp hi)
1746                  ;; An open bound. We need to be careful here because
1747                  ;; the floor of '(10.0) is 9, but the floor of
1748                  ;; 10.0 is 10.
1749                  (multiple-value-bind (q r) (floor (first hi))
1750                    (if (zerop r)
1751                        (1- q)
1752                        q)))
1753                 (hi
1754                  ;; A closed bound, so the answer is obvious.
1755                  (floor hi))
1756                 (t
1757                  hi)))
1758     (make-interval :low lo :high hi)))
1759 (defun floor-rem-bound (div)
1760   ;; The remainder depends only on the divisor. Try to get the
1761   ;; correct sign for the remainder if we can.
1762   (case (interval-range-info div)
1763     (+
1764      ;; The divisor is always positive.
1765      (let ((rem (interval-abs div)))
1766        (setf (interval-low rem) 0)
1767        (when (and (numberp (interval-high rem))
1768                   (not (zerop (interval-high rem))))
1769          ;; The remainder never contains the upper bound. However,
1770          ;; watch out for the case where the high limit is zero!
1771          (setf (interval-high rem) (list (interval-high rem))))
1772        rem))
1773     (-
1774      ;; The divisor is always negative.
1775      (let ((rem (interval-neg (interval-abs div))))
1776        (setf (interval-high rem) 0)
1777        (when (numberp (interval-low rem))
1778          ;; The remainder never contains the lower bound.
1779          (setf (interval-low rem) (list (interval-low rem))))
1780        rem))
1781     (otherwise
1782      ;; The divisor can be positive or negative. All bets off. The
1783      ;; magnitude of remainder is the maximum value of the divisor.
1784      (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1785        ;; The bound never reaches the limit, so make the interval open.
1786        (make-interval :low (if limit
1787                                (list (- limit))
1788                                limit)
1789                       :high (list limit))))))
1790 #| Test cases
1791 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
1792 => #S(INTERVAL :LOW 0 :HIGH 10)
1793 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1794 => #S(INTERVAL :LOW 0 :HIGH 10)
1795 (floor-quotient-bound (make-interval :low 0.3 :high 10))
1796 => #S(INTERVAL :LOW 0 :HIGH 10)
1797 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
1798 => #S(INTERVAL :LOW 0 :HIGH 9)
1799 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
1800 => #S(INTERVAL :LOW 0 :HIGH 10)
1801 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
1802 => #S(INTERVAL :LOW 0 :HIGH 10)
1803 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1804 => #S(INTERVAL :LOW -2 :HIGH 10)
1805 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1806 => #S(INTERVAL :LOW -1 :HIGH 10)
1807 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
1808 => #S(INTERVAL :LOW -1 :HIGH 10)
1809
1810 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
1811 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1812 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
1813 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1814 (floor-rem-bound (make-interval :low -10 :high -2.3))
1815 #S(INTERVAL :LOW (-10) :HIGH 0)
1816 (floor-rem-bound (make-interval :low 0.3 :high 10))
1817 => #S(INTERVAL :LOW 0 :HIGH '(10))
1818 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
1819 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
1820 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
1821 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1822 |#
1823 \f
1824 ;;; same functions for CEILING
1825 (defun ceiling-quotient-bound (quot)
1826   ;; Take the ceiling of the quotient and then massage it into what we
1827   ;; need.
1828   (let ((lo (interval-low quot))
1829         (hi (interval-high quot)))
1830     ;; Take the ceiling of the upper bound. The result is always a
1831     ;; closed upper bound.
1832     (setf hi (if hi
1833                  (ceiling (type-bound-number hi))
1834                  nil))
1835     ;; For the lower bound, we need to be careful.
1836     (setf lo
1837           (cond ((consp lo)
1838                  ;; An open bound. We need to be careful here because
1839                  ;; the ceiling of '(10.0) is 11, but the ceiling of
1840                  ;; 10.0 is 10.
1841                  (multiple-value-bind (q r) (ceiling (first lo))
1842                    (if (zerop r)
1843                        (1+ q)
1844                        q)))
1845                 (lo
1846                  ;; A closed bound, so the answer is obvious.
1847                  (ceiling lo))
1848                 (t
1849                  lo)))
1850     (make-interval :low lo :high hi)))
1851 (defun ceiling-rem-bound (div)
1852   ;; The remainder depends only on the divisor. Try to get the
1853   ;; correct sign for the remainder if we can.
1854   (case (interval-range-info div)
1855     (+
1856      ;; Divisor is always positive. The remainder is negative.
1857      (let ((rem (interval-neg (interval-abs div))))
1858        (setf (interval-high rem) 0)
1859        (when (and (numberp (interval-low rem))
1860                   (not (zerop (interval-low rem))))
1861          ;; The remainder never contains the upper bound. However,
1862          ;; watch out for the case when the upper bound is zero!
1863          (setf (interval-low rem) (list (interval-low rem))))
1864        rem))
1865     (-
1866      ;; Divisor is always negative. The remainder is positive
1867      (let ((rem (interval-abs div)))
1868        (setf (interval-low rem) 0)
1869        (when (numberp (interval-high rem))
1870          ;; The remainder never contains the lower bound.
1871          (setf (interval-high rem) (list (interval-high rem))))
1872        rem))
1873     (otherwise
1874      ;; The divisor can be positive or negative. All bets off. The
1875      ;; magnitude of remainder is the maximum value of the divisor.
1876      (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1877        ;; The bound never reaches the limit, so make the interval open.
1878        (make-interval :low (if limit
1879                                (list (- limit))
1880                                limit)
1881                       :high (list limit))))))
1882
1883 #| Test cases
1884 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
1885 => #S(INTERVAL :LOW 1 :HIGH 11)
1886 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1887 => #S(INTERVAL :LOW 1 :HIGH 11)
1888 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
1889 => #S(INTERVAL :LOW 1 :HIGH 10)
1890 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
1891 => #S(INTERVAL :LOW 1 :HIGH 10)
1892 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
1893 => #S(INTERVAL :LOW 1 :HIGH 11)
1894 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
1895 => #S(INTERVAL :LOW 1 :HIGH 11)
1896 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1897 => #S(INTERVAL :LOW -1 :HIGH 11)
1898 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1899 => #S(INTERVAL :LOW 0 :HIGH 11)
1900 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
1901 => #S(INTERVAL :LOW -1 :HIGH 11)
1902
1903 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
1904 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
1905 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
1906 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1907 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
1908 => #S(INTERVAL :LOW 0 :HIGH (10))
1909 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
1910 => #S(INTERVAL :LOW (-10) :HIGH 0)
1911 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
1912 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
1913 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
1914 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1915 |#
1916 \f
1917 (defun truncate-quotient-bound (quot)
1918   ;; For positive quotients, truncate is exactly like floor. For
1919   ;; negative quotients, truncate is exactly like ceiling. Otherwise,
1920   ;; it's the union of the two pieces.
1921   (case (interval-range-info quot)
1922     (+
1923      ;; just like FLOOR
1924      (floor-quotient-bound quot))
1925     (-
1926      ;; just like CEILING
1927      (ceiling-quotient-bound quot))
1928     (otherwise
1929      ;; Split the interval into positive and negative pieces, compute
1930      ;; the result for each piece and put them back together.
1931      (destructuring-bind (neg pos) (interval-split 0 quot t t)
1932        (interval-merge-pair (ceiling-quotient-bound neg)
1933                             (floor-quotient-bound pos))))))
1934
1935 (defun truncate-rem-bound (num div)
1936   ;; This is significantly more complicated than FLOOR or CEILING. We
1937   ;; need both the number and the divisor to determine the range. The
1938   ;; basic idea is to split the ranges of NUM and DEN into positive
1939   ;; and negative pieces and deal with each of the four possibilities
1940   ;; in turn.
1941   (case (interval-range-info num)
1942     (+
1943      (case (interval-range-info div)
1944        (+
1945         (floor-rem-bound div))
1946        (-
1947         (ceiling-rem-bound div))
1948        (otherwise
1949         (destructuring-bind (neg pos) (interval-split 0 div t t)
1950           (interval-merge-pair (truncate-rem-bound num neg)
1951                                (truncate-rem-bound num pos))))))
1952     (-
1953      (case (interval-range-info div)
1954        (+
1955         (ceiling-rem-bound div))
1956        (-
1957         (floor-rem-bound div))
1958        (otherwise
1959         (destructuring-bind (neg pos) (interval-split 0 div t t)
1960           (interval-merge-pair (truncate-rem-bound num neg)
1961                                (truncate-rem-bound num pos))))))
1962     (otherwise
1963      (destructuring-bind (neg pos) (interval-split 0 num t t)
1964        (interval-merge-pair (truncate-rem-bound neg div)
1965                             (truncate-rem-bound pos div))))))
1966 ) ; PROGN
1967
1968 ;;; Derive useful information about the range. Returns three values:
1969 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
1970 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
1971 ;;; - The abs of the maximal value if there is one, or nil if it is
1972 ;;;   unbounded.
1973 (defun numeric-range-info (low high)
1974   (cond ((and low (not (minusp low)))
1975          (values '+ low high))
1976         ((and high (not (plusp high)))
1977          (values '- (- high) (if low (- low) nil)))
1978         (t
1979          (values nil 0 (and low high (max (- low) high))))))
1980
1981 (defun integer-truncate-derive-type
1982        (number-low number-high divisor-low divisor-high)
1983   ;; The result cannot be larger in magnitude than the number, but the
1984   ;; sign might change. If we can determine the sign of either the
1985   ;; number or the divisor, we can eliminate some of the cases.
1986   (multiple-value-bind (number-sign number-min number-max)
1987       (numeric-range-info number-low number-high)
1988     (multiple-value-bind (divisor-sign divisor-min divisor-max)
1989         (numeric-range-info divisor-low divisor-high)
1990       (when (and divisor-max (zerop divisor-max))
1991         ;; We've got a problem: guaranteed division by zero.
1992         (return-from integer-truncate-derive-type t))
1993       (when (zerop divisor-min)
1994         ;; We'll assume that they aren't going to divide by zero.
1995         (incf divisor-min))
1996       (cond ((and number-sign divisor-sign)
1997              ;; We know the sign of both.
1998              (if (eq number-sign divisor-sign)
1999                  ;; Same sign, so the result will be positive.
2000                  `(integer ,(if divisor-max
2001                                 (truncate number-min divisor-max)
2002                                 0)
2003                            ,(if number-max
2004                                 (truncate number-max divisor-min)
2005                                 '*))
2006                  ;; Different signs, the result will be negative.
2007                  `(integer ,(if number-max
2008                                 (- (truncate number-max divisor-min))
2009                                 '*)
2010                            ,(if divisor-max
2011                                 (- (truncate number-min divisor-max))
2012                                 0))))
2013             ((eq divisor-sign '+)
2014              ;; The divisor is positive. Therefore, the number will just
2015              ;; become closer to zero.
2016              `(integer ,(if number-low
2017                             (truncate number-low divisor-min)
2018                             '*)
2019                        ,(if number-high
2020                             (truncate number-high divisor-min)
2021                             '*)))
2022             ((eq divisor-sign '-)
2023              ;; The divisor is negative. Therefore, the absolute value of
2024              ;; the number will become closer to zero, but the sign will also
2025              ;; change.
2026              `(integer ,(if number-high
2027                             (- (truncate number-high divisor-min))
2028                             '*)
2029                        ,(if number-low
2030                             (- (truncate number-low divisor-min))
2031                             '*)))
2032             ;; The divisor could be either positive or negative.
2033             (number-max
2034              ;; The number we are dividing has a bound. Divide that by the
2035              ;; smallest posible divisor.
2036              (let ((bound (truncate number-max divisor-min)))
2037                `(integer ,(- bound) ,bound)))
2038             (t
2039              ;; The number we are dividing is unbounded, so we can't tell
2040              ;; anything about the result.
2041              `integer)))))
2042
2043 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2044 (defun integer-rem-derive-type
2045        (number-low number-high divisor-low divisor-high)
2046   (if (and divisor-low divisor-high)
2047       ;; We know the range of the divisor, and the remainder must be
2048       ;; smaller than the divisor. We can tell the sign of the
2049       ;; remainer if we know the sign of the number.
2050       (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2051         `(integer ,(if (or (null number-low)
2052                            (minusp number-low))
2053                        (- divisor-max)
2054                        0)
2055                   ,(if (or (null number-high)
2056                            (plusp number-high))
2057                        divisor-max
2058                        0)))
2059       ;; The divisor is potentially either very positive or very
2060       ;; negative. Therefore, the remainer is unbounded, but we might
2061       ;; be able to tell something about the sign from the number.
2062       `(integer ,(if (and number-low (not (minusp number-low)))
2063                      ;; The number we are dividing is positive.
2064                      ;; Therefore, the remainder must be positive.
2065                      0
2066                      '*)
2067                 ,(if (and number-high (not (plusp number-high)))
2068                      ;; The number we are dividing is negative.
2069                      ;; Therefore, the remainder must be negative.
2070                      0
2071                      '*))))
2072
2073 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2074 (defoptimizer (random derive-type) ((bound &optional state))
2075   (let ((type (continuation-type bound)))
2076     (when (numeric-type-p type)
2077       (let ((class (numeric-type-class type))
2078             (high (numeric-type-high type))
2079             (format (numeric-type-format type)))
2080         (make-numeric-type
2081          :class class
2082          :format format
2083          :low (coerce 0 (or format class 'real))
2084          :high (cond ((not high) nil)
2085                      ((eq class 'integer) (max (1- high) 0))
2086                      ((or (consp high) (zerop high)) high)
2087                      (t `(,high))))))))
2088
2089 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2090 (defun random-derive-type-aux (type)
2091   (let ((class (numeric-type-class type))
2092         (high (numeric-type-high type))
2093         (format (numeric-type-format type)))
2094     (make-numeric-type
2095          :class class
2096          :format format
2097          :low (coerce 0 (or format class 'real))
2098          :high (cond ((not high) nil)
2099                      ((eq class 'integer) (max (1- high) 0))
2100                      ((or (consp high) (zerop high)) high)
2101                      (t `(,high))))))
2102
2103 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2104 (defoptimizer (random derive-type) ((bound &optional state))
2105   (one-arg-derive-type bound #'random-derive-type-aux nil))
2106 \f
2107 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2108
2109 ;;; Return the maximum number of bits an integer of the supplied type
2110 ;;; can take up, or NIL if it is unbounded. The second (third) value
2111 ;;; is T if the integer can be positive (negative) and NIL if not.
2112 ;;; Zero counts as positive.
2113 (defun integer-type-length (type)
2114   (if (numeric-type-p type)
2115       (let ((min (numeric-type-low type))
2116             (max (numeric-type-high type)))
2117         (values (and min max (max (integer-length min) (integer-length max)))
2118                 (or (null max) (not (minusp max)))
2119                 (or (null min) (minusp min))))
2120       (values nil t t)))
2121
2122 (defun logand-derive-type-aux (x y &optional same-leaf)
2123   (declare (ignore same-leaf))
2124   (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2125     (declare (ignore x-pos))
2126     (multiple-value-bind (y-len y-pos y-neg) (integer-type-length  y)
2127       (declare (ignore y-pos))
2128       (if (not x-neg)
2129           ;; X must be positive.
2130           (if (not y-neg)
2131               ;; They must both be positive.
2132               (cond ((or (null x-len) (null y-len))
2133                      (specifier-type 'unsigned-byte))
2134                     ((or (zerop x-len) (zerop y-len))
2135                      (specifier-type '(integer 0 0)))
2136                     (t
2137                      (specifier-type `(unsigned-byte ,(min x-len y-len)))))
2138               ;; X is positive, but Y might be negative.
2139               (cond ((null x-len)
2140                      (specifier-type 'unsigned-byte))
2141                     ((zerop x-len)
2142                      (specifier-type '(integer 0 0)))
2143                     (t
2144                      (specifier-type `(unsigned-byte ,x-len)))))
2145           ;; X might be negative.
2146           (if (not y-neg)
2147               ;; Y must be positive.
2148               (cond ((null y-len)
2149                      (specifier-type 'unsigned-byte))
2150                     ((zerop y-len)
2151                      (specifier-type '(integer 0 0)))
2152                     (t
2153                      (specifier-type
2154                       `(unsigned-byte ,y-len))))
2155               ;; Either might be negative.
2156               (if (and x-len y-len)
2157                   ;; The result is bounded.
2158                   (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2159                   ;; We can't tell squat about the result.
2160                   (specifier-type 'integer)))))))
2161
2162 (defun logior-derive-type-aux (x y &optional same-leaf)
2163   (declare (ignore same-leaf))
2164   (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2165     (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2166       (cond
2167        ((and (not x-neg) (not y-neg))
2168         ;; Both are positive.
2169         (if (and x-len y-len (zerop x-len) (zerop y-len))
2170             (specifier-type '(integer 0 0))
2171             (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2172                                              (max x-len y-len)
2173                                              '*)))))
2174        ((not x-pos)
2175         ;; X must be negative.
2176         (if (not y-pos)
2177             ;; Both are negative. The result is going to be negative
2178             ;; and be the same length or shorter than the smaller.
2179             (if (and x-len y-len)
2180                 ;; It's bounded.
2181                 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2182                 ;; It's unbounded.
2183                 (specifier-type '(integer * -1)))
2184             ;; X is negative, but we don't know about Y. The result
2185             ;; will be negative, but no more negative than X.
2186             (specifier-type
2187              `(integer ,(or (numeric-type-low x) '*)
2188                        -1))))
2189        (t
2190         ;; X might be either positive or negative.
2191         (if (not y-pos)
2192             ;; But Y is negative. The result will be negative.
2193             (specifier-type
2194              `(integer ,(or (numeric-type-low y) '*)
2195                        -1))
2196             ;; We don't know squat about either. It won't get any bigger.
2197             (if (and x-len y-len)
2198                 ;; Bounded.
2199                 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2200                 ;; Unbounded.
2201                 (specifier-type 'integer))))))))
2202
2203 (defun logxor-derive-type-aux (x y &optional same-leaf)
2204   (declare (ignore same-leaf))
2205   (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2206     (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2207       (cond
2208        ((or (and (not x-neg) (not y-neg))
2209             (and (not x-pos) (not y-pos)))
2210         ;; Either both are negative or both are positive. The result
2211         ;; will be positive, and as long as the longer.
2212         (if (and x-len y-len (zerop x-len) (zerop y-len))
2213             (specifier-type '(integer 0 0))
2214             (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2215                                              (max x-len y-len)
2216                                              '*)))))
2217        ((or (and (not x-pos) (not y-neg))
2218             (and (not y-neg) (not y-pos)))
2219         ;; Either X is negative and Y is positive of vice-versa. The
2220         ;; result will be negative.
2221         (specifier-type `(integer ,(if (and x-len y-len)
2222                                        (ash -1 (max x-len y-len))
2223                                        '*)
2224                                   -1)))
2225        ;; We can't tell what the sign of the result is going to be.
2226        ;; All we know is that we don't create new bits.
2227        ((and x-len y-len)
2228         (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2229        (t
2230         (specifier-type 'integer))))))
2231
2232 (macrolet ((deffrob (logfun)
2233              (let ((fun-aux (symbolicate logfun "-DERIVE-TYPE-AUX")))
2234              `(defoptimizer (,logfun derive-type) ((x y))
2235                 (two-arg-derive-type x y #',fun-aux #',logfun)))))
2236   (deffrob logand)
2237   (deffrob logior)
2238   (deffrob logxor))
2239 \f
2240 ;;;; miscellaneous derive-type methods
2241
2242 (defoptimizer (integer-length derive-type) ((x))
2243   (let ((x-type (continuation-type x)))
2244     (when (and (numeric-type-p x-type)
2245                (csubtypep x-type (specifier-type 'integer)))
2246       ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2247       ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically.  Be
2248       ;; careful about LO or HI being NIL, though.  Also, if 0 is
2249       ;; contained in X, the lower bound is obviously 0.
2250       (flet ((null-or-min (a b)
2251                (and a b (min (integer-length a)
2252                              (integer-length b))))
2253              (null-or-max (a b)
2254                (and a b (max (integer-length a)
2255                              (integer-length b)))))
2256         (let* ((min (numeric-type-low x-type))
2257                (max (numeric-type-high x-type))
2258                (min-len (null-or-min min max))
2259                (max-len (null-or-max min max)))
2260           (when (ctypep 0 x-type)
2261             (setf min-len 0))
2262           (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2263
2264 (defoptimizer (code-char derive-type) ((code))
2265   (specifier-type 'base-char))
2266
2267 (defoptimizer (values derive-type) ((&rest values))
2268   (make-values-type :required (mapcar #'continuation-type values)))
2269 \f
2270 ;;;; byte operations
2271 ;;;;
2272 ;;;; We try to turn byte operations into simple logical operations.
2273 ;;;; First, we convert byte specifiers into separate size and position
2274 ;;;; arguments passed to internal %FOO functions. We then attempt to
2275 ;;;; transform the %FOO functions into boolean operations when the
2276 ;;;; size and position are constant and the operands are fixnums.
2277
2278 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2279            ;; expressions that evaluate to the SIZE and POSITION of
2280            ;; the byte-specifier form SPEC. We may wrap a let around
2281            ;; the result of the body to bind some variables.
2282            ;;
2283            ;; If the spec is a BYTE form, then bind the vars to the
2284            ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2285            ;; and BYTE-POSITION. The goal of this transformation is to
2286            ;; avoid consing up byte specifiers and then immediately
2287            ;; throwing them away.
2288            (with-byte-specifier ((size-var pos-var spec) &body body)
2289              (once-only ((spec `(macroexpand ,spec))
2290                          (temp '(gensym)))
2291                         `(if (and (consp ,spec)
2292                                   (eq (car ,spec) 'byte)
2293                                   (= (length ,spec) 3))
2294                         (let ((,size-var (second ,spec))
2295                               (,pos-var (third ,spec)))
2296                           ,@body)
2297                         (let ((,size-var `(byte-size ,,temp))
2298                               (,pos-var `(byte-position ,,temp)))
2299                           `(let ((,,temp ,,spec))
2300                              ,,@body))))))
2301
2302   (define-source-transform ldb (spec int)
2303     (with-byte-specifier (size pos spec)
2304       `(%ldb ,size ,pos ,int)))
2305
2306   (define-source-transform dpb (newbyte spec int)
2307     (with-byte-specifier (size pos spec)
2308       `(%dpb ,newbyte ,size ,pos ,int)))
2309
2310   (define-source-transform mask-field (spec int)
2311     (with-byte-specifier (size pos spec)
2312       `(%mask-field ,size ,pos ,int)))
2313
2314   (define-source-transform deposit-field (newbyte spec int)
2315     (with-byte-specifier (size pos spec)
2316       `(%deposit-field ,newbyte ,size ,pos ,int))))
2317
2318 (defoptimizer (%ldb derive-type) ((size posn num))
2319   (let ((size (continuation-type size)))
2320     (if (and (numeric-type-p size)
2321              (csubtypep size (specifier-type 'integer)))
2322         (let ((size-high (numeric-type-high size)))
2323           (if (and size-high (<= size-high sb!vm:n-word-bits))
2324               (specifier-type `(unsigned-byte ,size-high))
2325               (specifier-type 'unsigned-byte)))
2326         *universal-type*)))
2327
2328 (defoptimizer (%mask-field derive-type) ((size posn num))
2329   (let ((size (continuation-type size))
2330         (posn (continuation-type posn)))
2331     (if (and (numeric-type-p size)
2332              (csubtypep size (specifier-type 'integer))
2333              (numeric-type-p posn)
2334              (csubtypep posn (specifier-type 'integer)))
2335         (let ((size-high (numeric-type-high size))
2336               (posn-high (numeric-type-high posn)))
2337           (if (and size-high posn-high
2338                    (<= (+ size-high posn-high) sb!vm:n-word-bits))
2339               (specifier-type `(unsigned-byte ,(+ size-high posn-high)))
2340               (specifier-type 'unsigned-byte)))
2341         *universal-type*)))
2342
2343 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2344   (let ((size (continuation-type size))
2345         (posn (continuation-type posn))
2346         (int (continuation-type int)))
2347     (if (and (numeric-type-p size)
2348              (csubtypep size (specifier-type 'integer))
2349              (numeric-type-p posn)
2350              (csubtypep posn (specifier-type 'integer))
2351              (numeric-type-p int)
2352              (csubtypep int (specifier-type 'integer)))
2353         (let ((size-high (numeric-type-high size))
2354               (posn-high (numeric-type-high posn))
2355               (high (numeric-type-high int))
2356               (low (numeric-type-low int)))
2357           (if (and size-high posn-high high low
2358                    (<= (+ size-high posn-high) sb!vm:n-word-bits))
2359               (specifier-type
2360                (list (if (minusp low) 'signed-byte 'unsigned-byte)
2361                      (max (integer-length high)
2362                           (integer-length low)
2363                           (+ size-high posn-high))))
2364               *universal-type*))
2365         *universal-type*)))
2366
2367 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2368   (let ((size (continuation-type size))
2369         (posn (continuation-type posn))
2370         (int (continuation-type int)))
2371     (if (and (numeric-type-p size)
2372              (csubtypep size (specifier-type 'integer))
2373              (numeric-type-p posn)
2374              (csubtypep posn (specifier-type 'integer))
2375              (numeric-type-p int)
2376              (csubtypep int (specifier-type 'integer)))
2377         (let ((size-high (numeric-type-high size))
2378               (posn-high (numeric-type-high posn))
2379               (high (numeric-type-high int))
2380               (low (numeric-type-low int)))
2381           (if (and size-high posn-high high low
2382                    (<= (+ size-high posn-high) sb!vm:n-word-bits))
2383               (specifier-type
2384                (list (if (minusp low) 'signed-byte 'unsigned-byte)
2385                      (max (integer-length high)
2386                           (integer-length low)
2387                           (+ size-high posn-high))))
2388               *universal-type*))
2389         *universal-type*)))
2390
2391 (deftransform %ldb ((size posn int)
2392                     (fixnum fixnum integer)
2393                     (unsigned-byte #.sb!vm:n-word-bits))
2394   "convert to inline logical operations"
2395   `(logand (ash int (- posn))
2396            (ash ,(1- (ash 1 sb!vm:n-word-bits))
2397                 (- size ,sb!vm:n-word-bits))))
2398
2399 (deftransform %mask-field ((size posn int)
2400                            (fixnum fixnum integer)
2401                            (unsigned-byte #.sb!vm:n-word-bits))
2402   "convert to inline logical operations"
2403   `(logand int
2404            (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2405                      (- size ,sb!vm:n-word-bits))
2406                 posn)))
2407
2408 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2409 ;;;   (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2410 ;;; as the result type, as that would allow result types that cover
2411 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2412 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2413
2414 (deftransform %dpb ((new size posn int)
2415                     *
2416                     (unsigned-byte #.sb!vm:n-word-bits))
2417   "convert to inline logical operations"
2418   `(let ((mask (ldb (byte size 0) -1)))
2419      (logior (ash (logand new mask) posn)
2420              (logand int (lognot (ash mask posn))))))
2421
2422 (deftransform %dpb ((new size posn int)
2423                     *
2424                     (signed-byte #.sb!vm:n-word-bits))
2425   "convert to inline logical operations"
2426   `(let ((mask (ldb (byte size 0) -1)))
2427      (logior (ash (logand new mask) posn)
2428              (logand int (lognot (ash mask posn))))))
2429
2430 (deftransform %deposit-field ((new size posn int)
2431                               *
2432                               (unsigned-byte #.sb!vm:n-word-bits))
2433   "convert to inline logical operations"
2434   `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2435      (logior (logand new mask)
2436              (logand int (lognot mask)))))
2437
2438 (deftransform %deposit-field ((new size posn int)
2439                               *
2440                               (signed-byte #.sb!vm:n-word-bits))
2441   "convert to inline logical operations"
2442   `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2443      (logior (logand new mask)
2444              (logand int (lognot mask)))))
2445 \f
2446 ;;; Modular functions
2447
2448 ;;; (ldb (byte s 0) (foo                 x  y ...)) =
2449 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2450 ;;;
2451 ;;; and similar for other arguments.
2452
2453 ;;; Try to recursively cut all uses of the continuation CONT to WIDTH
2454 ;;; bits.
2455 ;;;
2456 ;;; For good functions, we just recursively cut arguments; their
2457 ;;; "goodness" means that the result will not increase (in the
2458 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
2459 ;;; replaced with the version, cutting its result to WIDTH or more
2460 ;;; bits. If we have changed anything, we need to flush old derived
2461 ;;; types, because they have nothing in common with the new code.
2462 (defun cut-to-width (cont width)
2463   (declare (type continuation cont) (type (integer 0) width))
2464   (labels ((reoptimize-node (node name)
2465              (setf (node-derived-type node)
2466                    (fun-type-returns
2467                     (info :function :type name)))
2468              (setf (continuation-%derived-type (node-cont node)) nil)
2469              (setf (node-reoptimize node) t)
2470              (setf (block-reoptimize (node-block node)) t)
2471              (setf (component-reoptimize (node-component node)) t))
2472            (cut-node (node &aux did-something)
2473              (when (and (combination-p node)
2474                         (fun-info-p (basic-combination-kind node)))
2475                (let* ((fun-ref (continuation-use (combination-fun node)))
2476                       (fun-name (leaf-source-name (ref-leaf fun-ref)))
2477                       (modular-fun (find-modular-version fun-name width))
2478                       (name (and (modular-fun-info-p modular-fun)
2479                                  (modular-fun-info-name modular-fun))))
2480                  (when (and modular-fun
2481                             (not (and (eq name 'logand)
2482                                       (csubtypep
2483                                        (single-value-type (node-derived-type node))
2484                                        (specifier-type `(unsigned-byte ,width))))))
2485                    (unless (eq modular-fun :good)
2486                      (setq did-something t)
2487                      (change-ref-leaf
2488                         fun-ref
2489                         (find-free-fun name "in a strange place"))
2490                        (setf (combination-kind node) :full))
2491                    (dolist (arg (basic-combination-args node))
2492                      (when (cut-continuation arg)
2493                        (setq did-something t)))
2494                    (when did-something
2495                      (reoptimize-node node fun-name))
2496                    did-something))))
2497            (cut-continuation (cont &aux did-something)
2498              (do-uses (node cont)
2499                (when (cut-node node)
2500                  (setq did-something t)))
2501              did-something))
2502     (cut-continuation cont)))
2503
2504 (defoptimizer (logand optimizer) ((x y) node)
2505   (let ((result-type (single-value-type (node-derived-type node))))
2506     (when (numeric-type-p result-type)
2507       (let ((low (numeric-type-low result-type))
2508             (high (numeric-type-high result-type)))
2509         (when (and (numberp low)
2510                    (numberp high)
2511                    (>= low 0))
2512           (let ((width (integer-length high)))
2513             (when (some (lambda (x) (<= width x))
2514                         *modular-funs-widths*)
2515               ;; FIXME: This should be (CUT-TO-WIDTH NODE WIDTH).
2516               (cut-to-width x width)
2517               (cut-to-width y width)
2518               nil ; After fixing above, replace with T.
2519               )))))))
2520 \f
2521 ;;; miscellanous numeric transforms
2522
2523 ;;; If a constant appears as the first arg, swap the args.
2524 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
2525   (if (and (constant-continuation-p x)
2526            (not (constant-continuation-p y)))
2527       `(,(continuation-fun-name (basic-combination-fun node))
2528         y
2529         ,(continuation-value x))
2530       (give-up-ir1-transform)))
2531
2532 (dolist (x '(= char= + * logior logand logxor))
2533   (%deftransform x '(function * *) #'commutative-arg-swap
2534                  "place constant arg last"))
2535
2536 ;;; Handle the case of a constant BOOLE-CODE.
2537 (deftransform boole ((op x y) * *)
2538   "convert to inline logical operations"
2539   (unless (constant-continuation-p op)
2540     (give-up-ir1-transform "BOOLE code is not a constant."))
2541   (let ((control (continuation-value op)))
2542     (case control
2543       (#.boole-clr 0)
2544       (#.boole-set -1)
2545       (#.boole-1 'x)
2546       (#.boole-2 'y)
2547       (#.boole-c1 '(lognot x))
2548       (#.boole-c2 '(lognot y))
2549       (#.boole-and '(logand x y))
2550       (#.boole-ior '(logior x y))
2551       (#.boole-xor '(logxor x y))
2552       (#.boole-eqv '(logeqv x y))
2553       (#.boole-nand '(lognand x y))
2554       (#.boole-nor '(lognor x y))
2555       (#.boole-andc1 '(logandc1 x y))
2556       (#.boole-andc2 '(logandc2 x y))
2557       (#.boole-orc1 '(logorc1 x y))
2558       (#.boole-orc2 '(logorc2 x y))
2559       (t
2560        (abort-ir1-transform "~S is an illegal control arg to BOOLE."
2561                             control)))))
2562 \f
2563 ;;;; converting special case multiply/divide to shifts
2564
2565 ;;; If arg is a constant power of two, turn * into a shift.
2566 (deftransform * ((x y) (integer integer) *)
2567   "convert x*2^k to shift"
2568   (unless (constant-continuation-p y)
2569     (give-up-ir1-transform))
2570   (let* ((y (continuation-value y))
2571          (y-abs (abs y))
2572          (len (1- (integer-length y-abs))))
2573     (unless (= y-abs (ash 1 len))
2574       (give-up-ir1-transform))
2575     (if (minusp y)
2576         `(- (ash x ,len))
2577         `(ash x ,len))))
2578
2579 ;;; If arg is a constant power of two, turn FLOOR into a shift and
2580 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
2581 ;;; remainder.
2582 (flet ((frob (y ceil-p)
2583          (unless (constant-continuation-p y)
2584            (give-up-ir1-transform))
2585          (let* ((y (continuation-value y))
2586                 (y-abs (abs y))
2587                 (len (1- (integer-length y-abs))))
2588            (unless (= y-abs (ash 1 len))
2589              (give-up-ir1-transform))
2590            (let ((shift (- len))
2591                  (mask (1- y-abs))
2592                  (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
2593              `(let ((x (+ x ,delta)))
2594                 ,(if (minusp y)
2595                      `(values (ash (- x) ,shift)
2596                               (- (- (logand (- x) ,mask)) ,delta))
2597                      `(values (ash x ,shift)
2598                               (- (logand x ,mask) ,delta))))))))
2599   (deftransform floor ((x y) (integer integer) *)
2600     "convert division by 2^k to shift"
2601     (frob y nil))
2602   (deftransform ceiling ((x y) (integer integer) *)
2603     "convert division by 2^k to shift"
2604     (frob y t)))
2605
2606 ;;; Do the same for MOD.
2607 (deftransform mod ((x y) (integer integer) *)
2608   "convert remainder mod 2^k to LOGAND"
2609   (unless (constant-continuation-p y)
2610     (give-up-ir1-transform))
2611   (let* ((y (continuation-value y))
2612          (y-abs (abs y))
2613          (len (1- (integer-length y-abs))))
2614     (unless (= y-abs (ash 1 len))
2615       (give-up-ir1-transform))
2616     (let ((mask (1- y-abs)))
2617       (if (minusp y)
2618           `(- (logand (- x) ,mask))
2619           `(logand x ,mask)))))
2620
2621 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
2622 (deftransform truncate ((x y) (integer integer))
2623   "convert division by 2^k to shift"
2624   (unless (constant-continuation-p y)
2625     (give-up-ir1-transform))
2626   (let* ((y (continuation-value y))
2627          (y-abs (abs y))
2628          (len (1- (integer-length y-abs))))
2629     (unless (= y-abs (ash 1 len))
2630       (give-up-ir1-transform))
2631     (let* ((shift (- len))
2632            (mask (1- y-abs)))
2633       `(if (minusp x)
2634            (values ,(if (minusp y)
2635                         `(ash (- x) ,shift)
2636                         `(- (ash (- x) ,shift)))
2637                    (- (logand (- x) ,mask)))
2638            (values ,(if (minusp y)
2639                         `(- (ash (- x) ,shift))
2640                         `(ash x ,shift))
2641                    (logand x ,mask))))))
2642
2643 ;;; And the same for REM.
2644 (deftransform rem ((x y) (integer integer) *)
2645   "convert remainder mod 2^k to LOGAND"
2646   (unless (constant-continuation-p y)
2647     (give-up-ir1-transform))
2648   (let* ((y (continuation-value y))
2649          (y-abs (abs y))
2650          (len (1- (integer-length y-abs))))
2651     (unless (= y-abs (ash 1 len))
2652       (give-up-ir1-transform))
2653     (let ((mask (1- y-abs)))
2654       `(if (minusp x)
2655            (- (logand (- x) ,mask))
2656            (logand x ,mask)))))
2657 \f
2658 ;;;; arithmetic and logical identity operation elimination
2659
2660 ;;; Flush calls to various arith functions that convert to the
2661 ;;; identity function or a constant.
2662 (macrolet ((def (name identity result)
2663              `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
2664                 "fold identity operations"
2665                 ',result)))
2666   (def ash 0 x)
2667   (def logand -1 x)
2668   (def logand 0 0)
2669   (def logior 0 x)
2670   (def logior -1 -1)
2671   (def logxor -1 (lognot x))
2672   (def logxor 0 x))
2673
2674 (deftransform logand ((x y) (* (constant-arg t)) *)
2675   "fold identity operation"
2676   (let ((y (continuation-value y)))
2677     (unless (and (plusp y)
2678                  (= y (1- (ash 1 (integer-length y)))))
2679       (give-up-ir1-transform))
2680     (unless (csubtypep (continuation-type x)
2681                        (specifier-type `(integer 0 ,y)))
2682       (give-up-ir1-transform))
2683     'x))
2684
2685 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
2686 ;;; (* 0 -4.0) is -0.0.
2687 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
2688   "convert (- 0 x) to negate"
2689   '(%negate y))
2690 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
2691   "convert (* x 0) to 0"
2692   0)
2693
2694 ;;; Return T if in an arithmetic op including continuations X and Y,
2695 ;;; the result type is not affected by the type of X. That is, Y is at
2696 ;;; least as contagious as X.
2697 #+nil
2698 (defun not-more-contagious (x y)
2699   (declare (type continuation x y))
2700   (let ((x (continuation-type x))
2701         (y (continuation-type y)))
2702     (values (type= (numeric-contagion x y)
2703                    (numeric-contagion y y)))))
2704 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
2705 ;;; XXX needs more work as valid transforms are missed; some cases are
2706 ;;; specific to particular transform functions so the use of this
2707 ;;; function may need a re-think.
2708 (defun not-more-contagious (x y)
2709   (declare (type continuation x y))
2710   (flet ((simple-numeric-type (num)
2711            (and (numeric-type-p num)
2712                 ;; Return non-NIL if NUM is integer, rational, or a float
2713                 ;; of some type (but not FLOAT)
2714                 (case (numeric-type-class num)
2715                   ((integer rational)
2716                    t)
2717                   (float
2718                    (numeric-type-format num))
2719                   (t
2720                    nil)))))
2721     (let ((x (continuation-type x))
2722           (y (continuation-type y)))
2723       (if (and (simple-numeric-type x)
2724                (simple-numeric-type y))
2725           (values (type= (numeric-contagion x y)
2726                          (numeric-contagion y y)))))))
2727
2728 ;;; Fold (+ x 0).
2729 ;;;
2730 ;;; If y is not constant, not zerop, or is contagious, or a positive
2731 ;;; float +0.0 then give up.
2732 (deftransform + ((x y) (t (constant-arg t)) *)
2733   "fold zero arg"
2734   (let ((val (continuation-value y)))
2735     (unless (and (zerop val)
2736                  (not (and (floatp val) (plusp (float-sign val))))
2737                  (not-more-contagious y x))
2738       (give-up-ir1-transform)))
2739   'x)
2740
2741 ;;; Fold (- x 0).
2742 ;;;
2743 ;;; If y is not constant, not zerop, or is contagious, or a negative
2744 ;;; float -0.0 then give up.
2745 (deftransform - ((x y) (t (constant-arg t)) *)
2746   "fold zero arg"
2747   (let ((val (continuation-value y)))
2748     (unless (and (zerop val)
2749                  (not (and (floatp val) (minusp (float-sign val))))
2750                  (not-more-contagious y x))
2751       (give-up-ir1-transform)))
2752   'x)
2753
2754 ;;; Fold (OP x +/-1)
2755 (macrolet ((def (name result minus-result)
2756              `(deftransform ,name ((x y) (t (constant-arg real)) *)
2757                 "fold identity operations"
2758                 (let ((val (continuation-value y)))
2759                   (unless (and (= (abs val) 1)
2760                                (not-more-contagious y x))
2761                     (give-up-ir1-transform))
2762                   (if (minusp val) ',minus-result ',result)))))
2763   (def * x (%negate x))
2764   (def / x (%negate x))
2765   (def expt x (/ 1 x)))
2766
2767 ;;; Fold (expt x n) into multiplications for small integral values of
2768 ;;; N; convert (expt x 1/2) to sqrt.
2769 (deftransform expt ((x y) (t (constant-arg real)) *)
2770   "recode as multiplication or sqrt"
2771   (let ((val (continuation-value y)))
2772     ;; If Y would cause the result to be promoted to the same type as
2773     ;; Y, we give up. If not, then the result will be the same type
2774     ;; as X, so we can replace the exponentiation with simple
2775     ;; multiplication and division for small integral powers.
2776     (unless (not-more-contagious y x)
2777       (give-up-ir1-transform))
2778     (cond ((zerop val)
2779            (let ((x-type (continuation-type x)))
2780              (cond ((csubtypep x-type (specifier-type '(or rational
2781                                                         (complex rational))))
2782                     '1)
2783                    ((csubtypep x-type (specifier-type 'real))
2784                     `(if (rationalp x)
2785                          1
2786                          (float 1 x)))
2787                    ((csubtypep x-type (specifier-type 'complex))
2788                     ;; both parts are float
2789                     `(1+ (* x ,val)))
2790                    (t (give-up-ir1-transform)))))
2791           ((= val 2) '(* x x))
2792           ((= val -2) '(/ (* x x)))
2793           ((= val 3) '(* x x x))
2794           ((= val -3) '(/ (* x x x)))
2795           ((= val 1/2) '(sqrt x))
2796           ((= val -1/2) '(/ (sqrt x)))
2797           (t (give-up-ir1-transform)))))
2798
2799 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
2800 ;;; transformations?
2801 ;;; Perhaps we should have to prove that the denominator is nonzero before
2802 ;;; doing them?  -- WHN 19990917
2803 (macrolet ((def (name)
2804              `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2805                                    *)
2806                 "fold zero arg"
2807                 0)))
2808   (def ash)
2809   (def /))
2810
2811 (macrolet ((def (name)
2812              `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2813                                    *)
2814                 "fold zero arg"
2815                 '(values 0 0))))
2816   (def truncate)
2817   (def round)
2818   (def floor)
2819   (def ceiling))
2820 \f
2821 ;;;; character operations
2822
2823 (deftransform char-equal ((a b) (base-char base-char))
2824   "open code"
2825   '(let* ((ac (char-code a))
2826           (bc (char-code b))
2827           (sum (logxor ac bc)))
2828      (or (zerop sum)
2829          (when (eql sum #x20)
2830            (let ((sum (+ ac bc)))
2831              (and (> sum 161) (< sum 213)))))))
2832
2833 (deftransform char-upcase ((x) (base-char))
2834   "open code"
2835   '(let ((n-code (char-code x)))
2836      (if (and (> n-code #o140)  ; Octal 141 is #\a.
2837               (< n-code #o173)) ; Octal 172 is #\z.
2838          (code-char (logxor #x20 n-code))
2839          x)))
2840
2841 (deftransform char-downcase ((x) (base-char))
2842   "open code"
2843   '(let ((n-code (char-code x)))
2844      (if (and (> n-code 64)     ; 65 is #\A.
2845               (< n-code 91))    ; 90 is #\Z.
2846          (code-char (logxor #x20 n-code))
2847          x)))
2848 \f
2849 ;;;; equality predicate transforms
2850
2851 ;;; Return true if X and Y are continuations whose only use is a
2852 ;;; reference to the same leaf, and the value of the leaf cannot
2853 ;;; change.
2854 (defun same-leaf-ref-p (x y)
2855   (declare (type continuation x y))
2856   (let ((x-use (principal-continuation-use x))
2857         (y-use (principal-continuation-use y)))
2858     (and (ref-p x-use)
2859          (ref-p y-use)
2860          (eq (ref-leaf x-use) (ref-leaf y-use))
2861          (constant-reference-p x-use))))
2862
2863 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
2864 ;;; if there is no intersection between the types of the arguments,
2865 ;;; then the result is definitely false.
2866 (deftransform simple-equality-transform ((x y) * *
2867                                          :defun-only t)
2868   (cond ((same-leaf-ref-p x y)
2869          t)
2870         ((not (types-equal-or-intersect (continuation-type x)
2871                                         (continuation-type y)))
2872          nil)
2873         (t
2874          (give-up-ir1-transform))))
2875
2876 (macrolet ((def (x)
2877              `(%deftransform ',x '(function * *) #'simple-equality-transform)))
2878   (def eq)
2879   (def char=)
2880   (def equal))
2881
2882 ;;; This is similar to SIMPLE-EQUALITY-PREDICATE, except that we also
2883 ;;; try to convert to a type-specific predicate or EQ:
2884 ;;; -- If both args are characters, convert to CHAR=. This is better than
2885 ;;;    just converting to EQ, since CHAR= may have special compilation
2886 ;;;    strategies for non-standard representations, etc.
2887 ;;; -- If either arg is definitely not a number, then we can compare
2888 ;;;    with EQ.
2889 ;;; -- Otherwise, we try to put the arg we know more about second. If X
2890 ;;;    is constant then we put it second. If X is a subtype of Y, we put
2891 ;;;    it second. These rules make it easier for the back end to match
2892 ;;;    these interesting cases.
2893 ;;; -- If Y is a fixnum, then we quietly pass because the back end can
2894 ;;;    handle that case, otherwise give an efficiency note.
2895 (deftransform eql ((x y) * *)
2896   "convert to simpler equality predicate"
2897   (let ((x-type (continuation-type x))
2898         (y-type (continuation-type y))
2899         (char-type (specifier-type 'character))
2900         (number-type (specifier-type 'number)))
2901     (cond ((same-leaf-ref-p x y)
2902            t)
2903           ((not (types-equal-or-intersect x-type y-type))
2904            nil)
2905           ((and (csubtypep x-type char-type)
2906                 (csubtypep y-type char-type))
2907            '(char= x y))
2908           ((or (not (types-equal-or-intersect x-type number-type))
2909                (not (types-equal-or-intersect y-type number-type)))
2910            '(eq x y))
2911           ((and (not (constant-continuation-p y))
2912                 (or (constant-continuation-p x)
2913                     (and (csubtypep x-type y-type)
2914                          (not (csubtypep y-type x-type)))))
2915            '(eql y x))
2916           (t
2917            (give-up-ir1-transform)))))
2918
2919 ;;; Convert to EQL if both args are rational and complexp is specified
2920 ;;; and the same for both.
2921 (deftransform = ((x y) * *)
2922   "open code"
2923   (let ((x-type (continuation-type x))
2924         (y-type (continuation-type y)))
2925     (if (and (csubtypep x-type (specifier-type 'number))
2926              (csubtypep y-type (specifier-type 'number)))
2927         (cond ((or (and (csubtypep x-type (specifier-type 'float))
2928                         (csubtypep y-type (specifier-type 'float)))
2929                    (and (csubtypep x-type (specifier-type '(complex float)))
2930                         (csubtypep y-type (specifier-type '(complex float)))))
2931                ;; They are both floats. Leave as = so that -0.0 is
2932                ;; handled correctly.
2933                (give-up-ir1-transform))
2934               ((or (and (csubtypep x-type (specifier-type 'rational))
2935                         (csubtypep y-type (specifier-type 'rational)))
2936                    (and (csubtypep x-type
2937                                    (specifier-type '(complex rational)))
2938                         (csubtypep y-type
2939                                    (specifier-type '(complex rational)))))
2940                ;; They are both rationals and complexp is the same.
2941                ;; Convert to EQL.
2942                '(eql x y))
2943               (t
2944                (give-up-ir1-transform
2945                 "The operands might not be the same type.")))
2946         (give-up-ir1-transform
2947          "The operands might not be the same type."))))
2948
2949 ;;; If CONT's type is a numeric type, then return the type, otherwise
2950 ;;; GIVE-UP-IR1-TRANSFORM.
2951 (defun numeric-type-or-lose (cont)
2952   (declare (type continuation cont))
2953   (let ((res (continuation-type cont)))
2954     (unless (numeric-type-p res) (give-up-ir1-transform))
2955     res))
2956
2957 ;;; See whether we can statically determine (< X Y) using type
2958 ;;; information. If X's high bound is < Y's low, then X < Y.
2959 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
2960 ;;; NIL). If not, at least make sure any constant arg is second.
2961 ;;;
2962 ;;; FIXME: Why should constant argument be second? It would be nice to
2963 ;;; find out and explain.
2964 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2965 (defun ir1-transform-< (x y first second inverse)
2966   (if (same-leaf-ref-p x y)
2967       nil
2968       (let* ((x-type (numeric-type-or-lose x))
2969              (x-lo (numeric-type-low x-type))
2970              (x-hi (numeric-type-high x-type))
2971              (y-type (numeric-type-or-lose y))
2972              (y-lo (numeric-type-low y-type))
2973              (y-hi (numeric-type-high y-type)))
2974         (cond ((and x-hi y-lo (< x-hi y-lo))
2975                t)
2976               ((and y-hi x-lo (>= x-lo y-hi))
2977                nil)
2978               ((and (constant-continuation-p first)
2979                     (not (constant-continuation-p second)))
2980                `(,inverse y x))
2981               (t
2982                (give-up-ir1-transform))))))
2983 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2984 (defun ir1-transform-< (x y first second inverse)
2985   (if (same-leaf-ref-p x y)
2986       nil
2987       (let ((xi (numeric-type->interval (numeric-type-or-lose x)))
2988             (yi (numeric-type->interval (numeric-type-or-lose y))))
2989         (cond ((interval-< xi yi)
2990                t)
2991               ((interval->= xi yi)
2992                nil)
2993               ((and (constant-continuation-p first)
2994                     (not (constant-continuation-p second)))
2995                `(,inverse y x))
2996               (t
2997                (give-up-ir1-transform))))))
2998
2999 (deftransform < ((x y) (integer integer) *)
3000   (ir1-transform-< x y x y '>))
3001
3002 (deftransform > ((x y) (integer integer) *)
3003   (ir1-transform-< y x x y '<))
3004
3005 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
3006 (deftransform < ((x y) (float float) *)
3007   (ir1-transform-< x y x y '>))
3008
3009 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
3010 (deftransform > ((x y) (float float) *)
3011   (ir1-transform-< y x x y '<))
3012
3013 (defun ir1-transform-char< (x y first second inverse)
3014   (cond
3015     ((same-leaf-ref-p x y) nil)
3016     ;; If we had interval representation of character types, as we
3017     ;; might eventually have to to support 2^21 characters, then here
3018     ;; we could do some compile-time computation as in IR1-TRANSFORM-<
3019     ;; above.  -- CSR, 2003-07-01
3020     ((and (constant-continuation-p first)
3021           (not (constant-continuation-p second)))
3022      `(,inverse y x))
3023     (t (give-up-ir1-transform))))
3024
3025 (deftransform char< ((x y) (character character) *)
3026   (ir1-transform-char< x y x y 'char>))
3027
3028 (deftransform char> ((x y) (character character) *)
3029   (ir1-transform-char< y x x y 'char<))
3030 \f
3031 ;;;; converting N-arg comparisons
3032 ;;;;
3033 ;;;; We convert calls to N-arg comparison functions such as < into
3034 ;;;; two-arg calls. This transformation is enabled for all such
3035 ;;;; comparisons in this file. If any of these predicates are not
3036 ;;;; open-coded, then the transformation should be removed at some
3037 ;;;; point to avoid pessimization.
3038
3039 ;;; This function is used for source transformation of N-arg
3040 ;;; comparison functions other than inequality. We deal both with
3041 ;;; converting to two-arg calls and inverting the sense of the test,
3042 ;;; if necessary. If the call has two args, then we pass or return a
3043 ;;; negated test as appropriate. If it is a degenerate one-arg call,
3044 ;;; then we transform to code that returns true. Otherwise, we bind
3045 ;;; all the arguments and expand into a bunch of IFs.
3046 (declaim (ftype (function (symbol list boolean t) *) multi-compare))
3047 (defun multi-compare (predicate args not-p type)
3048   (let ((nargs (length args)))
3049     (cond ((< nargs 1) (values nil t))
3050           ((= nargs 1) `(progn (the ,type ,@args) t))
3051           ((= nargs 2)
3052            (if not-p
3053                `(if (,predicate ,(first args) ,(second args)) nil t)
3054                (values nil t)))
3055           (t
3056            (do* ((i (1- nargs) (1- i))
3057                  (last nil current)
3058                  (current (gensym) (gensym))
3059                  (vars (list current) (cons current vars))
3060                  (result t (if not-p
3061                                `(if (,predicate ,current ,last)
3062                                     nil ,result)
3063                                `(if (,predicate ,current ,last)
3064                                     ,result nil))))
3065                ((zerop i)
3066                 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3067                   ,@args)))))))
3068
3069 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
3070 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
3071 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
3072 (define-source-transform <= (&rest args) (multi-compare '> args t 'real))
3073 (define-source-transform >= (&rest args) (multi-compare '< args t 'real))
3074
3075 (define-source-transform char= (&rest args) (multi-compare 'char= args nil
3076                                                            'character))
3077 (define-source-transform char< (&rest args) (multi-compare 'char< args nil
3078                                                            'character))
3079 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
3080                                                            'character))
3081 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
3082                                                             'character))
3083 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
3084                                                             'character))
3085
3086 (define-source-transform char-equal (&rest args)
3087   (multi-compare 'char-equal args nil 'character))
3088 (define-source-transform char-lessp (&rest args)
3089   (multi-compare 'char-lessp args nil 'character))
3090 (define-source-transform char-greaterp (&rest args)
3091   (multi-compare 'char-greaterp args nil 'character))
3092 (define-source-transform char-not-greaterp (&rest args)
3093   (multi-compare 'char-greaterp args t 'character))
3094 (define-source-transform char-not-lessp (&rest args)
3095   (multi-compare 'char-lessp args t 'character))
3096
3097 ;;; This function does source transformation of N-arg inequality
3098 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3099 ;;; arg cases. If there are more than two args, then we expand into
3100 ;;; the appropriate n^2 comparisons only when speed is important.
3101 (declaim (ftype (function (symbol list t) *) multi-not-equal))
3102 (defun multi-not-equal (predicate args type)
3103   (let ((nargs (length args)))
3104     (cond ((< nargs 1) (values nil t))
3105           ((= nargs 1) `(progn (the ,type ,@args) t))
3106           ((= nargs 2)
3107            `(if (,predicate ,(first args) ,(second args)) nil t))
3108           ((not (policy *lexenv*
3109                         (and (>= speed space)
3110                              (>= speed compilation-speed))))
3111            (values nil t))
3112           (t
3113            (let ((vars (make-gensym-list nargs)))
3114              (do ((var vars next)
3115                   (next (cdr vars) (cdr next))
3116                   (result t))
3117                  ((null next)
3118                   `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3119                     ,@args))
3120                (let ((v1 (first var)))
3121                  (dolist (v2 next)
3122                    (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3123
3124 (define-source-transform /= (&rest args)
3125   (multi-not-equal '= args 'number))
3126 (define-source-transform char/= (&rest args)
3127   (multi-not-equal 'char= args 'character))
3128 (define-source-transform char-not-equal (&rest args)
3129   (multi-not-equal 'char-equal args 'character))
3130
3131 ;;; Expand MAX and MIN into the obvious comparisons.
3132 (define-source-transform max (arg0 &rest rest)
3133   (once-only ((arg0 arg0))
3134     (if (null rest)
3135         `(values (the real ,arg0))
3136         `(let ((maxrest (max ,@rest)))
3137           (if (> ,arg0 maxrest) ,arg0 maxrest)))))
3138 (define-source-transform min (arg0 &rest rest)
3139   (once-only ((arg0 arg0))
3140     (if (null rest)
3141         `(values (the real ,arg0))
3142         `(let ((minrest (min ,@rest)))
3143           (if (< ,arg0 minrest) ,arg0 minrest)))))
3144 \f
3145 ;;;; converting N-arg arithmetic functions
3146 ;;;;
3147 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3148 ;;;; versions, and degenerate cases are flushed.
3149
3150 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3151 (declaim (ftype (function (symbol t list) list) associate-args))
3152 (defun associate-args (function first-arg more-args)
3153   (let ((next (rest more-args))
3154         (arg (first more-args)))
3155     (if (null next)
3156         `(,function ,first-arg ,arg)
3157         (associate-args function `(,function ,first-arg ,arg) next))))
3158
3159 ;;; Do source transformations for transitive functions such as +.
3160 ;;; One-arg cases are replaced with the arg and zero arg cases with
3161 ;;; the identity.  ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3162 ;;; ensure (with THE) that the argument in one-argument calls is.
3163 (defun source-transform-transitive (fun args identity
3164                                     &optional one-arg-result-type)
3165   (declare (symbol fun leaf-fun) (list args))
3166   (case (length args)
3167     (0 identity)
3168     (1 (if one-arg-result-type
3169            `(values (the ,one-arg-result-type ,(first args)))
3170            `(values ,(first args))))
3171     (2 (values nil t))
3172     (t
3173      (associate-args fun (first args) (rest args)))))
3174
3175 (define-source-transform + (&rest args)
3176   (source-transform-transitive '+ args 0 'number))
3177 (define-source-transform * (&rest args)
3178   (source-transform-transitive '* args 1 'number))
3179 (define-source-transform logior (&rest args)
3180   (source-transform-transitive 'logior args 0 'integer))
3181 (define-source-transform logxor (&rest args)
3182   (source-transform-transitive 'logxor args 0 'integer))
3183 (define-source-transform logand (&rest args)
3184   (source-transform-transitive 'logand args -1 'integer))
3185
3186 (define-source-transform logeqv (&rest args)
3187   (if (evenp (length args))
3188       `(lognot (logxor ,@args))
3189       `(logxor ,@args)))
3190
3191 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3192 ;;; because when they are given one argument, they return its absolute
3193 ;;; value.
3194
3195 (define-source-transform gcd (&rest args)
3196   (case (length args)
3197     (0 0)
3198     (1 `(abs (the integer ,(first args))))
3199     (2 (values nil t))
3200     (t (associate-args 'gcd (first args) (rest args)))))
3201
3202 (define-source-transform lcm (&rest args)
3203   (case (length args)
3204     (0 1)
3205     (1 `(abs (the integer ,(first args))))
3206     (2 (values nil t))
3207     (t (associate-args 'lcm (first args) (rest args)))))
3208
3209 ;;; Do source transformations for intransitive n-arg functions such as
3210 ;;; /. With one arg, we form the inverse. With two args we pass.
3211 ;;; Otherwise we associate into two-arg calls.
3212 (declaim (ftype (function (symbol list t)
3213                           (values list &optional (member nil t)))
3214                 source-transform-intransitive))
3215 (defun source-transform-intransitive (function args inverse)
3216   (case (length args)
3217     ((0 2) (values nil t))
3218     (1 `(,@inverse ,(first args)))
3219     (t (associate-args function (first args) (rest args)))))
3220
3221 (define-source-transform - (&rest args)
3222   (source-transform-intransitive '- args '(%negate)))
3223 (define-source-transform / (&rest args)
3224   (source-transform-intransitive '/ args '(/ 1)))
3225 \f
3226 ;;;; transforming APPLY
3227
3228 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3229 ;;; only needs to understand one kind of variable-argument call. It is
3230 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3231 (define-source-transform apply (fun arg &rest more-args)
3232   (let ((args (cons arg more-args)))
3233     `(multiple-value-call ,fun
3234        ,@(mapcar (lambda (x)
3235                    `(values ,x))
3236                  (butlast args))
3237        (values-list ,(car (last args))))))
3238 \f
3239 ;;;; transforming FORMAT
3240 ;;;;
3241 ;;;; If the control string is a compile-time constant, then replace it
3242 ;;;; with a use of the FORMATTER macro so that the control string is
3243 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3244 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3245 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3246
3247 ;;; for compile-time argument count checking.
3248 ;;;
3249 ;;; FIXME I: this is currently called from DEFTRANSFORMs, the vast
3250 ;;; majority of which are not going to transform the code, but instead
3251 ;;; are going to GIVE-UP-IR1-TRANSFORM unconditionally.  It would be
3252 ;;; nice to make this explicit, maybe by implementing a new
3253 ;;; "optimizer" (say, DEFOPTIMIZER CONSISTENCY-CHECK).
3254 ;;;
3255 ;;; FIXME II: In some cases, type information could be correlated; for
3256 ;;; instance, ~{ ... ~} requires a list argument, so if the
3257 ;;; continuation-type of a corresponding argument is known and does
3258 ;;; not intersect the list type, a warning could be signalled.
3259 (defun check-format-args (string args fun)
3260   (declare (type string string))
3261   (unless (typep string 'simple-string)
3262     (setq string (coerce string 'simple-string)))
3263   (multiple-value-bind (min max)
3264       (handler-case (sb!format:%compiler-walk-format-string string args)
3265         (sb!format:format-error (c)
3266           (compiler-warn "~A" c)))
3267     (when min
3268       (let ((nargs (length args)))
3269         (cond
3270           ((< nargs min)
3271            (compiler-warn "Too few arguments (~D) to ~S ~S: ~
3272                            requires at least ~D."
3273                           nargs fun string min))
3274           ((> nargs max)
3275            (;; to get warned about probably bogus code at
3276             ;; cross-compile time.
3277             #+sb-xc-host compiler-warn
3278             ;; ANSI saith that too many arguments doesn't cause a
3279             ;; run-time error.
3280             #-sb-xc-host compiler-style-warn
3281             "Too many arguments (~D) to ~S ~S: uses at most ~D."
3282             nargs fun string max)))))))
3283
3284 (defoptimizer (format optimizer) ((dest control &rest args))
3285   (when (constant-continuation-p control)
3286     (let ((x (continuation-value control)))
3287       (when (stringp x)
3288         (check-format-args x args 'format)))))
3289
3290 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3291                       :policy (> speed space))
3292   (unless (constant-continuation-p control)
3293     (give-up-ir1-transform "The control string is not a constant."))
3294   (let ((arg-names (make-gensym-list (length args))))
3295     `(lambda (dest control ,@arg-names)
3296        (declare (ignore control))
3297        (format dest (formatter ,(continuation-value control)) ,@arg-names))))
3298
3299 (deftransform format ((stream control &rest args) (stream function &rest t) *
3300                       :policy (> speed space))
3301   (let ((arg-names (make-gensym-list (length args))))
3302     `(lambda (stream control ,@arg-names)
3303        (funcall control stream ,@arg-names)
3304        nil)))
3305
3306 (deftransform format ((tee control &rest args) ((member t) function &rest t) *
3307                       :policy (> speed space))
3308   (let ((arg-names (make-gensym-list (length args))))
3309     `(lambda (tee control ,@arg-names)
3310        (declare (ignore tee))
3311        (funcall control *standard-output* ,@arg-names)
3312        nil)))
3313
3314 (macrolet
3315     ((def (name)
3316          `(defoptimizer (,name optimizer) ((control &rest args))
3317             (when (constant-continuation-p control)
3318               (let ((x (continuation-value control)))
3319                 (when (stringp x)
3320                   (check-format-args x args ',name)))))))
3321   (def error)
3322   (def warn)
3323   #+sb-xc-host ; Only we should be using these
3324   (progn
3325     (def style-warn)
3326     (def compiler-abort)
3327     (def compiler-error)
3328     (def compiler-warn)
3329     (def compiler-style-warn)
3330     (def compiler-notify)
3331     (def maybe-compiler-notify)
3332     (def bug)))
3333
3334 (defoptimizer (cerror optimizer) ((report control &rest args))
3335   (when (and (constant-continuation-p control)
3336              (constant-continuation-p report))
3337     (let ((x (continuation-value control))
3338           (y (continuation-value report)))
3339       (when (and (stringp x) (stringp y))
3340         (multiple-value-bind (min1 max1)
3341             (handler-case
3342                 (sb!format:%compiler-walk-format-string x args)
3343               (sb!format:format-error (c)
3344                 (compiler-warn "~A" c)))
3345           (when min1
3346             (multiple-value-bind (min2 max2)
3347                 (handler-case
3348                     (sb!format:%compiler-walk-format-string y args)
3349                   (sb!format:format-error (c)
3350                     (compiler-warn "~A" c)))
3351               (when min2
3352                 (let ((nargs (length args)))
3353                   (cond
3354                     ((< nargs (min min1 min2))
3355                      (compiler-warn "Too few arguments (~D) to ~S ~S ~S: ~
3356                                      requires at least ~D."
3357                                     nargs 'cerror y x (min min1 min2)))
3358                     ((> nargs (max max1 max2))
3359                      (;; to get warned about probably bogus code at
3360                       ;; cross-compile time.
3361                       #+sb-xc-host compiler-warn
3362                       ;; ANSI saith that too many arguments doesn't cause a
3363                       ;; run-time error.
3364                       #-sb-xc-host compiler-style-warn
3365                       "Too many arguments (~D) to ~S ~S ~S: uses at most ~D."
3366                       nargs 'cerror y x (max max1 max2)))))))))))))
3367
3368 (defoptimizer (coerce derive-type) ((value type))
3369   (cond
3370     ((constant-continuation-p type)
3371      ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3372      ;; but dealing with the niggle that complex canonicalization gets
3373      ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3374      ;; type COMPLEX.
3375      (let* ((specifier (continuation-value type))
3376             (result-typeoid (careful-specifier-type specifier)))
3377        (cond
3378          ((null result-typeoid) nil)
3379          ((csubtypep result-typeoid (specifier-type 'number))
3380           ;; the difficult case: we have to cope with ANSI 12.1.5.3
3381           ;; Rule of Canonical Representation for Complex Rationals,
3382           ;; which is a truly nasty delivery to field.
3383           (cond
3384             ((csubtypep result-typeoid (specifier-type 'real))
3385              ;; cleverness required here: it would be nice to deduce
3386              ;; that something of type (INTEGER 2 3) coerced to type
3387              ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3388              ;; FLOAT gets its own clause because it's implemented as
3389              ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3390              ;; logic below.
3391              result-typeoid)
3392             ((and (numeric-type-p result-typeoid)
3393                   (eq (numeric-type-complexp result-typeoid) :real))
3394              ;; FIXME: is this clause (a) necessary or (b) useful?
3395              result-typeoid)
3396             ((or (csubtypep result-typeoid
3397                             (specifier-type '(complex single-float)))
3398                  (csubtypep result-typeoid
3399                             (specifier-type '(complex double-float)))
3400                  #!+long-float
3401                  (csubtypep result-typeoid
3402                             (specifier-type '(complex long-float))))
3403              ;; float complex types are never canonicalized.
3404              result-typeoid)
3405             (t
3406              ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
3407              ;; probably just a COMPLEX or equivalent.  So, in that
3408              ;; case, we will return a complex or an object of the
3409              ;; provided type if it's rational:
3410              (type-union result-typeoid
3411                          (type-intersection (continuation-type value)
3412                                             (specifier-type 'rational))))))
3413          (t result-typeoid))))
3414     (t
3415      ;; OK, the result-type argument isn't constant.  However, there
3416      ;; are common uses where we can still do better than just
3417      ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
3418      ;; where Y is of a known type.  See messages on cmucl-imp
3419      ;; 2001-02-14 and sbcl-devel 2002-12-12.  We only worry here
3420      ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
3421      ;; the basis that it's unlikely that other uses are both
3422      ;; time-critical and get to this branch of the COND (non-constant
3423      ;; second argument to COERCE).  -- CSR, 2002-12-16
3424      (let ((value-type (continuation-type value))
3425            (type-type (continuation-type type)))
3426        (labels
3427            ((good-cons-type-p (cons-type)
3428               ;; Make sure the cons-type we're looking at is something
3429               ;; we're prepared to handle which is basically something
3430               ;; that array-element-type can return.
3431               (or (and (member-type-p cons-type)
3432                        (null (rest (member-type-members cons-type)))
3433                        (null (first (member-type-members cons-type))))
3434                   (let ((car-type (cons-type-car-type cons-type)))
3435                     (and (member-type-p car-type)
3436                          (null (rest (member-type-members car-type)))
3437                          (or (symbolp (first (member-type-members car-type)))
3438                              (numberp (first (member-type-members car-type)))
3439                              (and (listp (first (member-type-members
3440                                                  car-type)))
3441                                   (numberp (first (first (member-type-members
3442                                                           car-type))))))
3443                          (good-cons-type-p (cons-type-cdr-type cons-type))))))
3444             (unconsify-type (good-cons-type)
3445               ;; Convert the "printed" respresentation of a cons
3446               ;; specifier into a type specifier.  That is, the
3447               ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
3448               ;; NULL)) is converted to (SIGNED-BYTE 16).
3449               (cond ((or (null good-cons-type)
3450                          (eq good-cons-type 'null))
3451                      nil)
3452                     ((and (eq (first good-cons-type) 'cons)
3453                           (eq (first (second good-cons-type)) 'member))
3454                      `(,(second (second good-cons-type))
3455                        ,@(unconsify-type (caddr good-cons-type))))))
3456             (coerceable-p (c-type)
3457               ;; Can the value be coerced to the given type?  Coerce is
3458               ;; complicated, so we don't handle every possible case
3459               ;; here---just the most common and easiest cases:
3460               ;;
3461               ;; * Any REAL can be coerced to a FLOAT type.
3462               ;; * Any NUMBER can be coerced to a (COMPLEX
3463               ;;   SINGLE/DOUBLE-FLOAT).
3464               ;;
3465               ;; FIXME I: we should also be able to deal with characters
3466               ;; here.
3467               ;;
3468               ;; FIXME II: I'm not sure that anything is necessary
3469               ;; here, at least while COMPLEX is not a specialized
3470               ;; array element type in the system.  Reasoning: if
3471               ;; something cannot be coerced to the requested type, an
3472               ;; error will be raised (and so any downstream compiled
3473               ;; code on the assumption of the returned type is
3474               ;; unreachable).  If something can, then it will be of
3475               ;; the requested type, because (by assumption) COMPLEX
3476               ;; (and other difficult types like (COMPLEX INTEGER)
3477               ;; aren't specialized types.
3478               (let ((coerced-type c-type))
3479                 (or (and (subtypep coerced-type 'float)
3480                          (csubtypep value-type (specifier-type 'real)))
3481                     (and (subtypep coerced-type
3482                                    '(or (complex single-float)
3483                                         (complex double-float)))
3484                          (csubtypep value-type (specifier-type 'number))))))
3485             (process-types (type)
3486               ;; FIXME: This needs some work because we should be able
3487               ;; to derive the resulting type better than just the
3488               ;; type arg of coerce.  That is, if X is (INTEGER 10
3489               ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
3490               ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
3491               ;; double-float.
3492               (cond ((member-type-p type)
3493                      (let ((members (member-type-members type)))
3494                        (if (every #'coerceable-p members)
3495                            (specifier-type `(or ,@members))
3496                            *universal-type*)))
3497                     ((and (cons-type-p type)
3498                           (good-cons-type-p type))
3499                      (let ((c-type (unconsify-type (type-specifier type))))
3500                        (if (coerceable-p c-type)
3501                            (specifier-type c-type)
3502                            *universal-type*)))
3503                     (t
3504                      *universal-type*))))
3505          (cond ((union-type-p type-type)
3506                 (apply #'type-union (mapcar #'process-types
3507                                             (union-type-types type-type))))
3508                ((or (member-type-p type-type)
3509                     (cons-type-p type-type))
3510                 (process-types type-type))
3511                (t
3512                 *universal-type*)))))))
3513
3514 (defoptimizer (compile derive-type) ((nameoid function))
3515   (when (csubtypep (continuation-type nameoid)
3516                    (specifier-type 'null))
3517     (values-specifier-type '(values function boolean boolean))))
3518
3519 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
3520 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
3521 ;;; optimizer, above).
3522 (defoptimizer (array-element-type derive-type) ((array))
3523   (let ((array-type (continuation-type array)))
3524     (labels ((consify (list)
3525               (if (endp list)
3526                   '(eql nil)
3527                   `(cons (eql ,(car list)) ,(consify (rest list)))))
3528             (get-element-type (a)
3529               (let ((element-type
3530                      (type-specifier (array-type-specialized-element-type a))))
3531                 (cond ((eq element-type '*)
3532                        (specifier-type 'type-specifier))
3533                       ((symbolp element-type)
3534                        (make-member-type :members (list element-type)))
3535                       ((consp element-type)
3536                        (specifier-type (consify element-type)))
3537                       (t
3538                        (error "can't understand type ~S~%" element-type))))))
3539       (cond ((array-type-p array-type)
3540              (get-element-type array-type))
3541             ((union-type-p array-type)
3542              (apply #'type-union
3543                     (mapcar #'get-element-type (union-type-types array-type))))
3544             (t
3545              *universal-type*)))))
3546
3547 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
3548   `(macrolet ((%index (x) `(truly-the index ,x))
3549               (%parent (i) `(ash ,i -1))
3550               (%left (i) `(%index (ash ,i 1)))
3551               (%right (i) `(%index (1+ (ash ,i 1))))
3552               (%heapify (i)
3553                `(do* ((i ,i)
3554                       (left (%left i) (%left i)))
3555                  ((> left current-heap-size))
3556                  (declare (type index i left))
3557                  (let* ((i-elt (%elt i))
3558                         (i-key (funcall keyfun i-elt))
3559                         (left-elt (%elt left))
3560                         (left-key (funcall keyfun left-elt)))
3561                    (multiple-value-bind (large large-elt large-key)
3562                        (if (funcall ,',predicate i-key left-key)
3563                            (values left left-elt left-key)
3564                            (values i i-elt i-key))
3565                      (let ((right (%right i)))
3566                        (multiple-value-bind (largest largest-elt)
3567                            (if (> right current-heap-size)
3568                                (values large large-elt)
3569                                (let* ((right-elt (%elt right))
3570                                       (right-key (funcall keyfun right-elt)))
3571                                  (if (funcall ,',predicate large-key right-key)
3572                                      (values right right-elt)
3573                                      (values large large-elt))))
3574                          (cond ((= largest i)
3575                                 (return))
3576                                (t
3577                                 (setf (%elt i) largest-elt
3578                                       (%elt largest) i-elt
3579                                       i largest)))))))))
3580               (%sort-vector (keyfun &optional (vtype 'vector))
3581                `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had trouble getting
3582                            ;; type inference to propagate all the way
3583                            ;; through this tangled mess of
3584                            ;; inlining. The TRULY-THE here works
3585                            ;; around that. -- WHN
3586                            (%elt (i)
3587                             `(aref (truly-the ,',vtype ,',',vector)
3588                               (%index (+ (%index ,i) start-1)))))
3589                  (let ((start-1 (1- ,',start)) ; Heaps prefer 1-based addressing.
3590                        (current-heap-size (- ,',end ,',start))
3591                        (keyfun ,keyfun))
3592                    (declare (type (integer -1 #.(1- most-positive-fixnum))
3593                                   start-1))
3594                    (declare (type index current-heap-size))
3595                    (declare (type function keyfun))
3596                    (loop for i of-type index
3597                          from (ash current-heap-size -1) downto 1 do
3598                          (%heapify i))
3599                    (loop
3600                     (when (< current-heap-size 2)
3601                       (return))
3602                     (rotatef (%elt 1) (%elt current-heap-size))
3603                     (decf current-heap-size)
3604                     (%heapify 1))))))
3605     (if (typep ,vector 'simple-vector)
3606         ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
3607         ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
3608         (if (null ,key)
3609             ;; Special-casing the KEY=NIL case lets us avoid some
3610             ;; function calls.
3611             (%sort-vector #'identity simple-vector)
3612             (%sort-vector ,key simple-vector))
3613         ;; It's hard to anticipate many speed-critical applications for
3614         ;; sorting vector types other than (VECTOR T), so we just lump
3615         ;; them all together in one slow dynamically typed mess.
3616         (locally
3617           (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
3618           (%sort-vector (or ,key #'identity))))))
3619 \f
3620 ;;;; debuggers' little helpers
3621
3622 ;;; for debugging when transforms are behaving mysteriously,
3623 ;;; e.g. when debugging a problem with an ASH transform
3624 ;;;   (defun foo (&optional s)
3625 ;;;     (sb-c::/report-continuation s "S outside WHEN")
3626 ;;;     (when (and (integerp s) (> s 3))
3627 ;;;       (sb-c::/report-continuation s "S inside WHEN")
3628 ;;;       (let ((bound (ash 1 (1- s))))
3629 ;;;         (sb-c::/report-continuation bound "BOUND")
3630 ;;;         (let ((x (- bound))
3631 ;;;               (y (1- bound)))
3632 ;;;           (sb-c::/report-continuation x "X")
3633 ;;;           (sb-c::/report-continuation x "Y"))
3634 ;;;         `(integer ,(- bound) ,(1- bound)))))
3635 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
3636 ;;; and the function doesn't do anything at all.)
3637 #!+sb-show
3638 (progn
3639   (defknown /report-continuation (t t) null)
3640   (deftransform /report-continuation ((x message) (t t))
3641     (format t "~%/in /REPORT-CONTINUATION~%")
3642     (format t "/(CONTINUATION-TYPE X)=~S~%" (continuation-type x))
3643     (when (constant-continuation-p x)
3644       (format t "/(CONTINUATION-VALUE X)=~S~%" (continuation-value x)))
3645     (format t "/MESSAGE=~S~%" (continuation-value message))
3646     (give-up-ir1-transform "not a real transform"))
3647   (defun /report-continuation (x message)
3648     (declare (ignore x message))))