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