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