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