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