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