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