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