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