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