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