0.8alpha.0.8:
[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 (defun convert-numeric-type (type)
821   (declare (type numeric-type type))
822   ;;; Only convert real float interval delimiters types.
823   (if (eq (numeric-type-complexp type) :real)
824       (let* ((lo (numeric-type-low type))
825              (lo-val (type-bound-number lo))
826              (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
827              (hi (numeric-type-high type))
828              (hi-val (type-bound-number hi))
829              (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
830         (if (or lo-float-zero-p hi-float-zero-p)
831             (make-numeric-type
832              :class (numeric-type-class type)
833              :format (numeric-type-format type)
834              :complexp :real
835              :low (if lo-float-zero-p
836                       (if (consp lo)
837                           (list (float 0.0 lo-val))
838                           (float -0.0 lo-val))
839                       lo)
840              :high (if hi-float-zero-p
841                        (if (consp hi)
842                            (list (float -0.0 hi-val))
843                            (float 0.0 hi-val))
844                        hi))
845             type))
846       ;; Not real float.
847       type))
848
849 ;;; Convert back from the intermediate convention for which -0.0 and
850 ;;; 0.0 are considered different to the standard type convention for
851 ;;; which and equal.
852 (defun convert-back-numeric-type (type)
853   (declare (type numeric-type type))
854   ;;; Only convert real float interval delimiters types.
855   (if (eq (numeric-type-complexp type) :real)
856       (let* ((lo (numeric-type-low type))
857              (lo-val (type-bound-number lo))
858              (lo-float-zero-p
859               (and lo (floatp lo-val) (= lo-val 0.0)
860                    (float-sign lo-val)))
861              (hi (numeric-type-high type))
862              (hi-val (type-bound-number hi))
863              (hi-float-zero-p
864               (and hi (floatp hi-val) (= hi-val 0.0)
865                    (float-sign hi-val))))
866         (cond
867           ;; (float +0.0 +0.0) => (member 0.0)
868           ;; (float -0.0 -0.0) => (member -0.0)
869           ((and lo-float-zero-p hi-float-zero-p)
870            ;; shouldn't have exclusive bounds here..
871            (aver (and (not (consp lo)) (not (consp hi))))
872            (if (= lo-float-zero-p hi-float-zero-p)
873                ;; (float +0.0 +0.0) => (member 0.0)
874                ;; (float -0.0 -0.0) => (member -0.0)
875                (specifier-type `(member ,lo-val))
876                ;; (float -0.0 +0.0) => (float 0.0 0.0)
877                ;; (float +0.0 -0.0) => (float 0.0 0.0)
878                (make-numeric-type :class (numeric-type-class type)
879                                   :format (numeric-type-format type)
880                                   :complexp :real
881                                   :low hi-val
882                                   :high hi-val)))
883           (lo-float-zero-p
884            (cond
885              ;; (float -0.0 x) => (float 0.0 x)
886              ((and (not (consp lo)) (minusp lo-float-zero-p))
887               (make-numeric-type :class (numeric-type-class type)
888                                  :format (numeric-type-format type)
889                                  :complexp :real
890                                  :low (float 0.0 lo-val)
891                                  :high hi))
892              ;; (float (+0.0) x) => (float (0.0) x)
893              ((and (consp lo) (plusp lo-float-zero-p))
894               (make-numeric-type :class (numeric-type-class type)
895                                  :format (numeric-type-format type)
896                                  :complexp :real
897                                  :low (list (float 0.0 lo-val))
898                                  :high hi))
899              (t
900               ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
901               ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
902               (list (make-member-type :members (list (float 0.0 lo-val)))
903                     (make-numeric-type :class (numeric-type-class type)
904                                        :format (numeric-type-format type)
905                                        :complexp :real
906                                        :low (list (float 0.0 lo-val))
907                                        :high hi)))))
908           (hi-float-zero-p
909            (cond
910              ;; (float x +0.0) => (float x 0.0)
911              ((and (not (consp hi)) (plusp hi-float-zero-p))
912               (make-numeric-type :class (numeric-type-class type)
913                                  :format (numeric-type-format type)
914                                  :complexp :real
915                                  :low lo
916                                  :high (float 0.0 hi-val)))
917              ;; (float x (-0.0)) => (float x (0.0))
918              ((and (consp hi) (minusp hi-float-zero-p))
919               (make-numeric-type :class (numeric-type-class type)
920                                  :format (numeric-type-format type)
921                                  :complexp :real
922                                  :low lo
923                                  :high (list (float 0.0 hi-val))))
924              (t
925               ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
926               ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
927               (list (make-member-type :members (list (float -0.0 hi-val)))
928                     (make-numeric-type :class (numeric-type-class type)
929                                        :format (numeric-type-format type)
930                                        :complexp :real
931                                        :low lo
932                                        :high (list (float 0.0 hi-val)))))))
933           (t
934            type)))
935       ;; not real float
936       type))
937
938 ;;; Convert back a possible list of numeric types.
939 (defun convert-back-numeric-type-list (type-list)
940   (typecase type-list
941     (list
942      (let ((results '()))
943        (dolist (type type-list)
944          (if (numeric-type-p type)
945              (let ((result (convert-back-numeric-type type)))
946                (if (listp result)
947                    (setf results (append results result))
948                    (push result results)))
949              (push type results)))
950        results))
951     (numeric-type
952      (convert-back-numeric-type type-list))
953     (union-type
954      (convert-back-numeric-type-list (union-type-types type-list)))
955     (t
956      type-list)))
957
958 ;;; FIXME: MAKE-CANONICAL-UNION-TYPE and CONVERT-MEMBER-TYPE probably
959 ;;; belong in the kernel's type logic, invoked always, instead of in
960 ;;; the compiler, invoked only during some type optimizations.
961
962 ;;; Take a list of types and return a canonical type specifier,
963 ;;; combining any MEMBER types together. If both positive and negative
964 ;;; MEMBER types are present they are converted to a float type.
965 ;;; XXX This would be far simpler if the type-union methods could handle
966 ;;; member/number unions.
967 (defun make-canonical-union-type (type-list)
968   (let ((members '())
969         (misc-types '()))
970     (dolist (type type-list)
971       (if (member-type-p type)
972           (setf members (union members (member-type-members type)))
973           (push type misc-types)))
974     #!+long-float
975     (when (null (set-difference '(-0l0 0l0) members))
976       (push (specifier-type '(long-float 0l0 0l0)) misc-types)
977       (setf members (set-difference members '(-0l0 0l0))))
978     (when (null (set-difference '(-0d0 0d0) members))
979       (push (specifier-type '(double-float 0d0 0d0)) misc-types)
980       (setf members (set-difference members '(-0d0 0d0))))
981     (when (null (set-difference '(-0f0 0f0) members))
982       (push (specifier-type '(single-float 0f0 0f0)) misc-types)
983       (setf members (set-difference members '(-0f0 0f0))))
984     (if members
985         (apply #'type-union (make-member-type :members members) misc-types)
986         (apply #'type-union misc-types))))
987
988 ;;; Convert a member type with a single member to a numeric type.
989 (defun convert-member-type (arg)
990   (let* ((members (member-type-members arg))
991          (member (first members))
992          (member-type (type-of member)))
993     (aver (not (rest members)))
994     (specifier-type `(,(if (subtypep member-type 'integer)
995                            'integer
996                            member-type)
997                       ,member ,member))))
998
999 ;;; This is used in defoptimizers for computing the resulting type of
1000 ;;; a function.
1001 ;;;
1002 ;;; Given the continuation ARG, derive the resulting type using the
1003 ;;; DERIVE-FCN. DERIVE-FCN takes exactly one argument which is some
1004 ;;; "atomic" continuation type like numeric-type or member-type
1005 ;;; (containing just one element). It should return the resulting
1006 ;;; type, which can be a list of types.
1007 ;;;
1008 ;;; For the case of member types, if a member-fcn is given it is
1009 ;;; called to compute the result otherwise the member type is first
1010 ;;; converted to a numeric type and the derive-fcn is call.
1011 (defun one-arg-derive-type (arg derive-fcn member-fcn
1012                                 &optional (convert-type t))
1013   (declare (type function derive-fcn)
1014            (type (or null function) member-fcn))
1015   (let ((arg-list (prepare-arg-for-derive-type (continuation-type arg))))
1016     (when arg-list
1017       (flet ((deriver (x)
1018                (typecase x
1019                  (member-type
1020                   (if member-fcn
1021                       (with-float-traps-masked
1022                           (:underflow :overflow :divide-by-zero)
1023                         (make-member-type
1024                          :members (list
1025                                    (funcall member-fcn
1026                                             (first (member-type-members x))))))
1027                       ;; Otherwise convert to a numeric type.
1028                       (let ((result-type-list
1029                              (funcall derive-fcn (convert-member-type x))))
1030                         (if convert-type
1031                             (convert-back-numeric-type-list result-type-list)
1032                             result-type-list))))
1033                  (numeric-type
1034                   (if convert-type
1035                       (convert-back-numeric-type-list
1036                        (funcall derive-fcn (convert-numeric-type x)))
1037                       (funcall derive-fcn x)))
1038                  (t
1039                   *universal-type*))))
1040         ;; Run down the list of args and derive the type of each one,
1041         ;; saving all of the results in a list.
1042         (let ((results nil))
1043           (dolist (arg arg-list)
1044             (let ((result (deriver arg)))
1045               (if (listp result)
1046                   (setf results (append results result))
1047                   (push result results))))
1048           (if (rest results)
1049               (make-canonical-union-type results)
1050               (first results)))))))
1051
1052 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1053 ;;; two arguments. DERIVE-FCN takes 3 args in this case: the two
1054 ;;; original args and a third which is T to indicate if the two args
1055 ;;; really represent the same continuation. This is useful for
1056 ;;; deriving the type of things like (* x x), which should always be
1057 ;;; positive. If we didn't do this, we wouldn't be able to tell.
1058 (defun two-arg-derive-type (arg1 arg2 derive-fcn fcn
1059                                  &optional (convert-type t))
1060   (declare (type function derive-fcn fcn))
1061   (flet ((deriver (x y same-arg)
1062            (cond ((and (member-type-p x) (member-type-p y))
1063                   (let* ((x (first (member-type-members x)))
1064                          (y (first (member-type-members y)))
1065                          (result (with-float-traps-masked
1066                                      (:underflow :overflow :divide-by-zero
1067                                       :invalid)
1068                                    (funcall fcn x y))))
1069                     (cond ((null result))
1070                           ((and (floatp result) (float-nan-p result))
1071                            (make-numeric-type :class 'float
1072                                               :format (type-of result)
1073                                               :complexp :real))
1074                           (t
1075                            (make-member-type :members (list result))))))
1076                  ((and (member-type-p x) (numeric-type-p y))
1077                   (let* ((x (convert-member-type x))
1078                          (y (if convert-type (convert-numeric-type y) y))
1079                          (result (funcall derive-fcn x y same-arg)))
1080                     (if convert-type
1081                         (convert-back-numeric-type-list result)
1082                         result)))
1083                  ((and (numeric-type-p x) (member-type-p y))
1084                   (let* ((x (if convert-type (convert-numeric-type x) x))
1085                          (y (convert-member-type y))
1086                          (result (funcall derive-fcn x y same-arg)))
1087                     (if convert-type
1088                         (convert-back-numeric-type-list result)
1089                         result)))
1090                  ((and (numeric-type-p x) (numeric-type-p y))
1091                   (let* ((x (if convert-type (convert-numeric-type x) x))
1092                          (y (if convert-type (convert-numeric-type y) y))
1093                          (result (funcall derive-fcn x y same-arg)))
1094                     (if convert-type
1095                         (convert-back-numeric-type-list result)
1096                         result)))
1097                  (t
1098                   *universal-type*))))
1099     (let ((same-arg (same-leaf-ref-p arg1 arg2))
1100           (a1 (prepare-arg-for-derive-type (continuation-type arg1)))
1101           (a2 (prepare-arg-for-derive-type (continuation-type arg2))))
1102       (when (and a1 a2)
1103         (let ((results nil))
1104           (if same-arg
1105               ;; Since the args are the same continuation, just run
1106               ;; down the lists.
1107               (dolist (x a1)
1108                 (let ((result (deriver x x same-arg)))
1109                   (if (listp result)
1110                       (setf results (append results result))
1111                       (push result results))))
1112               ;; Try all pairwise combinations.
1113               (dolist (x a1)
1114                 (dolist (y a2)
1115                   (let ((result (or (deriver x y same-arg)
1116                                     (numeric-contagion x y))))
1117                     (if (listp result)
1118                         (setf results (append results result))
1119                         (push result results))))))
1120           (if (rest results)
1121               (make-canonical-union-type results)
1122               (first results)))))))
1123 \f
1124 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1125 (progn
1126 (defoptimizer (+ derive-type) ((x y))
1127   (derive-integer-type
1128    x y
1129    #'(lambda (x y)
1130        (flet ((frob (x y)
1131                 (if (and x y)
1132                     (+ x y)
1133                     nil)))
1134          (values (frob (numeric-type-low x) (numeric-type-low y))
1135                  (frob (numeric-type-high x) (numeric-type-high y)))))))
1136
1137 (defoptimizer (- derive-type) ((x y))
1138   (derive-integer-type
1139    x y
1140    #'(lambda (x y)
1141        (flet ((frob (x y)
1142                 (if (and x y)
1143                     (- x y)
1144                     nil)))
1145          (values (frob (numeric-type-low x) (numeric-type-high y))
1146                  (frob (numeric-type-high x) (numeric-type-low y)))))))
1147
1148 (defoptimizer (* derive-type) ((x y))
1149   (derive-integer-type
1150    x y
1151    #'(lambda (x y)
1152        (let ((x-low (numeric-type-low x))
1153              (x-high (numeric-type-high x))
1154              (y-low (numeric-type-low y))
1155              (y-high (numeric-type-high y)))
1156          (cond ((not (and x-low y-low))
1157                 (values nil nil))
1158                ((or (minusp x-low) (minusp y-low))
1159                 (if (and x-high y-high)
1160                     (let ((max (* (max (abs x-low) (abs x-high))
1161                                   (max (abs y-low) (abs y-high)))))
1162                       (values (- max) max))
1163                     (values nil nil)))
1164                (t
1165                 (values (* x-low y-low)
1166                         (if (and x-high y-high)
1167                             (* x-high y-high)
1168                             nil))))))))
1169
1170 (defoptimizer (/ derive-type) ((x y))
1171   (numeric-contagion (continuation-type x) (continuation-type y)))
1172
1173 ) ; PROGN
1174
1175 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1176 (progn
1177 (defun +-derive-type-aux (x y same-arg)
1178   (if (and (numeric-type-real-p x)
1179            (numeric-type-real-p y))
1180       (let ((result
1181              (if same-arg
1182                  (let ((x-int (numeric-type->interval x)))
1183                    (interval-add x-int x-int))
1184                  (interval-add (numeric-type->interval x)
1185                                (numeric-type->interval y))))
1186             (result-type (numeric-contagion x y)))
1187         ;; If the result type is a float, we need to be sure to coerce
1188         ;; the bounds into the correct type.
1189         (when (eq (numeric-type-class result-type) 'float)
1190           (setf result (interval-func
1191                         #'(lambda (x)
1192                             (coerce x (or (numeric-type-format result-type)
1193                                           'float)))
1194                         result)))
1195         (make-numeric-type
1196          :class (if (and (eq (numeric-type-class x) 'integer)
1197                          (eq (numeric-type-class y) 'integer))
1198                     ;; The sum of integers is always an integer.
1199                     'integer
1200                     (numeric-type-class result-type))
1201          :format (numeric-type-format result-type)
1202          :low (interval-low result)
1203          :high (interval-high result)))
1204       ;; general contagion
1205       (numeric-contagion x y)))
1206
1207 (defoptimizer (+ derive-type) ((x y))
1208   (two-arg-derive-type x y #'+-derive-type-aux #'+))
1209
1210 (defun --derive-type-aux (x y same-arg)
1211   (if (and (numeric-type-real-p x)
1212            (numeric-type-real-p y))
1213       (let ((result
1214              ;; (- X X) is always 0.
1215              (if same-arg
1216                  (make-interval :low 0 :high 0)
1217                  (interval-sub (numeric-type->interval x)
1218                                (numeric-type->interval y))))
1219             (result-type (numeric-contagion x y)))
1220         ;; If the result type is a float, we need to be sure to coerce
1221         ;; the bounds into the correct type.
1222         (when (eq (numeric-type-class result-type) 'float)
1223           (setf result (interval-func
1224                         #'(lambda (x)
1225                             (coerce x (or (numeric-type-format result-type)
1226                                           'float)))
1227                         result)))
1228         (make-numeric-type
1229          :class (if (and (eq (numeric-type-class x) 'integer)
1230                          (eq (numeric-type-class y) 'integer))
1231                     ;; The difference of integers is always an integer.
1232                     'integer
1233                     (numeric-type-class result-type))
1234          :format (numeric-type-format result-type)
1235          :low (interval-low result)
1236          :high (interval-high result)))
1237       ;; general contagion
1238       (numeric-contagion x y)))
1239
1240 (defoptimizer (- derive-type) ((x y))
1241   (two-arg-derive-type x y #'--derive-type-aux #'-))
1242
1243 (defun *-derive-type-aux (x y same-arg)
1244   (if (and (numeric-type-real-p x)
1245            (numeric-type-real-p y))
1246       (let ((result
1247              ;; (* X X) is always positive, so take care to do it right.
1248              (if same-arg
1249                  (interval-sqr (numeric-type->interval x))
1250                  (interval-mul (numeric-type->interval x)
1251                                (numeric-type->interval y))))
1252             (result-type (numeric-contagion x y)))
1253         ;; If the result type is a float, we need to be sure to coerce
1254         ;; the bounds into the correct type.
1255         (when (eq (numeric-type-class result-type) 'float)
1256           (setf result (interval-func
1257                         #'(lambda (x)
1258                             (coerce x (or (numeric-type-format result-type)
1259                                           'float)))
1260                         result)))
1261         (make-numeric-type
1262          :class (if (and (eq (numeric-type-class x) 'integer)
1263                          (eq (numeric-type-class y) 'integer))
1264                     ;; The product of integers is always an integer.
1265                     'integer
1266                     (numeric-type-class result-type))
1267          :format (numeric-type-format result-type)
1268          :low (interval-low result)
1269          :high (interval-high result)))
1270       (numeric-contagion x y)))
1271
1272 (defoptimizer (* derive-type) ((x y))
1273   (two-arg-derive-type x y #'*-derive-type-aux #'*))
1274
1275 (defun /-derive-type-aux (x y same-arg)
1276   (if (and (numeric-type-real-p x)
1277            (numeric-type-real-p y))
1278       (let ((result
1279              ;; (/ X X) is always 1, except if X can contain 0. In
1280              ;; that case, we shouldn't optimize the division away
1281              ;; because we want 0/0 to signal an error.
1282              (if (and same-arg
1283                       (not (interval-contains-p
1284                             0 (interval-closure (numeric-type->interval y)))))
1285                  (make-interval :low 1 :high 1)
1286                  (interval-div (numeric-type->interval x)
1287                                (numeric-type->interval y))))
1288             (result-type (numeric-contagion x y)))
1289         ;; If the result type is a float, we need to be sure to coerce
1290         ;; the bounds into the correct type.
1291         (when (eq (numeric-type-class result-type) 'float)
1292           (setf result (interval-func
1293                         #'(lambda (x)
1294                             (coerce x (or (numeric-type-format result-type)
1295                                           'float)))
1296                         result)))
1297         (make-numeric-type :class (numeric-type-class result-type)
1298                            :format (numeric-type-format result-type)
1299                            :low (interval-low result)
1300                            :high (interval-high result)))
1301       (numeric-contagion x y)))
1302
1303 (defoptimizer (/ derive-type) ((x y))
1304   (two-arg-derive-type x y #'/-derive-type-aux #'/))
1305
1306 ) ; PROGN
1307
1308 (defun ash-derive-type-aux (n-type shift same-arg)
1309   (declare (ignore same-arg))
1310   ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1311   ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1312   ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1313   ;; two bignums yielding zero) and it's hard to avoid that
1314   ;; calculation in here.
1315   #+(and cmu sb-xc-host)
1316   (when (and (or (typep (numeric-type-low n-type) 'bignum)
1317                  (typep (numeric-type-high n-type) 'bignum))
1318              (or (typep (numeric-type-low shift) 'bignum)
1319                  (typep (numeric-type-high shift) 'bignum)))
1320     (return-from ash-derive-type-aux *universal-type*))
1321   (flet ((ash-outer (n s)
1322            (when (and (fixnump s)
1323                       (<= s 64)
1324                       (> s sb!xc:most-negative-fixnum))
1325              (ash n s)))
1326          ;; KLUDGE: The bare 64's here should be related to
1327          ;; symbolic machine word size values somehow.
1328
1329          (ash-inner (n s)
1330            (if (and (fixnump s)
1331                     (> s sb!xc:most-negative-fixnum))
1332              (ash n (min s 64))
1333              (if (minusp n) -1 0))))
1334     (or (and (csubtypep n-type (specifier-type 'integer))
1335              (csubtypep shift (specifier-type 'integer))
1336              (let ((n-low (numeric-type-low n-type))
1337                    (n-high (numeric-type-high n-type))
1338                    (s-low (numeric-type-low shift))
1339                    (s-high (numeric-type-high shift)))
1340                (make-numeric-type :class 'integer  :complexp :real
1341                                   :low (when n-low
1342                                          (if (minusp n-low)
1343                                            (ash-outer n-low s-high)
1344                                            (ash-inner n-low s-low)))
1345                                   :high (when n-high
1346                                           (if (minusp n-high)
1347                                             (ash-inner n-high s-low)
1348                                             (ash-outer n-high s-high))))))
1349         *universal-type*)))
1350
1351 (defoptimizer (ash derive-type) ((n shift))
1352   (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1353
1354 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1355 (macrolet ((frob (fun)
1356              `#'(lambda (type type2)
1357                   (declare (ignore type2))
1358                   (let ((lo (numeric-type-low type))
1359                         (hi (numeric-type-high type)))
1360                     (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1361
1362   (defoptimizer (%negate derive-type) ((num))
1363     (derive-integer-type num num (frob -))))
1364
1365 (defoptimizer (lognot derive-type) ((int))
1366   (derive-integer-type int int
1367                        (lambda (type type2)
1368                          (declare (ignore type2))
1369                          (let ((lo (numeric-type-low type))
1370                                (hi (numeric-type-high type)))
1371                            (values (if hi (lognot hi) nil)
1372                                    (if lo (lognot lo) nil)
1373                                    (numeric-type-class type)
1374                                    (numeric-type-format type))))))
1375
1376 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1377 (defoptimizer (%negate derive-type) ((num))
1378   (flet ((negate-bound (b)
1379            (and b
1380                 (set-bound (- (type-bound-number b))
1381                            (consp b)))))
1382     (one-arg-derive-type num
1383                          (lambda (type)
1384                            (modified-numeric-type
1385                             type
1386                             :low (negate-bound (numeric-type-high type))
1387                             :high (negate-bound (numeric-type-low type))))
1388                          #'-)))
1389
1390 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1391 (defoptimizer (abs derive-type) ((num))
1392   (let ((type (continuation-type num)))
1393     (if (and (numeric-type-p type)
1394              (eq (numeric-type-class type) 'integer)
1395              (eq (numeric-type-complexp type) :real))
1396         (let ((lo (numeric-type-low type))
1397               (hi (numeric-type-high type)))
1398           (make-numeric-type :class 'integer :complexp :real
1399                              :low (cond ((and hi (minusp hi))
1400                                          (abs hi))
1401                                         (lo
1402                                          (max 0 lo))
1403                                         (t
1404                                          0))
1405                              :high (if (and hi lo)
1406                                        (max (abs hi) (abs lo))
1407                                        nil)))
1408         (numeric-contagion type type))))
1409
1410 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1411 (defun abs-derive-type-aux (type)
1412   (cond ((eq (numeric-type-complexp type) :complex)
1413          ;; The absolute value of a complex number is always a
1414          ;; non-negative float.
1415          (let* ((format (case (numeric-type-class type)
1416                           ((integer rational) 'single-float)
1417                           (t (numeric-type-format type))))
1418                 (bound-format (or format 'float)))
1419            (make-numeric-type :class 'float
1420                               :format format
1421                               :complexp :real
1422                               :low (coerce 0 bound-format)
1423                               :high nil)))
1424         (t
1425          ;; The absolute value of a real number is a non-negative real
1426          ;; of the same type.
1427          (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1428                 (class (numeric-type-class type))
1429                 (format (numeric-type-format type))
1430                 (bound-type (or format class 'real)))
1431            (make-numeric-type
1432             :class class
1433             :format format
1434             :complexp :real
1435             :low (coerce-numeric-bound (interval-low abs-bnd) bound-type)
1436             :high (coerce-numeric-bound
1437                    (interval-high abs-bnd) bound-type))))))
1438
1439 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1440 (defoptimizer (abs derive-type) ((num))
1441   (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1442
1443 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1444 (defoptimizer (truncate derive-type) ((number divisor))
1445   (let ((number-type (continuation-type number))
1446         (divisor-type (continuation-type divisor))
1447         (integer-type (specifier-type 'integer)))
1448     (if (and (numeric-type-p number-type)
1449              (csubtypep number-type integer-type)
1450              (numeric-type-p divisor-type)
1451              (csubtypep divisor-type integer-type))
1452         (let ((number-low (numeric-type-low number-type))
1453               (number-high (numeric-type-high number-type))
1454               (divisor-low (numeric-type-low divisor-type))
1455               (divisor-high (numeric-type-high divisor-type)))
1456           (values-specifier-type
1457            `(values ,(integer-truncate-derive-type number-low number-high
1458                                                    divisor-low divisor-high)
1459                     ,(integer-rem-derive-type number-low number-high
1460                                               divisor-low divisor-high))))
1461         *universal-type*)))
1462
1463 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1464 (progn
1465
1466 (defun rem-result-type (number-type divisor-type)
1467   ;; Figure out what the remainder type is. The remainder is an
1468   ;; integer if both args are integers; a rational if both args are
1469   ;; rational; and a float otherwise.
1470   (cond ((and (csubtypep number-type (specifier-type 'integer))
1471               (csubtypep divisor-type (specifier-type 'integer)))
1472          'integer)
1473         ((and (csubtypep number-type (specifier-type 'rational))
1474               (csubtypep divisor-type (specifier-type 'rational)))
1475          'rational)
1476         ((and (csubtypep number-type (specifier-type 'float))
1477               (csubtypep divisor-type (specifier-type 'float)))
1478          ;; Both are floats so the result is also a float, of
1479          ;; the largest type.
1480          (or (float-format-max (numeric-type-format number-type)
1481                                (numeric-type-format divisor-type))
1482              'float))
1483         ((and (csubtypep number-type (specifier-type 'float))
1484               (csubtypep divisor-type (specifier-type 'rational)))
1485          ;; One of the arguments is a float and the other is a
1486          ;; rational. The remainder is a float of the same
1487          ;; type.
1488          (or (numeric-type-format number-type) 'float))
1489         ((and (csubtypep divisor-type (specifier-type 'float))
1490               (csubtypep number-type (specifier-type 'rational)))
1491          ;; One of the arguments is a float and the other is a
1492          ;; rational. The remainder is a float of the same
1493          ;; type.
1494          (or (numeric-type-format divisor-type) 'float))
1495         (t
1496          ;; Some unhandled combination. This usually means both args
1497          ;; are REAL so the result is a REAL.
1498          'real)))
1499
1500 (defun truncate-derive-type-quot (number-type divisor-type)
1501   (let* ((rem-type (rem-result-type number-type divisor-type))
1502          (number-interval (numeric-type->interval number-type))
1503          (divisor-interval (numeric-type->interval divisor-type)))
1504     ;;(declare (type (member '(integer rational float)) rem-type))
1505     ;; We have real numbers now.
1506     (cond ((eq rem-type 'integer)
1507            ;; Since the remainder type is INTEGER, both args are
1508            ;; INTEGERs.
1509            (let* ((res (integer-truncate-derive-type
1510                         (interval-low number-interval)
1511                         (interval-high number-interval)
1512                         (interval-low divisor-interval)
1513                         (interval-high divisor-interval))))
1514              (specifier-type (if (listp res) res 'integer))))
1515           (t
1516            (let ((quot (truncate-quotient-bound
1517                         (interval-div number-interval
1518                                       divisor-interval))))
1519              (specifier-type `(integer ,(or (interval-low quot) '*)
1520                                        ,(or (interval-high quot) '*))))))))
1521
1522 (defun truncate-derive-type-rem (number-type divisor-type)
1523   (let* ((rem-type (rem-result-type number-type divisor-type))
1524          (number-interval (numeric-type->interval number-type))
1525          (divisor-interval (numeric-type->interval divisor-type))
1526          (rem (truncate-rem-bound number-interval divisor-interval)))
1527     ;;(declare (type (member '(integer rational float)) rem-type))
1528     ;; We have real numbers now.
1529     (cond ((eq rem-type 'integer)
1530            ;; Since the remainder type is INTEGER, both args are
1531            ;; INTEGERs.
1532            (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1533                                        ,(or (interval-high rem) '*))))
1534           (t
1535            (multiple-value-bind (class format)
1536                (ecase rem-type
1537                  (integer
1538                   (values 'integer nil))
1539                  (rational
1540                   (values 'rational nil))
1541                  ((or single-float double-float #!+long-float long-float)
1542                   (values 'float rem-type))
1543                  (float
1544                   (values 'float nil))
1545                  (real
1546                   (values nil nil)))
1547              (when (member rem-type '(float single-float double-float
1548                                             #!+long-float long-float))
1549                (setf rem (interval-func #'(lambda (x)
1550                                             (coerce x rem-type))
1551                                         rem)))
1552              (make-numeric-type :class class
1553                                 :format format
1554                                 :low (interval-low rem)
1555                                 :high (interval-high rem)))))))
1556
1557 (defun truncate-derive-type-quot-aux (num div same-arg)
1558   (declare (ignore same-arg))
1559   (if (and (numeric-type-real-p num)
1560            (numeric-type-real-p div))
1561       (truncate-derive-type-quot num div)
1562       *empty-type*))
1563
1564 (defun truncate-derive-type-rem-aux (num div same-arg)
1565   (declare (ignore same-arg))
1566   (if (and (numeric-type-real-p num)
1567            (numeric-type-real-p div))
1568       (truncate-derive-type-rem num div)
1569       *empty-type*))
1570
1571 (defoptimizer (truncate derive-type) ((number divisor))
1572   (let ((quot (two-arg-derive-type number divisor
1573                                    #'truncate-derive-type-quot-aux #'truncate))
1574         (rem (two-arg-derive-type number divisor
1575                                   #'truncate-derive-type-rem-aux #'rem)))
1576     (when (and quot rem)
1577       (make-values-type :required (list quot rem)))))
1578
1579 (defun ftruncate-derive-type-quot (number-type divisor-type)
1580   ;; The bounds are the same as for truncate. However, the first
1581   ;; result is a float of some type. We need to determine what that
1582   ;; type is. Basically it's the more contagious of the two types.
1583   (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1584         (res-type (numeric-contagion number-type divisor-type)))
1585     (make-numeric-type :class 'float
1586                        :format (numeric-type-format res-type)
1587                        :low (numeric-type-low q-type)
1588                        :high (numeric-type-high q-type))))
1589
1590 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1591   (declare (ignore same-arg))
1592   (if (and (numeric-type-real-p n)
1593            (numeric-type-real-p d))
1594       (ftruncate-derive-type-quot n d)
1595       *empty-type*))
1596
1597 (defoptimizer (ftruncate derive-type) ((number divisor))
1598   (let ((quot
1599          (two-arg-derive-type number divisor
1600                               #'ftruncate-derive-type-quot-aux #'ftruncate))
1601         (rem (two-arg-derive-type number divisor
1602                                   #'truncate-derive-type-rem-aux #'rem)))
1603     (when (and quot rem)
1604       (make-values-type :required (list quot rem)))))
1605
1606 (defun %unary-truncate-derive-type-aux (number)
1607   (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1608
1609 (defoptimizer (%unary-truncate derive-type) ((number))
1610   (one-arg-derive-type number
1611                        #'%unary-truncate-derive-type-aux
1612                        #'%unary-truncate))
1613
1614 ;;; Define optimizers for FLOOR and CEILING.
1615 (macrolet
1616     ((def (name q-name r-name)
1617        (let ((q-aux (symbolicate q-name "-AUX"))
1618              (r-aux (symbolicate r-name "-AUX")))
1619          `(progn
1620            ;; Compute type of quotient (first) result.
1621            (defun ,q-aux (number-type divisor-type)
1622              (let* ((number-interval
1623                      (numeric-type->interval number-type))
1624                     (divisor-interval
1625                      (numeric-type->interval divisor-type))
1626                     (quot (,q-name (interval-div number-interval
1627                                                  divisor-interval))))
1628                (specifier-type `(integer ,(or (interval-low quot) '*)
1629                                          ,(or (interval-high quot) '*)))))
1630            ;; Compute type of remainder.
1631            (defun ,r-aux (number-type divisor-type)
1632              (let* ((divisor-interval
1633                      (numeric-type->interval divisor-type))
1634                     (rem (,r-name divisor-interval))
1635                     (result-type (rem-result-type number-type divisor-type)))
1636                (multiple-value-bind (class format)
1637                    (ecase result-type
1638                      (integer
1639                       (values 'integer nil))
1640                      (rational
1641                       (values 'rational nil))
1642                      ((or single-float double-float #!+long-float long-float)
1643                       (values 'float result-type))
1644                      (float
1645                       (values 'float nil))
1646                      (real
1647                       (values nil nil)))
1648                  (when (member result-type '(float single-float double-float
1649                                              #!+long-float long-float))
1650                    ;; Make sure that the limits on the interval have
1651                    ;; the right type.
1652                    (setf rem (interval-func (lambda (x)
1653                                               (coerce x result-type))
1654                                             rem)))
1655                  (make-numeric-type :class class
1656                                     :format format
1657                                     :low (interval-low rem)
1658                                     :high (interval-high rem)))))
1659            ;; the optimizer itself
1660            (defoptimizer (,name derive-type) ((number divisor))
1661              (flet ((derive-q (n d same-arg)
1662                       (declare (ignore same-arg))
1663                       (if (and (numeric-type-real-p n)
1664                                (numeric-type-real-p d))
1665                           (,q-aux n d)
1666                           *empty-type*))
1667                     (derive-r (n d same-arg)
1668                       (declare (ignore same-arg))
1669                       (if (and (numeric-type-real-p n)
1670                                (numeric-type-real-p d))
1671                           (,r-aux n d)
1672                           *empty-type*)))
1673                (let ((quot (two-arg-derive-type
1674                             number divisor #'derive-q #',name))
1675                      (rem (two-arg-derive-type
1676                            number divisor #'derive-r #'mod)))
1677                  (when (and quot rem)
1678                    (make-values-type :required (list quot rem))))))))))
1679
1680   (def floor floor-quotient-bound floor-rem-bound)
1681   (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1682
1683 ;;; Define optimizers for FFLOOR and FCEILING
1684 (macrolet ((def (name q-name r-name)
1685              (let ((q-aux (symbolicate "F" q-name "-AUX"))
1686                    (r-aux (symbolicate r-name "-AUX")))
1687                `(progn
1688                   ;; Compute type of quotient (first) result.
1689                   (defun ,q-aux (number-type divisor-type)
1690                     (let* ((number-interval
1691                             (numeric-type->interval number-type))
1692                            (divisor-interval
1693                             (numeric-type->interval divisor-type))
1694                            (quot (,q-name (interval-div number-interval
1695                                                         divisor-interval)))
1696                            (res-type (numeric-contagion number-type
1697                                                         divisor-type)))
1698                       (make-numeric-type
1699                        :class (numeric-type-class res-type)
1700                        :format (numeric-type-format res-type)
1701                        :low  (interval-low quot)
1702                        :high (interval-high quot))))
1703
1704                   (defoptimizer (,name derive-type) ((number divisor))
1705                     (flet ((derive-q (n d same-arg)
1706                              (declare (ignore same-arg))
1707                              (if (and (numeric-type-real-p n)
1708                                       (numeric-type-real-p d))
1709                                  (,q-aux n d)
1710                                  *empty-type*))
1711                            (derive-r (n d same-arg)
1712                              (declare (ignore same-arg))
1713                              (if (and (numeric-type-real-p n)
1714                                       (numeric-type-real-p d))
1715                                  (,r-aux n d)
1716                                  *empty-type*)))
1717                       (let ((quot (two-arg-derive-type
1718                                    number divisor #'derive-q #',name))
1719                             (rem (two-arg-derive-type
1720                                   number divisor #'derive-r #'mod)))
1721                         (when (and quot rem)
1722                           (make-values-type :required (list quot rem))))))))))
1723
1724   (def ffloor floor-quotient-bound floor-rem-bound)
1725   (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1726
1727 ;;; functions to compute the bounds on the quotient and remainder for
1728 ;;; the FLOOR function
1729 (defun floor-quotient-bound (quot)
1730   ;; Take the floor of the quotient and then massage it into what we
1731   ;; need.
1732   (let ((lo (interval-low quot))
1733         (hi (interval-high quot)))
1734     ;; Take the floor of the lower bound. The result is always a
1735     ;; closed lower bound.
1736     (setf lo (if lo
1737                  (floor (type-bound-number lo))
1738                  nil))
1739     ;; For the upper bound, we need to be careful.
1740     (setf hi
1741           (cond ((consp hi)
1742                  ;; An open bound. We need to be careful here because
1743                  ;; the floor of '(10.0) is 9, but the floor of
1744                  ;; 10.0 is 10.
1745                  (multiple-value-bind (q r) (floor (first hi))
1746                    (if (zerop r)
1747                        (1- q)
1748                        q)))
1749                 (hi
1750                  ;; A closed bound, so the answer is obvious.
1751                  (floor hi))
1752                 (t
1753                  hi)))
1754     (make-interval :low lo :high hi)))
1755 (defun floor-rem-bound (div)
1756   ;; The remainder depends only on the divisor. Try to get the
1757   ;; correct sign for the remainder if we can.
1758   (case (interval-range-info div)
1759     (+
1760      ;; The divisor is always positive.
1761      (let ((rem (interval-abs div)))
1762        (setf (interval-low rem) 0)
1763        (when (and (numberp (interval-high rem))
1764                   (not (zerop (interval-high rem))))
1765          ;; The remainder never contains the upper bound. However,
1766          ;; watch out for the case where the high limit is zero!
1767          (setf (interval-high rem) (list (interval-high rem))))
1768        rem))
1769     (-
1770      ;; The divisor is always negative.
1771      (let ((rem (interval-neg (interval-abs div))))
1772        (setf (interval-high rem) 0)
1773        (when (numberp (interval-low rem))
1774          ;; The remainder never contains the lower bound.
1775          (setf (interval-low rem) (list (interval-low rem))))
1776        rem))
1777     (otherwise
1778      ;; The divisor can be positive or negative. All bets off. The
1779      ;; magnitude of remainder is the maximum value of the divisor.
1780      (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1781        ;; The bound never reaches the limit, so make the interval open.
1782        (make-interval :low (if limit
1783                                (list (- limit))
1784                                limit)
1785                       :high (list limit))))))
1786 #| Test cases
1787 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
1788 => #S(INTERVAL :LOW 0 :HIGH 10)
1789 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1790 => #S(INTERVAL :LOW 0 :HIGH 10)
1791 (floor-quotient-bound (make-interval :low 0.3 :high 10))
1792 => #S(INTERVAL :LOW 0 :HIGH 10)
1793 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
1794 => #S(INTERVAL :LOW 0 :HIGH 9)
1795 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
1796 => #S(INTERVAL :LOW 0 :HIGH 10)
1797 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
1798 => #S(INTERVAL :LOW 0 :HIGH 10)
1799 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1800 => #S(INTERVAL :LOW -2 :HIGH 10)
1801 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1802 => #S(INTERVAL :LOW -1 :HIGH 10)
1803 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
1804 => #S(INTERVAL :LOW -1 :HIGH 10)
1805
1806 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
1807 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1808 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
1809 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1810 (floor-rem-bound (make-interval :low -10 :high -2.3))
1811 #S(INTERVAL :LOW (-10) :HIGH 0)
1812 (floor-rem-bound (make-interval :low 0.3 :high 10))
1813 => #S(INTERVAL :LOW 0 :HIGH '(10))
1814 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
1815 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
1816 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
1817 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1818 |#
1819 \f
1820 ;;; same functions for CEILING
1821 (defun ceiling-quotient-bound (quot)
1822   ;; Take the ceiling of the quotient and then massage it into what we
1823   ;; need.
1824   (let ((lo (interval-low quot))
1825         (hi (interval-high quot)))
1826     ;; Take the ceiling of the upper bound. The result is always a
1827     ;; closed upper bound.
1828     (setf hi (if hi
1829                  (ceiling (type-bound-number hi))
1830                  nil))
1831     ;; For the lower bound, we need to be careful.
1832     (setf lo
1833           (cond ((consp lo)
1834                  ;; An open bound. We need to be careful here because
1835                  ;; the ceiling of '(10.0) is 11, but the ceiling of
1836                  ;; 10.0 is 10.
1837                  (multiple-value-bind (q r) (ceiling (first lo))
1838                    (if (zerop r)
1839                        (1+ q)
1840                        q)))
1841                 (lo
1842                  ;; A closed bound, so the answer is obvious.
1843                  (ceiling lo))
1844                 (t
1845                  lo)))
1846     (make-interval :low lo :high hi)))
1847 (defun ceiling-rem-bound (div)
1848   ;; The remainder depends only on the divisor. Try to get the
1849   ;; correct sign for the remainder if we can.
1850   (case (interval-range-info div)
1851     (+
1852      ;; Divisor is always positive. The remainder is negative.
1853      (let ((rem (interval-neg (interval-abs div))))
1854        (setf (interval-high rem) 0)
1855        (when (and (numberp (interval-low rem))
1856                   (not (zerop (interval-low rem))))
1857          ;; The remainder never contains the upper bound. However,
1858          ;; watch out for the case when the upper bound is zero!
1859          (setf (interval-low rem) (list (interval-low rem))))
1860        rem))
1861     (-
1862      ;; Divisor is always negative. The remainder is positive
1863      (let ((rem (interval-abs div)))
1864        (setf (interval-low rem) 0)
1865        (when (numberp (interval-high rem))
1866          ;; The remainder never contains the lower bound.
1867          (setf (interval-high rem) (list (interval-high rem))))
1868        rem))
1869     (otherwise
1870      ;; The divisor can be positive or negative. All bets off. The
1871      ;; magnitude of remainder is the maximum value of the divisor.
1872      (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1873        ;; The bound never reaches the limit, so make the interval open.
1874        (make-interval :low (if limit
1875                                (list (- limit))
1876                                limit)
1877                       :high (list limit))))))
1878
1879 #| Test cases
1880 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
1881 => #S(INTERVAL :LOW 1 :HIGH 11)
1882 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1883 => #S(INTERVAL :LOW 1 :HIGH 11)
1884 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
1885 => #S(INTERVAL :LOW 1 :HIGH 10)
1886 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
1887 => #S(INTERVAL :LOW 1 :HIGH 10)
1888 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
1889 => #S(INTERVAL :LOW 1 :HIGH 11)
1890 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
1891 => #S(INTERVAL :LOW 1 :HIGH 11)
1892 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1893 => #S(INTERVAL :LOW -1 :HIGH 11)
1894 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1895 => #S(INTERVAL :LOW 0 :HIGH 11)
1896 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
1897 => #S(INTERVAL :LOW -1 :HIGH 11)
1898
1899 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
1900 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
1901 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
1902 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1903 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
1904 => #S(INTERVAL :LOW 0 :HIGH (10))
1905 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
1906 => #S(INTERVAL :LOW (-10) :HIGH 0)
1907 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
1908 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
1909 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
1910 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1911 |#
1912 \f
1913 (defun truncate-quotient-bound (quot)
1914   ;; For positive quotients, truncate is exactly like floor. For
1915   ;; negative quotients, truncate is exactly like ceiling. Otherwise,
1916   ;; it's the union of the two pieces.
1917   (case (interval-range-info quot)
1918     (+
1919      ;; just like FLOOR
1920      (floor-quotient-bound quot))
1921     (-
1922      ;; just like CEILING
1923      (ceiling-quotient-bound quot))
1924     (otherwise
1925      ;; Split the interval into positive and negative pieces, compute
1926      ;; the result for each piece and put them back together.
1927      (destructuring-bind (neg pos) (interval-split 0 quot t t)
1928        (interval-merge-pair (ceiling-quotient-bound neg)
1929                             (floor-quotient-bound pos))))))
1930
1931 (defun truncate-rem-bound (num div)
1932   ;; This is significantly more complicated than FLOOR or CEILING. We
1933   ;; need both the number and the divisor to determine the range. The
1934   ;; basic idea is to split the ranges of NUM and DEN into positive
1935   ;; and negative pieces and deal with each of the four possibilities
1936   ;; in turn.
1937   (case (interval-range-info num)
1938     (+
1939      (case (interval-range-info div)
1940        (+
1941         (floor-rem-bound div))
1942        (-
1943         (ceiling-rem-bound div))
1944        (otherwise
1945         (destructuring-bind (neg pos) (interval-split 0 div t t)
1946           (interval-merge-pair (truncate-rem-bound num neg)
1947                                (truncate-rem-bound num pos))))))
1948     (-
1949      (case (interval-range-info div)
1950        (+
1951         (ceiling-rem-bound div))
1952        (-
1953         (floor-rem-bound div))
1954        (otherwise
1955         (destructuring-bind (neg pos) (interval-split 0 div t t)
1956           (interval-merge-pair (truncate-rem-bound num neg)
1957                                (truncate-rem-bound num pos))))))
1958     (otherwise
1959      (destructuring-bind (neg pos) (interval-split 0 num t t)
1960        (interval-merge-pair (truncate-rem-bound neg div)
1961                             (truncate-rem-bound pos div))))))
1962 ) ; PROGN
1963
1964 ;;; Derive useful information about the range. Returns three values:
1965 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
1966 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
1967 ;;; - The abs of the maximal value if there is one, or nil if it is
1968 ;;;   unbounded.
1969 (defun numeric-range-info (low high)
1970   (cond ((and low (not (minusp low)))
1971          (values '+ low high))
1972         ((and high (not (plusp high)))
1973          (values '- (- high) (if low (- low) nil)))
1974         (t
1975          (values nil 0 (and low high (max (- low) high))))))
1976
1977 (defun integer-truncate-derive-type
1978        (number-low number-high divisor-low divisor-high)
1979   ;; The result cannot be larger in magnitude than the number, but the
1980   ;; sign might change. If we can determine the sign of either the
1981   ;; number or the divisor, we can eliminate some of the cases.
1982   (multiple-value-bind (number-sign number-min number-max)
1983       (numeric-range-info number-low number-high)
1984     (multiple-value-bind (divisor-sign divisor-min divisor-max)
1985         (numeric-range-info divisor-low divisor-high)
1986       (when (and divisor-max (zerop divisor-max))
1987         ;; We've got a problem: guaranteed division by zero.
1988         (return-from integer-truncate-derive-type t))
1989       (when (zerop divisor-min)
1990         ;; We'll assume that they aren't going to divide by zero.
1991         (incf divisor-min))
1992       (cond ((and number-sign divisor-sign)
1993              ;; We know the sign of both.
1994              (if (eq number-sign divisor-sign)
1995                  ;; Same sign, so the result will be positive.
1996                  `(integer ,(if divisor-max
1997                                 (truncate number-min divisor-max)
1998                                 0)
1999                            ,(if number-max
2000                                 (truncate number-max divisor-min)
2001                                 '*))
2002                  ;; Different signs, the result will be negative.
2003                  `(integer ,(if number-max
2004                                 (- (truncate number-max divisor-min))
2005                                 '*)
2006                            ,(if divisor-max
2007                                 (- (truncate number-min divisor-max))
2008                                 0))))
2009             ((eq divisor-sign '+)
2010              ;; The divisor is positive. Therefore, the number will just
2011              ;; become closer to zero.
2012              `(integer ,(if number-low
2013                             (truncate number-low divisor-min)
2014                             '*)
2015                        ,(if number-high
2016                             (truncate number-high divisor-min)
2017                             '*)))
2018             ((eq divisor-sign '-)
2019              ;; The divisor is negative. Therefore, the absolute value of
2020              ;; the number will become closer to zero, but the sign will also
2021              ;; change.
2022              `(integer ,(if number-high
2023                             (- (truncate number-high divisor-min))
2024                             '*)
2025                        ,(if number-low
2026                             (- (truncate number-low divisor-min))
2027                             '*)))
2028             ;; The divisor could be either positive or negative.
2029             (number-max
2030              ;; The number we are dividing has a bound. Divide that by the
2031              ;; smallest posible divisor.
2032              (let ((bound (truncate number-max divisor-min)))
2033                `(integer ,(- bound) ,bound)))
2034             (t
2035              ;; The number we are dividing is unbounded, so we can't tell
2036              ;; anything about the result.
2037              `integer)))))
2038
2039 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2040 (defun integer-rem-derive-type
2041        (number-low number-high divisor-low divisor-high)
2042   (if (and divisor-low divisor-high)
2043       ;; We know the range of the divisor, and the remainder must be
2044       ;; smaller than the divisor. We can tell the sign of the
2045       ;; remainer if we know the sign of the number.
2046       (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2047         `(integer ,(if (or (null number-low)
2048                            (minusp number-low))
2049                        (- divisor-max)
2050                        0)
2051                   ,(if (or (null number-high)
2052                            (plusp number-high))
2053                        divisor-max
2054                        0)))
2055       ;; The divisor is potentially either very positive or very
2056       ;; negative. Therefore, the remainer is unbounded, but we might
2057       ;; be able to tell something about the sign from the number.
2058       `(integer ,(if (and number-low (not (minusp number-low)))
2059                      ;; The number we are dividing is positive.
2060                      ;; Therefore, the remainder must be positive.
2061                      0
2062                      '*)
2063                 ,(if (and number-high (not (plusp number-high)))
2064                      ;; The number we are dividing is negative.
2065                      ;; Therefore, the remainder must be negative.
2066                      0
2067                      '*))))
2068
2069 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2070 (defoptimizer (random derive-type) ((bound &optional state))
2071   (let ((type (continuation-type bound)))
2072     (when (numeric-type-p type)
2073       (let ((class (numeric-type-class type))
2074             (high (numeric-type-high type))
2075             (format (numeric-type-format type)))
2076         (make-numeric-type
2077          :class class
2078          :format format
2079          :low (coerce 0 (or format class 'real))
2080          :high (cond ((not high) nil)
2081                      ((eq class 'integer) (max (1- high) 0))
2082                      ((or (consp high) (zerop high)) high)
2083                      (t `(,high))))))))
2084
2085 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2086 (defun random-derive-type-aux (type)
2087   (let ((class (numeric-type-class type))
2088         (high (numeric-type-high type))
2089         (format (numeric-type-format type)))
2090     (make-numeric-type
2091          :class class
2092          :format format
2093          :low (coerce 0 (or format class 'real))
2094          :high (cond ((not high) nil)
2095                      ((eq class 'integer) (max (1- high) 0))
2096                      ((or (consp high) (zerop high)) high)
2097                      (t `(,high))))))
2098
2099 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2100 (defoptimizer (random derive-type) ((bound &optional state))
2101   (one-arg-derive-type bound #'random-derive-type-aux nil))
2102 \f
2103 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2104
2105 ;;; Return the maximum number of bits an integer of the supplied type
2106 ;;; can take up, or NIL if it is unbounded. The second (third) value
2107 ;;; is T if the integer can be positive (negative) and NIL if not.
2108 ;;; Zero counts as positive.
2109 (defun integer-type-length (type)
2110   (if (numeric-type-p type)
2111       (let ((min (numeric-type-low type))
2112             (max (numeric-type-high type)))
2113         (values (and min max (max (integer-length min) (integer-length max)))
2114                 (or (null max) (not (minusp max)))
2115                 (or (null min) (minusp min))))
2116       (values nil t t)))
2117
2118 (defun logand-derive-type-aux (x y &optional same-leaf)
2119   (declare (ignore same-leaf))
2120   (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2121     (declare (ignore x-pos))
2122     (multiple-value-bind (y-len y-pos y-neg) (integer-type-length  y)
2123       (declare (ignore y-pos))
2124       (if (not x-neg)
2125           ;; X must be positive.
2126           (if (not y-neg)
2127               ;; They must both be positive.
2128               (cond ((or (null x-len) (null y-len))
2129                      (specifier-type 'unsigned-byte))
2130                     ((or (zerop x-len) (zerop y-len))
2131                      (specifier-type '(integer 0 0)))
2132                     (t
2133                      (specifier-type `(unsigned-byte ,(min x-len y-len)))))
2134               ;; X is positive, but Y might be negative.
2135               (cond ((null x-len)
2136                      (specifier-type 'unsigned-byte))
2137                     ((zerop x-len)
2138                      (specifier-type '(integer 0 0)))
2139                     (t
2140                      (specifier-type `(unsigned-byte ,x-len)))))
2141           ;; X might be negative.
2142           (if (not y-neg)
2143               ;; Y must be positive.
2144               (cond ((null y-len)
2145                      (specifier-type 'unsigned-byte))
2146                     ((zerop y-len)
2147                      (specifier-type '(integer 0 0)))
2148                     (t
2149                      (specifier-type
2150                       `(unsigned-byte ,y-len))))
2151               ;; Either might be negative.
2152               (if (and x-len y-len)
2153                   ;; The result is bounded.
2154                   (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2155                   ;; We can't tell squat about the result.
2156                   (specifier-type 'integer)))))))
2157
2158 (defun logior-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     (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2162       (cond
2163        ((and (not x-neg) (not y-neg))
2164         ;; Both are positive.
2165         (if (and x-len y-len (zerop x-len) (zerop y-len))
2166             (specifier-type '(integer 0 0))
2167             (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2168                                              (max x-len y-len)
2169                                              '*)))))
2170        ((not x-pos)
2171         ;; X must be negative.
2172         (if (not y-pos)
2173             ;; Both are negative. The result is going to be negative
2174             ;; and be the same length or shorter than the smaller.
2175             (if (and x-len y-len)
2176                 ;; It's bounded.
2177                 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2178                 ;; It's unbounded.
2179                 (specifier-type '(integer * -1)))
2180             ;; X is negative, but we don't know about Y. The result
2181             ;; will be negative, but no more negative than X.
2182             (specifier-type
2183              `(integer ,(or (numeric-type-low x) '*)
2184                        -1))))
2185        (t
2186         ;; X might be either positive or negative.
2187         (if (not y-pos)
2188             ;; But Y is negative. The result will be negative.
2189             (specifier-type
2190              `(integer ,(or (numeric-type-low y) '*)
2191                        -1))
2192             ;; We don't know squat about either. It won't get any bigger.
2193             (if (and x-len y-len)
2194                 ;; Bounded.
2195                 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2196                 ;; Unbounded.
2197                 (specifier-type 'integer))))))))
2198
2199 (defun logxor-derive-type-aux (x y &optional same-leaf)
2200   (declare (ignore same-leaf))
2201   (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2202     (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2203       (cond
2204        ((or (and (not x-neg) (not y-neg))
2205             (and (not x-pos) (not y-pos)))
2206         ;; Either both are negative or both are positive. The result
2207         ;; will be positive, and as long as the longer.
2208         (if (and x-len y-len (zerop x-len) (zerop y-len))
2209             (specifier-type '(integer 0 0))
2210             (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2211                                              (max x-len y-len)
2212                                              '*)))))
2213        ((or (and (not x-pos) (not y-neg))
2214             (and (not y-neg) (not y-pos)))
2215         ;; Either X is negative and Y is positive of vice-versa. The
2216         ;; result will be negative.
2217         (specifier-type `(integer ,(if (and x-len y-len)
2218                                        (ash -1 (max x-len y-len))
2219                                        '*)
2220                                   -1)))
2221        ;; We can't tell what the sign of the result is going to be.
2222        ;; All we know is that we don't create new bits.
2223        ((and x-len y-len)
2224         (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2225        (t
2226         (specifier-type 'integer))))))
2227
2228 (macrolet ((deffrob (logfcn)
2229              (let ((fcn-aux (symbolicate logfcn "-DERIVE-TYPE-AUX")))
2230              `(defoptimizer (,logfcn derive-type) ((x y))
2231                 (two-arg-derive-type x y #',fcn-aux #',logfcn)))))
2232   (deffrob logand)
2233   (deffrob logior)
2234   (deffrob logxor))
2235 \f
2236 ;;;; miscellaneous derive-type methods
2237
2238 (defoptimizer (integer-length derive-type) ((x))
2239   (let ((x-type (continuation-type x)))
2240     (when (and (numeric-type-p x-type)
2241                (csubtypep x-type (specifier-type 'integer)))
2242       ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2243       ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically.  Be
2244       ;; careful about LO or HI being NIL, though.  Also, if 0 is
2245       ;; contained in X, the lower bound is obviously 0.
2246       (flet ((null-or-min (a b)
2247                (and a b (min (integer-length a)
2248                              (integer-length b))))
2249              (null-or-max (a b)
2250                (and a b (max (integer-length a)
2251                              (integer-length b)))))
2252         (let* ((min (numeric-type-low x-type))
2253                (max (numeric-type-high x-type))
2254                (min-len (null-or-min min max))
2255                (max-len (null-or-max min max)))
2256           (when (ctypep 0 x-type)
2257             (setf min-len 0))
2258           (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2259
2260 (defoptimizer (code-char derive-type) ((code))
2261   (specifier-type 'base-char))
2262
2263 (defoptimizer (values derive-type) ((&rest values))
2264   (values-specifier-type
2265    `(values ,@(mapcar (lambda (x)
2266                         (type-specifier (continuation-type x)))
2267                       values))))
2268 \f
2269 ;;;; byte operations
2270 ;;;;
2271 ;;;; We try to turn byte operations into simple logical operations.
2272 ;;;; First, we convert byte specifiers into separate size and position
2273 ;;;; arguments passed to internal %FOO functions. We then attempt to
2274 ;;;; transform the %FOO functions into boolean operations when the
2275 ;;;; size and position are constant and the operands are fixnums.
2276
2277 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2278            ;; expressions that evaluate to the SIZE and POSITION of
2279            ;; the byte-specifier form SPEC. We may wrap a let around
2280            ;; the result of the body to bind some variables.
2281            ;;
2282            ;; If the spec is a BYTE form, then bind the vars to the
2283            ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2284            ;; and BYTE-POSITION. The goal of this transformation is to
2285            ;; avoid consing up byte specifiers and then immediately
2286            ;; throwing them away.
2287            (with-byte-specifier ((size-var pos-var spec) &body body)
2288              (once-only ((spec `(macroexpand ,spec))
2289                          (temp '(gensym)))
2290                         `(if (and (consp ,spec)
2291                                   (eq (car ,spec) 'byte)
2292                                   (= (length ,spec) 3))
2293                         (let ((,size-var (second ,spec))
2294                               (,pos-var (third ,spec)))
2295                           ,@body)
2296                         (let ((,size-var `(byte-size ,,temp))
2297                               (,pos-var `(byte-position ,,temp)))
2298                           `(let ((,,temp ,,spec))
2299                              ,,@body))))))
2300
2301   (define-source-transform ldb (spec int)
2302     (with-byte-specifier (size pos spec)
2303       `(%ldb ,size ,pos ,int)))
2304
2305   (define-source-transform dpb (newbyte spec int)
2306     (with-byte-specifier (size pos spec)
2307       `(%dpb ,newbyte ,size ,pos ,int)))
2308
2309   (define-source-transform mask-field (spec int)
2310     (with-byte-specifier (size pos spec)
2311       `(%mask-field ,size ,pos ,int)))
2312
2313   (define-source-transform deposit-field (newbyte spec int)
2314     (with-byte-specifier (size pos spec)
2315       `(%deposit-field ,newbyte ,size ,pos ,int))))
2316
2317 (defoptimizer (%ldb derive-type) ((size posn num))
2318   (let ((size (continuation-type size)))
2319     (if (and (numeric-type-p size)
2320              (csubtypep size (specifier-type 'integer)))
2321         (let ((size-high (numeric-type-high size)))
2322           (if (and size-high (<= size-high sb!vm:n-word-bits))
2323               (specifier-type `(unsigned-byte ,size-high))
2324               (specifier-type 'unsigned-byte)))
2325         *universal-type*)))
2326
2327 (defoptimizer (%mask-field derive-type) ((size posn num))
2328   (let ((size (continuation-type size))
2329         (posn (continuation-type posn)))
2330     (if (and (numeric-type-p size)
2331              (csubtypep size (specifier-type 'integer))
2332              (numeric-type-p posn)
2333              (csubtypep posn (specifier-type 'integer)))
2334         (let ((size-high (numeric-type-high size))
2335               (posn-high (numeric-type-high posn)))
2336           (if (and size-high posn-high
2337                    (<= (+ size-high posn-high) sb!vm:n-word-bits))
2338               (specifier-type `(unsigned-byte ,(+ size-high posn-high)))
2339               (specifier-type 'unsigned-byte)))
2340         *universal-type*)))
2341
2342 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2343   (let ((size (continuation-type size))
2344         (posn (continuation-type posn))
2345         (int (continuation-type int)))
2346     (if (and (numeric-type-p size)
2347              (csubtypep size (specifier-type 'integer))
2348              (numeric-type-p posn)
2349              (csubtypep posn (specifier-type 'integer))
2350              (numeric-type-p int)
2351              (csubtypep int (specifier-type 'integer)))
2352         (let ((size-high (numeric-type-high size))
2353               (posn-high (numeric-type-high posn))
2354               (high (numeric-type-high int))
2355               (low (numeric-type-low int)))
2356           (if (and size-high posn-high high low
2357                    (<= (+ size-high posn-high) sb!vm:n-word-bits))
2358               (specifier-type
2359                (list (if (minusp low) 'signed-byte 'unsigned-byte)
2360                      (max (integer-length high)
2361                           (integer-length low)
2362                           (+ size-high posn-high))))
2363               *universal-type*))
2364         *universal-type*)))
2365
2366 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2367   (let ((size (continuation-type size))
2368         (posn (continuation-type posn))
2369         (int (continuation-type int)))
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              (numeric-type-p int)
2375              (csubtypep int (specifier-type 'integer)))
2376         (let ((size-high (numeric-type-high size))
2377               (posn-high (numeric-type-high posn))
2378               (high (numeric-type-high int))
2379               (low (numeric-type-low int)))
2380           (if (and size-high posn-high high low
2381                    (<= (+ size-high posn-high) sb!vm:n-word-bits))
2382               (specifier-type
2383                (list (if (minusp low) 'signed-byte 'unsigned-byte)
2384                      (max (integer-length high)
2385                           (integer-length low)
2386                           (+ size-high posn-high))))
2387               *universal-type*))
2388         *universal-type*)))
2389
2390 (deftransform %ldb ((size posn int)
2391                     (fixnum fixnum integer)
2392                     (unsigned-byte #.sb!vm:n-word-bits))
2393   "convert to inline logical operations"
2394   `(logand (ash int (- posn))
2395            (ash ,(1- (ash 1 sb!vm:n-word-bits))
2396                 (- size ,sb!vm:n-word-bits))))
2397
2398 (deftransform %mask-field ((size posn int)
2399                            (fixnum fixnum integer)
2400                            (unsigned-byte #.sb!vm:n-word-bits))
2401   "convert to inline logical operations"
2402   `(logand int
2403            (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2404                      (- size ,sb!vm:n-word-bits))
2405                 posn)))
2406
2407 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2408 ;;;   (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2409 ;;; as the result type, as that would allow result types that cover
2410 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2411 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2412
2413 (deftransform %dpb ((new size posn int)
2414                     *
2415                     (unsigned-byte #.sb!vm:n-word-bits))
2416   "convert to inline logical operations"
2417   `(let ((mask (ldb (byte size 0) -1)))
2418      (logior (ash (logand new mask) posn)
2419              (logand int (lognot (ash mask posn))))))
2420
2421 (deftransform %dpb ((new size posn int)
2422                     *
2423                     (signed-byte #.sb!vm:n-word-bits))
2424   "convert to inline logical operations"
2425   `(let ((mask (ldb (byte size 0) -1)))
2426      (logior (ash (logand new mask) posn)
2427              (logand int (lognot (ash mask posn))))))
2428
2429 (deftransform %deposit-field ((new size posn int)
2430                               *
2431                               (unsigned-byte #.sb!vm:n-word-bits))
2432   "convert to inline logical operations"
2433   `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2434      (logior (logand new mask)
2435              (logand int (lognot mask)))))
2436
2437 (deftransform %deposit-field ((new size posn int)
2438                               *
2439                               (signed-byte #.sb!vm:n-word-bits))
2440   "convert to inline logical operations"
2441   `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2442      (logior (logand new mask)
2443              (logand int (lognot mask)))))
2444 \f
2445 ;;; miscellanous numeric transforms
2446
2447 ;;; If a constant appears as the first arg, swap the args.
2448 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
2449   (if (and (constant-continuation-p x)
2450            (not (constant-continuation-p y)))
2451       `(,(continuation-fun-name (basic-combination-fun node))
2452         y
2453         ,(continuation-value x))
2454       (give-up-ir1-transform)))
2455
2456 (dolist (x '(= char= + * logior logand logxor))
2457   (%deftransform x '(function * *) #'commutative-arg-swap
2458                  "place constant arg last"))
2459
2460 ;;; Handle the case of a constant BOOLE-CODE.
2461 (deftransform boole ((op x y) * *)
2462   "convert to inline logical operations"
2463   (unless (constant-continuation-p op)
2464     (give-up-ir1-transform "BOOLE code is not a constant."))
2465   (let ((control (continuation-value op)))
2466     (case control
2467       (#.boole-clr 0)
2468       (#.boole-set -1)
2469       (#.boole-1 'x)
2470       (#.boole-2 'y)
2471       (#.boole-c1 '(lognot x))
2472       (#.boole-c2 '(lognot y))
2473       (#.boole-and '(logand x y))
2474       (#.boole-ior '(logior x y))
2475       (#.boole-xor '(logxor x y))
2476       (#.boole-eqv '(logeqv x y))
2477       (#.boole-nand '(lognand x y))
2478       (#.boole-nor '(lognor x y))
2479       (#.boole-andc1 '(logandc1 x y))
2480       (#.boole-andc2 '(logandc2 x y))
2481       (#.boole-orc1 '(logorc1 x y))
2482       (#.boole-orc2 '(logorc2 x y))
2483       (t
2484        (abort-ir1-transform "~S is an illegal control arg to BOOLE."
2485                             control)))))
2486 \f
2487 ;;;; converting special case multiply/divide to shifts
2488
2489 ;;; If arg is a constant power of two, turn * into a shift.
2490 (deftransform * ((x y) (integer integer) *)
2491   "convert x*2^k to shift"
2492   (unless (constant-continuation-p y)
2493     (give-up-ir1-transform))
2494   (let* ((y (continuation-value y))
2495          (y-abs (abs y))
2496          (len (1- (integer-length y-abs))))
2497     (unless (= y-abs (ash 1 len))
2498       (give-up-ir1-transform))
2499     (if (minusp y)
2500         `(- (ash x ,len))
2501         `(ash x ,len))))
2502
2503 ;;; If both arguments and the result are (UNSIGNED-BYTE 32), try to
2504 ;;; come up with a ``better'' multiplication using multiplier
2505 ;;; recoding. There are two different ways the multiplier can be
2506 ;;; recoded. The more obvious is to shift X by the correct amount for
2507 ;;; each bit set in Y and to sum the results. But if there is a string
2508 ;;; of bits that are all set, you can add X shifted by one more then
2509 ;;; the bit position of the first set bit and subtract X shifted by
2510 ;;; the bit position of the last set bit. We can't use this second
2511 ;;; method when the high order bit is bit 31 because shifting by 32
2512 ;;; doesn't work too well.
2513 (deftransform * ((x y)
2514                  ((unsigned-byte 32) (unsigned-byte 32))
2515                  (unsigned-byte 32))
2516   "recode as shift and add"
2517   (unless (constant-continuation-p y)
2518     (give-up-ir1-transform))
2519   (let ((y (continuation-value y))
2520         (result nil)
2521         (first-one nil))
2522     (labels ((tub32 (x) `(truly-the (unsigned-byte 32) ,x))
2523              (add (next-factor)
2524                (setf result
2525                      (tub32
2526                       (if result
2527                           `(+ ,result ,(tub32 next-factor))
2528                           next-factor)))))
2529       (declare (inline add))
2530       (dotimes (bitpos 32)
2531         (if first-one
2532             (when (not (logbitp bitpos y))
2533               (add (if (= (1+ first-one) bitpos)
2534                        ;; There is only a single bit in the string.
2535                        `(ash x ,first-one)
2536                        ;; There are at least two.
2537                        `(- ,(tub32 `(ash x ,bitpos))
2538                            ,(tub32 `(ash x ,first-one)))))
2539               (setf first-one nil))
2540             (when (logbitp bitpos y)
2541               (setf first-one bitpos))))
2542       (when first-one
2543         (cond ((= first-one 31))
2544               ((= first-one 30)
2545                (add '(ash x 30)))
2546               (t
2547                (add `(- ,(tub32 '(ash x 31)) ,(tub32 `(ash x ,first-one))))))
2548         (add '(ash x 31))))
2549     (or result 0)))
2550
2551 ;;; If arg is a constant power of two, turn FLOOR into a shift and
2552 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
2553 ;;; remainder.
2554 (flet ((frob (y ceil-p)
2555          (unless (constant-continuation-p y)
2556            (give-up-ir1-transform))
2557          (let* ((y (continuation-value y))
2558                 (y-abs (abs y))
2559                 (len (1- (integer-length y-abs))))
2560            (unless (= y-abs (ash 1 len))
2561              (give-up-ir1-transform))
2562            (let ((shift (- len))
2563                  (mask (1- y-abs))
2564                  (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
2565              `(let ((x (+ x ,delta)))
2566                 ,(if (minusp y)
2567                      `(values (ash (- x) ,shift)
2568                               (- (- (logand (- x) ,mask)) ,delta))
2569                      `(values (ash x ,shift)
2570                               (- (logand x ,mask) ,delta))))))))
2571   (deftransform floor ((x y) (integer integer) *)
2572     "convert division by 2^k to shift"
2573     (frob y nil))
2574   (deftransform ceiling ((x y) (integer integer) *)
2575     "convert division by 2^k to shift"
2576     (frob y t)))
2577
2578 ;;; Do the same for MOD.
2579 (deftransform mod ((x y) (integer integer) *)
2580   "convert remainder mod 2^k to LOGAND"
2581   (unless (constant-continuation-p y)
2582     (give-up-ir1-transform))
2583   (let* ((y (continuation-value y))
2584          (y-abs (abs y))
2585          (len (1- (integer-length y-abs))))
2586     (unless (= y-abs (ash 1 len))
2587       (give-up-ir1-transform))
2588     (let ((mask (1- y-abs)))
2589       (if (minusp y)
2590           `(- (logand (- x) ,mask))
2591           `(logand x ,mask)))))
2592
2593 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
2594 (deftransform truncate ((x y) (integer integer))
2595   "convert division by 2^k to shift"
2596   (unless (constant-continuation-p y)
2597     (give-up-ir1-transform))
2598   (let* ((y (continuation-value y))
2599          (y-abs (abs y))
2600          (len (1- (integer-length y-abs))))
2601     (unless (= y-abs (ash 1 len))
2602       (give-up-ir1-transform))
2603     (let* ((shift (- len))
2604            (mask (1- y-abs)))
2605       `(if (minusp x)
2606            (values ,(if (minusp y)
2607                         `(ash (- x) ,shift)
2608                         `(- (ash (- x) ,shift)))
2609                    (- (logand (- x) ,mask)))
2610            (values ,(if (minusp y)
2611                         `(- (ash (- x) ,shift))
2612                         `(ash x ,shift))
2613                    (logand x ,mask))))))
2614
2615 ;;; And the same for REM.
2616 (deftransform rem ((x y) (integer integer) *)
2617   "convert remainder mod 2^k to LOGAND"
2618   (unless (constant-continuation-p y)
2619     (give-up-ir1-transform))
2620   (let* ((y (continuation-value y))
2621          (y-abs (abs y))
2622          (len (1- (integer-length y-abs))))
2623     (unless (= y-abs (ash 1 len))
2624       (give-up-ir1-transform))
2625     (let ((mask (1- y-abs)))
2626       `(if (minusp x)
2627            (- (logand (- x) ,mask))
2628            (logand x ,mask)))))
2629 \f
2630 ;;;; arithmetic and logical identity operation elimination
2631
2632 ;;; Flush calls to various arith functions that convert to the
2633 ;;; identity function or a constant.
2634 (macrolet ((def (name identity result)
2635              `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
2636                 "fold identity operations"
2637                 ',result)))
2638   (def ash 0 x)
2639   (def logand -1 x)
2640   (def logand 0 0)
2641   (def logior 0 x)
2642   (def logior -1 -1)
2643   (def logxor -1 (lognot x))
2644   (def logxor 0 x))
2645
2646 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
2647 ;;; (* 0 -4.0) is -0.0.
2648 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
2649   "convert (- 0 x) to negate"
2650   '(%negate y))
2651 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
2652   "convert (* x 0) to 0"
2653   0)
2654
2655 ;;; Return T if in an arithmetic op including continuations X and Y,
2656 ;;; the result type is not affected by the type of X. That is, Y is at
2657 ;;; least as contagious as X.
2658 #+nil
2659 (defun not-more-contagious (x y)
2660   (declare (type continuation x y))
2661   (let ((x (continuation-type x))
2662         (y (continuation-type y)))
2663     (values (type= (numeric-contagion x y)
2664                    (numeric-contagion y y)))))
2665 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
2666 ;;; XXX needs more work as valid transforms are missed; some cases are
2667 ;;; specific to particular transform functions so the use of this
2668 ;;; function may need a re-think.
2669 (defun not-more-contagious (x y)
2670   (declare (type continuation x y))
2671   (flet ((simple-numeric-type (num)
2672            (and (numeric-type-p num)
2673                 ;; Return non-NIL if NUM is integer, rational, or a float
2674                 ;; of some type (but not FLOAT)
2675                 (case (numeric-type-class num)
2676                   ((integer rational)
2677                    t)
2678                   (float
2679                    (numeric-type-format num))
2680                   (t
2681                    nil)))))
2682     (let ((x (continuation-type x))
2683           (y (continuation-type y)))
2684       (if (and (simple-numeric-type x)
2685                (simple-numeric-type y))
2686           (values (type= (numeric-contagion x y)
2687                          (numeric-contagion y y)))))))
2688
2689 ;;; Fold (+ x 0).
2690 ;;;
2691 ;;; If y is not constant, not zerop, or is contagious, or a positive
2692 ;;; float +0.0 then give up.
2693 (deftransform + ((x y) (t (constant-arg t)) *)
2694   "fold zero arg"
2695   (let ((val (continuation-value y)))
2696     (unless (and (zerop val)
2697                  (not (and (floatp val) (plusp (float-sign val))))
2698                  (not-more-contagious y x))
2699       (give-up-ir1-transform)))
2700   'x)
2701
2702 ;;; Fold (- x 0).
2703 ;;;
2704 ;;; If y is not constant, not zerop, or is contagious, or a negative
2705 ;;; float -0.0 then give up.
2706 (deftransform - ((x y) (t (constant-arg t)) *)
2707   "fold zero arg"
2708   (let ((val (continuation-value y)))
2709     (unless (and (zerop val)
2710                  (not (and (floatp val) (minusp (float-sign val))))
2711                  (not-more-contagious y x))
2712       (give-up-ir1-transform)))
2713   'x)
2714
2715 ;;; Fold (OP x +/-1)
2716 (macrolet ((def (name result minus-result)
2717              `(deftransform ,name ((x y) (t (constant-arg real)) *)
2718                 "fold identity operations"
2719                 (let ((val (continuation-value y)))
2720                   (unless (and (= (abs val) 1)
2721                                (not-more-contagious y x))
2722                     (give-up-ir1-transform))
2723                   (if (minusp val) ',minus-result ',result)))))
2724   (def * x (%negate x))
2725   (def / x (%negate x))
2726   (def expt x (/ 1 x)))
2727
2728 ;;; Fold (expt x n) into multiplications for small integral values of
2729 ;;; N; convert (expt x 1/2) to sqrt.
2730 (deftransform expt ((x y) (t (constant-arg real)) *)
2731   "recode as multiplication or sqrt"
2732   (let ((val (continuation-value y)))
2733     ;; If Y would cause the result to be promoted to the same type as
2734     ;; Y, we give up. If not, then the result will be the same type
2735     ;; as X, so we can replace the exponentiation with simple
2736     ;; multiplication and division for small integral powers.
2737     (unless (not-more-contagious y x)
2738       (give-up-ir1-transform))
2739     (cond ((zerop val) '(float 1 x))
2740           ((= val 2) '(* x x))
2741           ((= val -2) '(/ (* x x)))
2742           ((= val 3) '(* x x x))
2743           ((= val -3) '(/ (* x x x)))
2744           ((= val 1/2) '(sqrt x))
2745           ((= val -1/2) '(/ (sqrt x)))
2746           (t (give-up-ir1-transform)))))
2747
2748 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
2749 ;;; transformations?
2750 ;;; Perhaps we should have to prove that the denominator is nonzero before
2751 ;;; doing them?  -- WHN 19990917
2752 (macrolet ((def (name)
2753              `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2754                                    *)
2755                 "fold zero arg"
2756                 0)))
2757   (def ash)
2758   (def /))
2759
2760 (macrolet ((def (name)
2761              `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2762                                    *)
2763                 "fold zero arg"
2764                 '(values 0 0))))
2765   (def truncate)
2766   (def round)
2767   (def floor)
2768   (def ceiling))
2769 \f
2770 ;;;; character operations
2771
2772 (deftransform char-equal ((a b) (base-char base-char))
2773   "open code"
2774   '(let* ((ac (char-code a))
2775           (bc (char-code b))
2776           (sum (logxor ac bc)))
2777      (or (zerop sum)
2778          (when (eql sum #x20)
2779            (let ((sum (+ ac bc)))
2780              (and (> sum 161) (< sum 213)))))))
2781
2782 (deftransform char-upcase ((x) (base-char))
2783   "open code"
2784   '(let ((n-code (char-code x)))
2785      (if (and (> n-code #o140)  ; Octal 141 is #\a.
2786               (< n-code #o173)) ; Octal 172 is #\z.
2787          (code-char (logxor #x20 n-code))
2788          x)))
2789
2790 (deftransform char-downcase ((x) (base-char))
2791   "open code"
2792   '(let ((n-code (char-code x)))
2793      (if (and (> n-code 64)     ; 65 is #\A.
2794               (< n-code 91))    ; 90 is #\Z.
2795          (code-char (logxor #x20 n-code))
2796          x)))
2797 \f
2798 ;;;; equality predicate transforms
2799
2800 ;;; Return true if X and Y are continuations whose only use is a
2801 ;;; reference to the same leaf, and the value of the leaf cannot
2802 ;;; change.
2803 (defun same-leaf-ref-p (x y)
2804   (declare (type continuation x y))
2805   (let ((x-use (continuation-use x))
2806         (y-use (continuation-use y)))
2807     (and (ref-p x-use)
2808          (ref-p y-use)
2809          (eq (ref-leaf x-use) (ref-leaf y-use))
2810          (constant-reference-p x-use))))
2811
2812 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
2813 ;;; if there is no intersection between the types of the arguments,
2814 ;;; then the result is definitely false.
2815 (deftransform simple-equality-transform ((x y) * *
2816                                          :defun-only t)
2817   (cond ((same-leaf-ref-p x y)
2818          t)
2819         ((not (types-equal-or-intersect (continuation-type x)
2820                                         (continuation-type y)))
2821          nil)
2822         (t
2823          (give-up-ir1-transform))))
2824
2825 (macrolet ((def (x)
2826              `(%deftransform ',x '(function * *) #'simple-equality-transform)))
2827   (def eq)
2828   (def char=)
2829   (def equal))
2830
2831 ;;; This is similar to SIMPLE-EQUALITY-PREDICATE, except that we also
2832 ;;; try to convert to a type-specific predicate or EQ:
2833 ;;; -- If both args are characters, convert to CHAR=. This is better than
2834 ;;;    just converting to EQ, since CHAR= may have special compilation
2835 ;;;    strategies for non-standard representations, etc.
2836 ;;; -- If either arg is definitely not a number, then we can compare
2837 ;;;    with EQ.
2838 ;;; -- Otherwise, we try to put the arg we know more about second. If X
2839 ;;;    is constant then we put it second. If X is a subtype of Y, we put
2840 ;;;    it second. These rules make it easier for the back end to match
2841 ;;;    these interesting cases.
2842 ;;; -- If Y is a fixnum, then we quietly pass because the back end can
2843 ;;;    handle that case, otherwise give an efficiency note.
2844 (deftransform eql ((x y) * *)
2845   "convert to simpler equality predicate"
2846   (let ((x-type (continuation-type x))
2847         (y-type (continuation-type y))
2848         (char-type (specifier-type 'character))
2849         (number-type (specifier-type 'number)))
2850     (cond ((same-leaf-ref-p x y)
2851            t)
2852           ((not (types-equal-or-intersect x-type y-type))
2853            nil)
2854           ((and (csubtypep x-type char-type)
2855                 (csubtypep y-type char-type))
2856            '(char= x y))
2857           ((or (not (types-equal-or-intersect x-type number-type))
2858                (not (types-equal-or-intersect y-type number-type)))
2859            '(eq x y))
2860           ((and (not (constant-continuation-p y))
2861                 (or (constant-continuation-p x)
2862                     (and (csubtypep x-type y-type)
2863                          (not (csubtypep y-type x-type)))))
2864            '(eql y x))
2865           (t
2866            (give-up-ir1-transform)))))
2867
2868 ;;; Convert to EQL if both args are rational and complexp is specified
2869 ;;; and the same for both.
2870 (deftransform = ((x y) * *)
2871   "open code"
2872   (let ((x-type (continuation-type x))
2873         (y-type (continuation-type y)))
2874     (if (and (csubtypep x-type (specifier-type 'number))
2875              (csubtypep y-type (specifier-type 'number)))
2876         (cond ((or (and (csubtypep x-type (specifier-type 'float))
2877                         (csubtypep y-type (specifier-type 'float)))
2878                    (and (csubtypep x-type (specifier-type '(complex float)))
2879                         (csubtypep y-type (specifier-type '(complex float)))))
2880                ;; They are both floats. Leave as = so that -0.0 is
2881                ;; handled correctly.
2882                (give-up-ir1-transform))
2883               ((or (and (csubtypep x-type (specifier-type 'rational))
2884                         (csubtypep y-type (specifier-type 'rational)))
2885                    (and (csubtypep x-type
2886                                    (specifier-type '(complex rational)))
2887                         (csubtypep y-type
2888                                    (specifier-type '(complex rational)))))
2889                ;; They are both rationals and complexp is the same.
2890                ;; Convert to EQL.
2891                '(eql x y))
2892               (t
2893                (give-up-ir1-transform
2894                 "The operands might not be the same type.")))
2895         (give-up-ir1-transform
2896          "The operands might not be the same type."))))
2897
2898 ;;; If CONT's type is a numeric type, then return the type, otherwise
2899 ;;; GIVE-UP-IR1-TRANSFORM.
2900 (defun numeric-type-or-lose (cont)
2901   (declare (type continuation cont))
2902   (let ((res (continuation-type cont)))
2903     (unless (numeric-type-p res) (give-up-ir1-transform))
2904     res))
2905
2906 ;;; See whether we can statically determine (< X Y) using type
2907 ;;; information. If X's high bound is < Y's low, then X < Y.
2908 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
2909 ;;; NIL). If not, at least make sure any constant arg is second.
2910 ;;;
2911 ;;; FIXME: Why should constant argument be second? It would be nice to
2912 ;;; find out and explain.
2913 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2914 (defun ir1-transform-< (x y first second inverse)
2915   (if (same-leaf-ref-p x y)
2916       nil
2917       (let* ((x-type (numeric-type-or-lose x))
2918              (x-lo (numeric-type-low x-type))
2919              (x-hi (numeric-type-high x-type))
2920              (y-type (numeric-type-or-lose y))
2921              (y-lo (numeric-type-low y-type))
2922              (y-hi (numeric-type-high y-type)))
2923         (cond ((and x-hi y-lo (< x-hi y-lo))
2924                t)
2925               ((and y-hi x-lo (>= x-lo y-hi))
2926                nil)
2927               ((and (constant-continuation-p first)
2928                     (not (constant-continuation-p second)))
2929                `(,inverse y x))
2930               (t
2931                (give-up-ir1-transform))))))
2932 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2933 (defun ir1-transform-< (x y first second inverse)
2934   (if (same-leaf-ref-p x y)
2935       nil
2936       (let ((xi (numeric-type->interval (numeric-type-or-lose x)))
2937             (yi (numeric-type->interval (numeric-type-or-lose y))))
2938         (cond ((interval-< xi yi)
2939                t)
2940               ((interval->= xi yi)
2941                nil)
2942               ((and (constant-continuation-p first)
2943                     (not (constant-continuation-p second)))
2944                `(,inverse y x))
2945               (t
2946                (give-up-ir1-transform))))))
2947
2948 (deftransform < ((x y) (integer integer) *)
2949   (ir1-transform-< x y x y '>))
2950
2951 (deftransform > ((x y) (integer integer) *)
2952   (ir1-transform-< y x x y '<))
2953
2954 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2955 (deftransform < ((x y) (float float) *)
2956   (ir1-transform-< x y x y '>))
2957
2958 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2959 (deftransform > ((x y) (float float) *)
2960   (ir1-transform-< y x x y '<))
2961 \f
2962 ;;;; converting N-arg comparisons
2963 ;;;;
2964 ;;;; We convert calls to N-arg comparison functions such as < into
2965 ;;;; two-arg calls. This transformation is enabled for all such
2966 ;;;; comparisons in this file. If any of these predicates are not
2967 ;;;; open-coded, then the transformation should be removed at some
2968 ;;;; point to avoid pessimization.
2969
2970 ;;; This function is used for source transformation of N-arg
2971 ;;; comparison functions other than inequality. We deal both with
2972 ;;; converting to two-arg calls and inverting the sense of the test,
2973 ;;; if necessary. If the call has two args, then we pass or return a
2974 ;;; negated test as appropriate. If it is a degenerate one-arg call,
2975 ;;; then we transform to code that returns true. Otherwise, we bind
2976 ;;; all the arguments and expand into a bunch of IFs.
2977 (declaim (ftype (function (symbol list boolean) *) multi-compare))
2978 (defun multi-compare (predicate args not-p)
2979   (let ((nargs (length args)))
2980     (cond ((< nargs 1) (values nil t))
2981           ((= nargs 1) `(progn ,@args t))
2982           ((= nargs 2)
2983            (if not-p
2984                `(if (,predicate ,(first args) ,(second args)) nil t)
2985                (values nil t)))
2986           (t
2987            (do* ((i (1- nargs) (1- i))
2988                  (last nil current)
2989                  (current (gensym) (gensym))
2990                  (vars (list current) (cons current vars))
2991                  (result t (if not-p
2992                                `(if (,predicate ,current ,last)
2993                                     nil ,result)
2994                                `(if (,predicate ,current ,last)
2995                                     ,result nil))))
2996                ((zerop i)
2997                 `((lambda ,vars ,result) . ,args)))))))
2998
2999 (define-source-transform = (&rest args) (multi-compare '= args nil))
3000 (define-source-transform < (&rest args) (multi-compare '< args nil))
3001 (define-source-transform > (&rest args) (multi-compare '> args nil))
3002 (define-source-transform <= (&rest args) (multi-compare '> args t))
3003 (define-source-transform >= (&rest args) (multi-compare '< args t))
3004
3005 (define-source-transform char= (&rest args) (multi-compare 'char= args nil))
3006 (define-source-transform char< (&rest args) (multi-compare 'char< args nil))
3007 (define-source-transform char> (&rest args) (multi-compare 'char> args nil))
3008 (define-source-transform char<= (&rest args) (multi-compare 'char> args t))
3009 (define-source-transform char>= (&rest args) (multi-compare 'char< args t))
3010
3011 (define-source-transform char-equal (&rest args)
3012   (multi-compare 'char-equal args nil))
3013 (define-source-transform char-lessp (&rest args)
3014   (multi-compare 'char-lessp args nil))
3015 (define-source-transform char-greaterp (&rest args)
3016   (multi-compare 'char-greaterp args nil))
3017 (define-source-transform char-not-greaterp (&rest args)
3018   (multi-compare 'char-greaterp args t))
3019 (define-source-transform char-not-lessp (&rest args)
3020   (multi-compare 'char-lessp args t))
3021
3022 ;;; This function does source transformation of N-arg inequality
3023 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3024 ;;; arg cases. If there are more than two args, then we expand into
3025 ;;; the appropriate n^2 comparisons only when speed is important.
3026 (declaim (ftype (function (symbol list) *) multi-not-equal))
3027 (defun multi-not-equal (predicate args)
3028   (let ((nargs (length args)))
3029     (cond ((< nargs 1) (values nil t))
3030           ((= nargs 1) `(progn ,@args t))
3031           ((= nargs 2)
3032            `(if (,predicate ,(first args) ,(second args)) nil t))
3033           ((not (policy *lexenv*
3034                         (and (>= speed space)
3035                              (>= speed compilation-speed))))
3036            (values nil t))
3037           (t
3038            (let ((vars (make-gensym-list nargs)))
3039              (do ((var vars next)
3040                   (next (cdr vars) (cdr next))
3041                   (result t))
3042                  ((null next)
3043                   `((lambda ,vars ,result) . ,args))
3044                (let ((v1 (first var)))
3045                  (dolist (v2 next)
3046                    (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3047
3048 (define-source-transform /= (&rest args) (multi-not-equal '= args))
3049 (define-source-transform char/= (&rest args) (multi-not-equal 'char= args))
3050 (define-source-transform char-not-equal (&rest args)
3051   (multi-not-equal 'char-equal args))
3052
3053 ;;; FIXME: can go away once bug 194 is fixed and we can use (THE REAL X)
3054 ;;; as God intended
3055 (defun error-not-a-real (x)
3056   (error 'simple-type-error
3057          :datum x
3058          :expected-type 'real
3059          :format-control "not a REAL: ~S"
3060          :format-arguments (list x)))
3061
3062 ;;; Expand MAX and MIN into the obvious comparisons.
3063 (define-source-transform max (arg0 &rest rest)
3064   (once-only ((arg0 arg0))
3065     (if (null rest)
3066         `(values (the real ,arg0))
3067         `(let ((maxrest (max ,@rest)))
3068           (if (> ,arg0 maxrest) ,arg0 maxrest)))))
3069 (define-source-transform min (arg0 &rest rest)
3070   (once-only ((arg0 arg0))
3071     (if (null rest)
3072         `(values (the real ,arg0))
3073         `(let ((minrest (min ,@rest)))
3074           (if (< ,arg0 minrest) ,arg0 minrest)))))
3075 \f
3076 ;;;; converting N-arg arithmetic functions
3077 ;;;;
3078 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3079 ;;;; versions, and degenerate cases are flushed.
3080
3081 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3082 (declaim (ftype (function (symbol t list) list) associate-args))
3083 (defun associate-args (function first-arg more-args)
3084   (let ((next (rest more-args))
3085         (arg (first more-args)))
3086     (if (null next)
3087         `(,function ,first-arg ,arg)
3088         (associate-args function `(,function ,first-arg ,arg) next))))
3089
3090 ;;; Do source transformations for transitive functions such as +.
3091 ;;; One-arg cases are replaced with the arg and zero arg cases with
3092 ;;; the identity.  ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3093 ;;; ensure (with THE) that the argument in one-argument calls is.
3094 (defun source-transform-transitive (fun args identity
3095                                     &optional one-arg-result-type)
3096   (declare (symbol fun leaf-fun) (list args))
3097   (case (length args)
3098     (0 identity)
3099     (1 (if one-arg-result-type
3100            `(values (the ,one-arg-result-type ,(first args)))
3101            `(values ,(first args))))
3102     (2 (values nil t))
3103     (t
3104      (associate-args fun (first args) (rest args)))))
3105
3106 (define-source-transform + (&rest args)
3107   (source-transform-transitive '+ args 0 'number))
3108 (define-source-transform * (&rest args)
3109   (source-transform-transitive '* args 1 'number))
3110 (define-source-transform logior (&rest args)
3111   (source-transform-transitive 'logior args 0 'integer))
3112 (define-source-transform logxor (&rest args)
3113   (source-transform-transitive 'logxor args 0 'integer))
3114 (define-source-transform logand (&rest args)
3115   (source-transform-transitive 'logand args -1 'integer))
3116
3117 (define-source-transform logeqv (&rest args)
3118   (if (evenp (length args))
3119       `(lognot (logxor ,@args))
3120       `(logxor ,@args)))
3121
3122 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3123 ;;; because when they are given one argument, they return its absolute
3124 ;;; value.
3125
3126 (define-source-transform gcd (&rest args)
3127   (case (length args)
3128     (0 0)
3129     (1 `(abs (the integer ,(first args))))
3130     (2 (values nil t))
3131     (t (associate-args 'gcd (first args) (rest args)))))
3132
3133 (define-source-transform lcm (&rest args)
3134   (case (length args)
3135     (0 1)
3136     (1 `(abs (the integer ,(first args))))
3137     (2 (values nil t))
3138     (t (associate-args 'lcm (first args) (rest args)))))
3139
3140 ;;; Do source transformations for intransitive n-arg functions such as
3141 ;;; /. With one arg, we form the inverse. With two args we pass.
3142 ;;; Otherwise we associate into two-arg calls.
3143 (declaim (ftype (function (symbol list t)
3144                           (values list &optional (member nil t)))
3145                 source-transform-intransitive))
3146 (defun source-transform-intransitive (function args inverse)
3147   (case (length args)
3148     ((0 2) (values nil t))
3149     (1 `(,@inverse ,(first args)))
3150     (t (associate-args function (first args) (rest args)))))
3151
3152 (define-source-transform - (&rest args)
3153   (source-transform-intransitive '- args '(%negate)))
3154 (define-source-transform / (&rest args)
3155   (source-transform-intransitive '/ args '(/ 1)))
3156 \f
3157 ;;;; transforming APPLY
3158
3159 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3160 ;;; only needs to understand one kind of variable-argument call. It is
3161 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3162 (define-source-transform apply (fun arg &rest more-args)
3163   (let ((args (cons arg more-args)))
3164     `(multiple-value-call ,fun
3165        ,@(mapcar (lambda (x)
3166                    `(values ,x))
3167                  (butlast args))
3168        (values-list ,(car (last args))))))
3169 \f
3170 ;;;; transforming FORMAT
3171 ;;;;
3172 ;;;; If the control string is a compile-time constant, then replace it
3173 ;;;; with a use of the FORMATTER macro so that the control string is
3174 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3175 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3176 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3177
3178 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3179                       :policy (> speed space))
3180   (unless (constant-continuation-p control)
3181     (give-up-ir1-transform "The control string is not a constant."))
3182   (let ((arg-names (make-gensym-list (length args))))
3183     `(lambda (dest control ,@arg-names)
3184        (declare (ignore control))
3185        (format dest (formatter ,(continuation-value control)) ,@arg-names))))
3186
3187 (deftransform format ((stream control &rest args) (stream function &rest t) *
3188                       :policy (> speed space))
3189   (let ((arg-names (make-gensym-list (length args))))
3190     `(lambda (stream control ,@arg-names)
3191        (funcall control stream ,@arg-names)
3192        nil)))
3193
3194 (deftransform format ((tee control &rest args) ((member t) function &rest t) *
3195                       :policy (> speed space))
3196   (let ((arg-names (make-gensym-list (length args))))
3197     `(lambda (tee control ,@arg-names)
3198        (declare (ignore tee))
3199        (funcall control *standard-output* ,@arg-names)
3200        nil)))
3201
3202 (defoptimizer (coerce derive-type) ((value type))
3203   (cond
3204     ((constant-continuation-p type)
3205      ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3206      ;; but dealing with the niggle that complex canonicalization gets
3207      ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3208      ;; type COMPLEX.
3209      (let* ((specifier (continuation-value type))
3210             (result-typeoid (careful-specifier-type specifier)))
3211        (cond
3212          ((null result-typeoid) nil)
3213          ((csubtypep result-typeoid (specifier-type 'number))
3214           ;; the difficult case: we have to cope with ANSI 12.1.5.3
3215           ;; Rule of Canonical Representation for Complex Rationals,
3216           ;; which is a truly nasty delivery to field.
3217           (cond
3218             ((csubtypep result-typeoid (specifier-type 'real))
3219              ;; cleverness required here: it would be nice to deduce
3220              ;; that something of type (INTEGER 2 3) coerced to type
3221              ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3222              ;; FLOAT gets its own clause because it's implemented as
3223              ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3224              ;; logic below.
3225              result-typeoid)
3226             ((and (numeric-type-p result-typeoid)
3227                   (eq (numeric-type-complexp result-typeoid) :real))
3228              ;; FIXME: is this clause (a) necessary or (b) useful?
3229              result-typeoid)
3230             ((or (csubtypep result-typeoid
3231                             (specifier-type '(complex single-float)))
3232                  (csubtypep result-typeoid
3233                             (specifier-type '(complex double-float)))
3234                  #!+long-float
3235                  (csubtypep result-typeoid
3236                             (specifier-type '(complex long-float))))
3237              ;; float complex types are never canonicalized.
3238              result-typeoid)
3239             (t
3240              ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
3241              ;; probably just a COMPLEX or equivalent.  So, in that
3242              ;; case, we will return a complex or an object of the
3243              ;; provided type if it's rational:
3244              (type-union result-typeoid
3245                          (type-intersection (continuation-type value)
3246                                             (specifier-type 'rational))))))
3247          (t result-typeoid))))
3248     (t
3249      ;; OK, the result-type argument isn't constant.  However, there
3250      ;; are common uses where we can still do better than just
3251      ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
3252      ;; where Y is of a known type.  See messages on cmucl-imp
3253      ;; 2001-02-14 and sbcl-devel 2002-12-12.  We only worry here
3254      ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
3255      ;; the basis that it's unlikely that other uses are both
3256      ;; time-critical and get to this branch of the COND (non-constant
3257      ;; second argument to COERCE).  -- CSR, 2002-12-16
3258      (let ((value-type (continuation-type value))
3259            (type-type (continuation-type type)))
3260        (labels
3261            ((good-cons-type-p (cons-type)
3262               ;; Make sure the cons-type we're looking at is something
3263               ;; we're prepared to handle which is basically something
3264               ;; that array-element-type can return.
3265               (or (and (member-type-p cons-type)
3266                        (null (rest (member-type-members cons-type)))
3267                        (null (first (member-type-members cons-type))))
3268                   (let ((car-type (cons-type-car-type cons-type)))
3269                     (and (member-type-p car-type)
3270                          (null (rest (member-type-members car-type)))
3271                          (or (symbolp (first (member-type-members car-type)))
3272                              (numberp (first (member-type-members car-type)))
3273                              (and (listp (first (member-type-members
3274                                                  car-type)))
3275                                   (numberp (first (first (member-type-members
3276                                                           car-type))))))
3277                          (good-cons-type-p (cons-type-cdr-type cons-type))))))
3278             (unconsify-type (good-cons-type)
3279               ;; Convert the "printed" respresentation of a cons
3280               ;; specifier into a type specifier.  That is, the
3281               ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
3282               ;; NULL)) is converted to (SIGNED-BYTE 16).
3283               (cond ((or (null good-cons-type)
3284                          (eq good-cons-type 'null))
3285                      nil)
3286                     ((and (eq (first good-cons-type) 'cons)
3287                           (eq (first (second good-cons-type)) 'member))
3288                      `(,(second (second good-cons-type))
3289                        ,@(unconsify-type (caddr good-cons-type))))))
3290             (coerceable-p (c-type)
3291               ;; Can the value be coerced to the given type?  Coerce is
3292               ;; complicated, so we don't handle every possible case
3293               ;; here---just the most common and easiest cases:
3294               ;;
3295               ;; * Any REAL can be coerced to a FLOAT type.
3296               ;; * Any NUMBER can be coerced to a (COMPLEX
3297               ;;   SINGLE/DOUBLE-FLOAT).
3298               ;;
3299               ;; FIXME I: we should also be able to deal with characters
3300               ;; here.
3301               ;;
3302               ;; FIXME II: I'm not sure that anything is necessary
3303               ;; here, at least while COMPLEX is not a specialized
3304               ;; array element type in the system.  Reasoning: if
3305               ;; something cannot be coerced to the requested type, an
3306               ;; error will be raised (and so any downstream compiled
3307               ;; code on the assumption of the returned type is
3308               ;; unreachable).  If something can, then it will be of
3309               ;; the requested type, because (by assumption) COMPLEX
3310               ;; (and other difficult types like (COMPLEX INTEGER)
3311               ;; aren't specialized types.
3312               (let ((coerced-type c-type))
3313                 (or (and (subtypep coerced-type 'float)
3314                          (csubtypep value-type (specifier-type 'real)))
3315                     (and (subtypep coerced-type
3316                                    '(or (complex single-float)
3317                                         (complex double-float)))
3318                          (csubtypep value-type (specifier-type 'number))))))
3319             (process-types (type)
3320               ;; FIXME: This needs some work because we should be able
3321               ;; to derive the resulting type better than just the
3322               ;; type arg of coerce.  That is, if X is (INTEGER 10
3323               ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
3324               ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
3325               ;; double-float.
3326               (cond ((member-type-p type)
3327                      (let ((members (member-type-members type)))
3328                        (if (every #'coerceable-p members)
3329                            (specifier-type `(or ,@members))
3330                            *universal-type*)))
3331                     ((and (cons-type-p type)
3332                           (good-cons-type-p type))
3333                      (let ((c-type (unconsify-type (type-specifier type))))
3334                        (if (coerceable-p c-type)
3335                            (specifier-type c-type)
3336                            *universal-type*)))
3337                     (t
3338                      *universal-type*))))
3339          (cond ((union-type-p type-type)
3340                 (apply #'type-union (mapcar #'process-types
3341                                             (union-type-types type-type))))
3342                ((or (member-type-p type-type)
3343                     (cons-type-p type-type))
3344                 (process-types type-type))
3345                (t
3346                 *universal-type*)))))))
3347
3348 (defoptimizer (compile derive-type) ((nameoid function))
3349   (when (csubtypep (continuation-type nameoid)
3350                    (specifier-type 'null))
3351     (values-specifier-type '(values function boolean boolean))))
3352
3353 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
3354 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
3355 ;;; optimizer, above).
3356 (defoptimizer (array-element-type derive-type) ((array))
3357   (let ((array-type (continuation-type array)))
3358     (labels ((consify (list)
3359               (if (endp list)
3360                   '(eql nil)
3361                   `(cons (eql ,(car list)) ,(consify (rest list)))))
3362             (get-element-type (a)
3363               (let ((element-type
3364                      (type-specifier (array-type-specialized-element-type a))))
3365                 (cond ((eq element-type '*)
3366                        (specifier-type 'type-specifier))
3367                       ((symbolp element-type)
3368                        (make-member-type :members (list element-type)))
3369                       ((consp element-type)
3370                        (specifier-type (consify element-type)))
3371                       (t
3372                        (error "can't understand type ~S~%" element-type))))))
3373       (cond ((array-type-p array-type)
3374              (get-element-type array-type))
3375             ((union-type-p array-type)             
3376              (apply #'type-union
3377                     (mapcar #'get-element-type (union-type-types array-type))))
3378             (t
3379              *universal-type*)))))
3380
3381 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
3382   `(macrolet ((%index (x) `(truly-the index ,x))
3383               (%parent (i) `(ash ,i -1))
3384               (%left (i) `(%index (ash ,i 1)))
3385               (%right (i) `(%index (1+ (ash ,i 1))))
3386               (%heapify (i)
3387                `(do* ((i ,i)
3388                       (left (%left i) (%left i)))
3389                  ((> left current-heap-size))
3390                  (declare (type index i left))
3391                  (let* ((i-elt (%elt i))
3392                         (i-key (funcall keyfun i-elt))
3393                         (left-elt (%elt left))
3394                         (left-key (funcall keyfun left-elt)))
3395                    (multiple-value-bind (large large-elt large-key)
3396                        (if (funcall ,',predicate i-key left-key)
3397                            (values left left-elt left-key)
3398                            (values i i-elt i-key))
3399                      (let ((right (%right i)))
3400                        (multiple-value-bind (largest largest-elt)
3401                            (if (> right current-heap-size)
3402                                (values large large-elt)
3403                                (let* ((right-elt (%elt right))
3404                                       (right-key (funcall keyfun right-elt)))
3405                                  (if (funcall ,',predicate large-key right-key)
3406                                      (values right right-elt)
3407                                      (values large large-elt))))
3408                          (cond ((= largest i)
3409                                 (return))
3410                                (t
3411                                 (setf (%elt i) largest-elt
3412                                       (%elt largest) i-elt
3413                                       i largest)))))))))
3414               (%sort-vector (keyfun &optional (vtype 'vector))
3415                `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had trouble getting
3416                            ;; type inference to propagate all the way
3417                            ;; through this tangled mess of
3418                            ;; inlining. The TRULY-THE here works
3419                            ;; around that. -- WHN
3420                            (%elt (i)
3421                             `(aref (truly-the ,',vtype ,',',vector)
3422                               (%index (+ (%index ,i) start-1)))))
3423                  (let ((start-1 (1- ,',start)) ; Heaps prefer 1-based addressing.
3424                        (current-heap-size (- ,',end ,',start))
3425                        (keyfun ,keyfun))
3426                    (declare (type (integer -1 #.(1- most-positive-fixnum))
3427                                   start-1))
3428                    (declare (type index current-heap-size))
3429                    (declare (type function keyfun))
3430                    (loop for i of-type index
3431                          from (ash current-heap-size -1) downto 1 do
3432                          (%heapify i))
3433                    (loop 
3434                     (when (< current-heap-size 2)
3435                       (return))
3436                     (rotatef (%elt 1) (%elt current-heap-size))
3437                     (decf current-heap-size)
3438                     (%heapify 1))))))
3439     (if (typep ,vector 'simple-vector)
3440         ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
3441         ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
3442         (if (null ,key)
3443             ;; Special-casing the KEY=NIL case lets us avoid some
3444             ;; function calls.
3445             (%sort-vector #'identity simple-vector)
3446             (%sort-vector ,key simple-vector))
3447         ;; It's hard to anticipate many speed-critical applications for
3448         ;; sorting vector types other than (VECTOR T), so we just lump
3449         ;; them all together in one slow dynamically typed mess.
3450         (locally
3451           (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
3452           (%sort-vector (or ,key #'identity))))))
3453 \f
3454 ;;;; debuggers' little helpers
3455
3456 ;;; for debugging when transforms are behaving mysteriously,
3457 ;;; e.g. when debugging a problem with an ASH transform
3458 ;;;   (defun foo (&optional s)
3459 ;;;     (sb-c::/report-continuation s "S outside WHEN")
3460 ;;;     (when (and (integerp s) (> s 3))
3461 ;;;       (sb-c::/report-continuation s "S inside WHEN")
3462 ;;;       (let ((bound (ash 1 (1- s))))
3463 ;;;         (sb-c::/report-continuation bound "BOUND")
3464 ;;;         (let ((x (- bound))
3465 ;;;               (y (1- bound)))
3466 ;;;           (sb-c::/report-continuation x "X")
3467 ;;;           (sb-c::/report-continuation x "Y"))
3468 ;;;         `(integer ,(- bound) ,(1- bound)))))
3469 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
3470 ;;; and the function doesn't do anything at all.)
3471 #!+sb-show
3472 (progn
3473   (defknown /report-continuation (t t) null)
3474   (deftransform /report-continuation ((x message) (t t))
3475     (format t "~%/in /REPORT-CONTINUATION~%")
3476     (format t "/(CONTINUATION-TYPE X)=~S~%" (continuation-type x))
3477     (when (constant-continuation-p x)
3478       (format t "/(CONTINUATION-VALUE X)=~S~%" (continuation-value x)))
3479     (format t "/MESSAGE=~S~%" (continuation-value message))
3480     (give-up-ir1-transform "not a real transform"))
3481   (defun /report-continuation (&rest rest)
3482     (declare (ignore rest))))