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