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