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