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