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