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