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