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