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