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