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.
5 ;;;; This software is part of the SBCL system. See the README file for
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.
16 ;;; Convert into an IF so that IF optimizations will eliminate redundant
18 (define-source-transform not (x) `(if ,x nil t))
19 (define-source-transform null (x) `(if ,x nil t))
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)))
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
29 (define-source-transform identity (x) `(prog1 ,x))
30 (define-source-transform values (x) `(prog1 ,x))
32 ;;; Bind the value and make a closure that returns it.
33 (define-source-transform constantly (value)
34 (with-unique-names (rest n-value)
35 `(let ((,n-value ,value))
37 (declare (ignore ,rest))
40 ;;; If the function has a known number of arguments, then return a
41 ;;; lambda with the appropriate fixed number of args. If the
42 ;;; destination is a FUNCALL, then do the &REST APPLY thing, and let
43 ;;; MV optimization figure things out.
44 (deftransform complement ((fun) * * :node node)
46 (multiple-value-bind (min max)
47 (fun-type-nargs (continuation-type fun))
49 ((and min (eql min max))
50 (let ((dums (make-gensym-list min)))
51 `#'(lambda ,dums (not (funcall fun ,@dums)))))
52 ((let* ((cont (node-cont node))
53 (dest (continuation-dest cont)))
54 (and (combination-p dest)
55 (eq (combination-fun dest) cont)))
56 '#'(lambda (&rest args)
57 (not (apply fun args))))
59 (give-up-ir1-transform
60 "The function doesn't have a fixed argument count.")))))
64 ;;; Translate CxR into CAR/CDR combos.
65 (defun source-transform-cxr (form)
66 (if (/= (length form) 2)
68 (let ((name (symbol-name (car form))))
69 (do ((i (- (length name) 2) (1- i))
71 `(,(ecase (char name i)
77 ;;; Make source transforms to turn CxR forms into combinations of CAR
78 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
80 (/show0 "about to set CxR source transforms")
81 (loop for i of-type index from 2 upto 4 do
82 ;; Iterate over BUF = all names CxR where x = an I-element
83 ;; string of #\A or #\D characters.
84 (let ((buf (make-string (+ 2 i))))
85 (setf (aref buf 0) #\C
86 (aref buf (1+ i)) #\R)
87 (dotimes (j (ash 2 i))
88 (declare (type index j))
90 (declare (type index k))
91 (setf (aref buf (1+ k))
92 (if (logbitp k j) #\A #\D)))
93 (setf (info :function :source-transform (intern buf))
94 #'source-transform-cxr))))
95 (/show0 "done setting CxR source transforms")
97 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
98 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
99 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
101 (define-source-transform first (x) `(car ,x))
102 (define-source-transform rest (x) `(cdr ,x))
103 (define-source-transform second (x) `(cadr ,x))
104 (define-source-transform third (x) `(caddr ,x))
105 (define-source-transform fourth (x) `(cadddr ,x))
106 (define-source-transform fifth (x) `(nth 4 ,x))
107 (define-source-transform sixth (x) `(nth 5 ,x))
108 (define-source-transform seventh (x) `(nth 6 ,x))
109 (define-source-transform eighth (x) `(nth 7 ,x))
110 (define-source-transform ninth (x) `(nth 8 ,x))
111 (define-source-transform tenth (x) `(nth 9 ,x))
113 ;;; Translate RPLACx to LET and SETF.
114 (define-source-transform rplaca (x y)
119 (define-source-transform rplacd (x y)
125 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
127 (defvar *default-nthcdr-open-code-limit* 6)
128 (defvar *extreme-nthcdr-open-code-limit* 20)
130 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
131 "convert NTHCDR to CAxxR"
132 (unless (constant-continuation-p n)
133 (give-up-ir1-transform))
134 (let ((n (continuation-value n)))
136 (if (policy node (and (= speed 3) (= space 0)))
137 *extreme-nthcdr-open-code-limit*
138 *default-nthcdr-open-code-limit*))
139 (give-up-ir1-transform))
144 `(cdr ,(frob (1- n))))))
147 ;;;; arithmetic and numerology
149 (define-source-transform plusp (x) `(> ,x 0))
150 (define-source-transform minusp (x) `(< ,x 0))
151 (define-source-transform zerop (x) `(= ,x 0))
153 (define-source-transform 1+ (x) `(+ ,x 1))
154 (define-source-transform 1- (x) `(- ,x 1))
156 (define-source-transform oddp (x) `(not (zerop (logand ,x 1))))
157 (define-source-transform evenp (x) `(zerop (logand ,x 1)))
159 ;;; Note that all the integer division functions are available for
160 ;;; inline expansion.
162 (macrolet ((deffrob (fun)
163 `(define-source-transform ,fun (x &optional (y nil y-p))
170 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
172 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
175 (define-source-transform lognand (x y) `(lognot (logand ,x ,y)))
176 (define-source-transform lognor (x y) `(lognot (logior ,x ,y)))
177 (define-source-transform logandc1 (x y) `(logand (lognot ,x) ,y))
178 (define-source-transform logandc2 (x y) `(logand ,x (lognot ,y)))
179 (define-source-transform logorc1 (x y) `(logior (lognot ,x) ,y))
180 (define-source-transform logorc2 (x y) `(logior ,x (lognot ,y)))
181 (define-source-transform logtest (x y) `(not (zerop (logand ,x ,y))))
182 (define-source-transform logbitp (index integer)
183 `(not (zerop (logand (ash 1 ,index) ,integer))))
184 (define-source-transform byte (size position)
185 `(cons ,size ,position))
186 (define-source-transform byte-size (spec) `(car ,spec))
187 (define-source-transform byte-position (spec) `(cdr ,spec))
188 (define-source-transform ldb-test (bytespec integer)
189 `(not (zerop (mask-field ,bytespec ,integer))))
191 ;;; With the ratio and complex accessors, we pick off the "identity"
192 ;;; case, and use a primitive to handle the cell access case.
193 (define-source-transform numerator (num)
194 (once-only ((n-num `(the rational ,num)))
198 (define-source-transform denominator (num)
199 (once-only ((n-num `(the rational ,num)))
201 (%denominator ,n-num)
204 ;;;; interval arithmetic for computing bounds
206 ;;;; This is a set of routines for operating on intervals. It
207 ;;;; implements a simple interval arithmetic package. Although SBCL
208 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
209 ;;;; for two reasons:
211 ;;;; 1. This package is simpler than NUMERIC-TYPE.
213 ;;;; 2. It makes debugging much easier because you can just strip
214 ;;;; out these routines and test them independently of SBCL. (This is a
217 ;;;; One disadvantage is a probable increase in consing because we
218 ;;;; have to create these new interval structures even though
219 ;;;; numeric-type has everything we want to know. Reason 2 wins for
222 ;;; The basic interval type. It can handle open and closed intervals.
223 ;;; A bound is open if it is a list containing a number, just like
224 ;;; Lisp says. NIL means unbounded.
225 (defstruct (interval (:constructor %make-interval)
229 (defun make-interval (&key low high)
230 (labels ((normalize-bound (val)
231 (cond ((and (floatp val)
232 (float-infinity-p val))
233 ;; Handle infinities.
237 ;; Handle any closed bounds.
240 ;; We have an open bound. Normalize the numeric
241 ;; bound. If the normalized bound is still a number
242 ;; (not nil), keep the bound open. Otherwise, the
243 ;; bound is really unbounded, so drop the openness.
244 (let ((new-val (normalize-bound (first val))))
246 ;; The bound exists, so keep it open still.
249 (error "unknown bound type in MAKE-INTERVAL")))))
250 (%make-interval :low (normalize-bound low)
251 :high (normalize-bound high))))
253 ;;; Given a number X, create a form suitable as a bound for an
254 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
255 #!-sb-fluid (declaim (inline set-bound))
256 (defun set-bound (x open-p)
257 (if (and x open-p) (list x) x))
259 ;;; Apply the function F to a bound X. If X is an open bound, then
260 ;;; the result will be open. IF X is NIL, the result is NIL.
261 (defun bound-func (f x)
262 (declare (type function f))
264 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
265 ;; With these traps masked, we might get things like infinity
266 ;; or negative infinity returned. Check for this and return
267 ;; NIL to indicate unbounded.
268 (let ((y (funcall f (type-bound-number x))))
270 (float-infinity-p y))
272 (set-bound (funcall f (type-bound-number x)) (consp x)))))))
274 ;;; Apply a binary operator OP to two bounds X and Y. The result is
275 ;;; NIL if either is NIL. Otherwise bound is computed and the result
276 ;;; is open if either X or Y is open.
278 ;;; FIXME: only used in this file, not needed in target runtime
279 (defmacro bound-binop (op x y)
281 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
282 (set-bound (,op (type-bound-number ,x)
283 (type-bound-number ,y))
284 (or (consp ,x) (consp ,y))))))
286 ;;; Convert a numeric-type object to an interval object.
287 (defun numeric-type->interval (x)
288 (declare (type numeric-type x))
289 (make-interval :low (numeric-type-low x)
290 :high (numeric-type-high x)))
292 (defun copy-interval-limit (limit)
297 (defun copy-interval (x)
298 (declare (type interval x))
299 (make-interval :low (copy-interval-limit (interval-low x))
300 :high (copy-interval-limit (interval-high x))))
302 ;;; Given a point P contained in the interval X, split X into two
303 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
304 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
305 ;;; contains P. You can specify both to be T or NIL.
306 (defun interval-split (p x &optional close-lower close-upper)
307 (declare (type number p)
309 (list (make-interval :low (copy-interval-limit (interval-low x))
310 :high (if close-lower p (list p)))
311 (make-interval :low (if close-upper (list p) p)
312 :high (copy-interval-limit (interval-high x)))))
314 ;;; Return the closure of the interval. That is, convert open bounds
315 ;;; to closed bounds.
316 (defun interval-closure (x)
317 (declare (type interval x))
318 (make-interval :low (type-bound-number (interval-low x))
319 :high (type-bound-number (interval-high x))))
321 (defun signed-zero->= (x y)
325 (>= (float-sign (float x))
326 (float-sign (float y))))))
328 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
329 ;;; '-. Otherwise return NIL.
331 (defun interval-range-info (x &optional (point 0))
332 (declare (type interval x))
333 (let ((lo (interval-low x))
334 (hi (interval-high x)))
335 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
337 ((and hi (signed-zero->= point (type-bound-number hi)))
341 (defun interval-range-info (x &optional (point 0))
342 (declare (type interval x))
343 (labels ((signed->= (x y)
344 (if (and (zerop x) (zerop y) (floatp x) (floatp y))
345 (>= (float-sign x) (float-sign y))
347 (let ((lo (interval-low x))
348 (hi (interval-high x)))
349 (cond ((and lo (signed->= (type-bound-number lo) point))
351 ((and hi (signed->= point (type-bound-number hi)))
356 ;;; Test to see whether the interval X is bounded. HOW determines the
357 ;;; test, and should be either ABOVE, BELOW, or BOTH.
358 (defun interval-bounded-p (x how)
359 (declare (type interval x))
366 (and (interval-low x) (interval-high x)))))
368 ;;; signed zero comparison functions. Use these functions if we need
369 ;;; to distinguish between signed zeroes.
370 (defun signed-zero-< (x y)
374 (< (float-sign (float x))
375 (float-sign (float y))))))
376 (defun signed-zero-> (x y)
380 (> (float-sign (float x))
381 (float-sign (float y))))))
382 (defun signed-zero-= (x y)
385 (= (float-sign (float x))
386 (float-sign (float y)))))
387 (defun signed-zero-<= (x y)
391 (<= (float-sign (float x))
392 (float-sign (float y))))))
394 ;;; See whether the interval X contains the number P, taking into
395 ;;; account that the interval might not be closed.
396 (defun interval-contains-p (p x)
397 (declare (type number p)
399 ;; Does the interval X contain the number P? This would be a lot
400 ;; easier if all intervals were closed!
401 (let ((lo (interval-low x))
402 (hi (interval-high x)))
404 ;; The interval is bounded
405 (if (and (signed-zero-<= (type-bound-number lo) p)
406 (signed-zero-<= p (type-bound-number hi)))
407 ;; P is definitely in the closure of the interval.
408 ;; We just need to check the end points now.
409 (cond ((signed-zero-= p (type-bound-number lo))
411 ((signed-zero-= p (type-bound-number hi))
416 ;; Interval with upper bound
417 (if (signed-zero-< p (type-bound-number hi))
419 (and (numberp hi) (signed-zero-= p hi))))
421 ;; Interval with lower bound
422 (if (signed-zero-> p (type-bound-number lo))
424 (and (numberp lo) (signed-zero-= p lo))))
426 ;; Interval with no bounds
429 ;;; Determine whether two intervals X and Y intersect. Return T if so.
430 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
431 ;;; were closed. Otherwise the intervals are treated as they are.
433 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
434 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
435 ;;; is T, then they do intersect because we use the closure of X = [0,
436 ;;; 1] and Y = [1, 2] to determine intersection.
437 (defun interval-intersect-p (x y &optional closed-intervals-p)
438 (declare (type interval x y))
439 (multiple-value-bind (intersect diff)
440 (interval-intersection/difference (if closed-intervals-p
443 (if closed-intervals-p
446 (declare (ignore diff))
449 ;;; Are the two intervals adjacent? That is, is there a number
450 ;;; between the two intervals that is not an element of either
451 ;;; interval? If so, they are not adjacent. For example [0, 1) and
452 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
453 ;;; between both intervals.
454 (defun interval-adjacent-p (x y)
455 (declare (type interval x y))
456 (flet ((adjacent (lo hi)
457 ;; Check to see whether lo and hi are adjacent. If either is
458 ;; nil, they can't be adjacent.
459 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
460 ;; The bounds are equal. They are adjacent if one of
461 ;; them is closed (a number). If both are open (consp),
462 ;; then there is a number that lies between them.
463 (or (numberp lo) (numberp hi)))))
464 (or (adjacent (interval-low y) (interval-high x))
465 (adjacent (interval-low x) (interval-high y)))))
467 ;;; Compute the intersection and difference between two intervals.
468 ;;; Two values are returned: the intersection and the difference.
470 ;;; Let the two intervals be X and Y, and let I and D be the two
471 ;;; values returned by this function. Then I = X intersect Y. If I
472 ;;; is NIL (the empty set), then D is X union Y, represented as the
473 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
474 ;;; - I, which is a list of two intervals.
476 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
477 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
478 (defun interval-intersection/difference (x y)
479 (declare (type interval x y))
480 (let ((x-lo (interval-low x))
481 (x-hi (interval-high x))
482 (y-lo (interval-low y))
483 (y-hi (interval-high y)))
486 ;; If p is an open bound, make it closed. If p is a closed
487 ;; bound, make it open.
492 ;; Test whether P is in the interval.
493 (when (interval-contains-p (type-bound-number p)
494 (interval-closure int))
495 (let ((lo (interval-low int))
496 (hi (interval-high int)))
497 ;; Check for endpoints.
498 (cond ((and lo (= (type-bound-number p) (type-bound-number lo)))
499 (not (and (consp p) (numberp lo))))
500 ((and hi (= (type-bound-number p) (type-bound-number hi)))
501 (not (and (numberp p) (consp hi))))
503 (test-lower-bound (p int)
504 ;; P is a lower bound of an interval.
507 (not (interval-bounded-p int 'below))))
508 (test-upper-bound (p int)
509 ;; P is an upper bound of an interval.
512 (not (interval-bounded-p int 'above)))))
513 (let ((x-lo-in-y (test-lower-bound x-lo y))
514 (x-hi-in-y (test-upper-bound x-hi y))
515 (y-lo-in-x (test-lower-bound y-lo x))
516 (y-hi-in-x (test-upper-bound y-hi x)))
517 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
518 ;; Intervals intersect. Let's compute the intersection
519 ;; and the difference.
520 (multiple-value-bind (lo left-lo left-hi)
521 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
522 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
523 (multiple-value-bind (hi right-lo right-hi)
525 (values x-hi (opposite-bound x-hi) y-hi))
527 (values y-hi (opposite-bound y-hi) x-hi)))
528 (values (make-interval :low lo :high hi)
529 (list (make-interval :low left-lo
531 (make-interval :low right-lo
534 (values nil (list x y))))))))
536 ;;; If intervals X and Y intersect, return a new interval that is the
537 ;;; union of the two. If they do not intersect, return NIL.
538 (defun interval-merge-pair (x y)
539 (declare (type interval x y))
540 ;; If x and y intersect or are adjacent, create the union.
541 ;; Otherwise return nil
542 (when (or (interval-intersect-p x y)
543 (interval-adjacent-p x y))
544 (flet ((select-bound (x1 x2 min-op max-op)
545 (let ((x1-val (type-bound-number x1))
546 (x2-val (type-bound-number x2)))
548 ;; Both bounds are finite. Select the right one.
549 (cond ((funcall min-op x1-val x2-val)
550 ;; x1 is definitely better.
552 ((funcall max-op x1-val x2-val)
553 ;; x2 is definitely better.
556 ;; Bounds are equal. Select either
557 ;; value and make it open only if
559 (set-bound x1-val (and (consp x1) (consp x2))))))
561 ;; At least one bound is not finite. The
562 ;; non-finite bound always wins.
564 (let* ((x-lo (copy-interval-limit (interval-low x)))
565 (x-hi (copy-interval-limit (interval-high x)))
566 (y-lo (copy-interval-limit (interval-low y)))
567 (y-hi (copy-interval-limit (interval-high y))))
568 (make-interval :low (select-bound x-lo y-lo #'< #'>)
569 :high (select-bound x-hi y-hi #'> #'<))))))
571 ;;; basic arithmetic operations on intervals. We probably should do
572 ;;; true interval arithmetic here, but it's complicated because we
573 ;;; have float and integer types and bounds can be open or closed.
575 ;;; the negative of an interval
576 (defun interval-neg (x)
577 (declare (type interval x))
578 (make-interval :low (bound-func #'- (interval-high x))
579 :high (bound-func #'- (interval-low x))))
581 ;;; Add two intervals.
582 (defun interval-add (x y)
583 (declare (type interval x y))
584 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
585 :high (bound-binop + (interval-high x) (interval-high y))))
587 ;;; Subtract two intervals.
588 (defun interval-sub (x y)
589 (declare (type interval x y))
590 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
591 :high (bound-binop - (interval-high x) (interval-low y))))
593 ;;; Multiply two intervals.
594 (defun interval-mul (x y)
595 (declare (type interval x y))
596 (flet ((bound-mul (x y)
597 (cond ((or (null x) (null y))
598 ;; Multiply by infinity is infinity
600 ((or (and (numberp x) (zerop x))
601 (and (numberp y) (zerop y)))
602 ;; Multiply by closed zero is special. The result
603 ;; is always a closed bound. But don't replace this
604 ;; with zero; we want the multiplication to produce
605 ;; the correct signed zero, if needed.
606 (* (type-bound-number x) (type-bound-number y)))
607 ((or (and (floatp x) (float-infinity-p x))
608 (and (floatp y) (float-infinity-p y)))
609 ;; Infinity times anything is infinity
612 ;; General multiply. The result is open if either is open.
613 (bound-binop * x y)))))
614 (let ((x-range (interval-range-info x))
615 (y-range (interval-range-info y)))
616 (cond ((null x-range)
617 ;; Split x into two and multiply each separately
618 (destructuring-bind (x- x+) (interval-split 0 x t t)
619 (interval-merge-pair (interval-mul x- y)
620 (interval-mul x+ y))))
622 ;; Split y into two and multiply each separately
623 (destructuring-bind (y- y+) (interval-split 0 y t t)
624 (interval-merge-pair (interval-mul x y-)
625 (interval-mul x y+))))
627 (interval-neg (interval-mul (interval-neg x) y)))
629 (interval-neg (interval-mul x (interval-neg y))))
630 ((and (eq x-range '+) (eq y-range '+))
631 ;; If we are here, X and Y are both positive.
633 :low (bound-mul (interval-low x) (interval-low y))
634 :high (bound-mul (interval-high x) (interval-high y))))
636 (bug "excluded case in INTERVAL-MUL"))))))
638 ;;; Divide two intervals.
639 (defun interval-div (top bot)
640 (declare (type interval top bot))
641 (flet ((bound-div (x y y-low-p)
644 ;; Divide by infinity means result is 0. However,
645 ;; we need to watch out for the sign of the result,
646 ;; to correctly handle signed zeros. We also need
647 ;; to watch out for positive or negative infinity.
648 (if (floatp (type-bound-number x))
650 (- (float-sign (type-bound-number x) 0.0))
651 (float-sign (type-bound-number x) 0.0))
653 ((zerop (type-bound-number y))
654 ;; Divide by zero means result is infinity
656 ((and (numberp x) (zerop x))
657 ;; Zero divided by anything is zero.
660 (bound-binop / x y)))))
661 (let ((top-range (interval-range-info top))
662 (bot-range (interval-range-info bot)))
663 (cond ((null bot-range)
664 ;; The denominator contains zero, so anything goes!
665 (make-interval :low nil :high nil))
667 ;; Denominator is negative so flip the sign, compute the
668 ;; result, and flip it back.
669 (interval-neg (interval-div top (interval-neg bot))))
671 ;; Split top into two positive and negative parts, and
672 ;; divide each separately
673 (destructuring-bind (top- top+) (interval-split 0 top t t)
674 (interval-merge-pair (interval-div top- bot)
675 (interval-div top+ bot))))
677 ;; Top is negative so flip the sign, divide, and flip the
678 ;; sign of the result.
679 (interval-neg (interval-div (interval-neg top) bot)))
680 ((and (eq top-range '+) (eq bot-range '+))
683 :low (bound-div (interval-low top) (interval-high bot) t)
684 :high (bound-div (interval-high top) (interval-low bot) nil)))
686 (bug "excluded case in INTERVAL-DIV"))))))
688 ;;; Apply the function F to the interval X. If X = [a, b], then the
689 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
690 ;;; result makes sense. It will if F is monotonic increasing (or
692 (defun interval-func (f x)
693 (declare (type function f)
695 (let ((lo (bound-func f (interval-low x)))
696 (hi (bound-func f (interval-high x))))
697 (make-interval :low lo :high hi)))
699 ;;; Return T if X < Y. That is every number in the interval X is
700 ;;; always less than any number in the interval Y.
701 (defun interval-< (x y)
702 (declare (type interval x y))
703 ;; X < Y only if X is bounded above, Y is bounded below, and they
705 (when (and (interval-bounded-p x 'above)
706 (interval-bounded-p y 'below))
707 ;; Intervals are bounded in the appropriate way. Make sure they
709 (let ((left (interval-high x))
710 (right (interval-low y)))
711 (cond ((> (type-bound-number left)
712 (type-bound-number right))
713 ;; The intervals definitely overlap, so result is NIL.
715 ((< (type-bound-number left)
716 (type-bound-number right))
717 ;; The intervals definitely don't touch, so result is T.
720 ;; Limits are equal. Check for open or closed bounds.
721 ;; Don't overlap if one or the other are open.
722 (or (consp left) (consp right)))))))
724 ;;; Return T if X >= Y. That is, every number in the interval X is
725 ;;; always greater than any number in the interval Y.
726 (defun interval->= (x y)
727 (declare (type interval x y))
728 ;; X >= Y if lower bound of X >= upper bound of Y
729 (when (and (interval-bounded-p x 'below)
730 (interval-bounded-p y 'above))
731 (>= (type-bound-number (interval-low x))
732 (type-bound-number (interval-high y)))))
734 ;;; Return an interval that is the absolute value of X. Thus, if
735 ;;; X = [-1 10], the result is [0, 10].
736 (defun interval-abs (x)
737 (declare (type interval x))
738 (case (interval-range-info x)
744 (destructuring-bind (x- x+) (interval-split 0 x t t)
745 (interval-merge-pair (interval-neg x-) x+)))))
747 ;;; Compute the square of an interval.
748 (defun interval-sqr (x)
749 (declare (type interval x))
750 (interval-func (lambda (x) (* x x))
753 ;;;; numeric DERIVE-TYPE methods
755 ;;; a utility for defining derive-type methods of integer operations. If
756 ;;; the types of both X and Y are integer types, then we compute a new
757 ;;; integer type with bounds determined Fun when applied to X and Y.
758 ;;; Otherwise, we use Numeric-Contagion.
759 (defun derive-integer-type (x y fun)
760 (declare (type continuation x y) (type function fun))
761 (let ((x (continuation-type x))
762 (y (continuation-type y)))
763 (if (and (numeric-type-p x) (numeric-type-p y)
764 (eq (numeric-type-class x) 'integer)
765 (eq (numeric-type-class y) 'integer)
766 (eq (numeric-type-complexp x) :real)
767 (eq (numeric-type-complexp y) :real))
768 (multiple-value-bind (low high) (funcall fun x y)
769 (make-numeric-type :class 'integer
773 (numeric-contagion x y))))
775 ;;; simple utility to flatten a list
776 (defun flatten-list (x)
777 (labels ((flatten-helper (x r);; 'r' is the stuff to the 'right'.
781 (t (flatten-helper (car x)
782 (flatten-helper (cdr x) r))))))
783 (flatten-helper x nil)))
785 ;;; Take some type of continuation and massage it so that we get a
786 ;;; list of the constituent types. If ARG is *EMPTY-TYPE*, return NIL
787 ;;; to indicate failure.
788 (defun prepare-arg-for-derive-type (arg)
789 (flet ((listify (arg)
794 (union-type-types arg))
797 (unless (eq arg *empty-type*)
798 ;; Make sure all args are some type of numeric-type. For member
799 ;; types, convert the list of members into a union of equivalent
800 ;; single-element member-type's.
801 (let ((new-args nil))
802 (dolist (arg (listify arg))
803 (if (member-type-p arg)
804 ;; Run down the list of members and convert to a list of
806 (dolist (member (member-type-members arg))
807 (push (if (numberp member)
808 (make-member-type :members (list member))
811 (push arg new-args)))
812 (unless (member *empty-type* new-args)
815 ;;; Convert from the standard type convention for which -0.0 and 0.0
816 ;;; are equal to an intermediate convention for which they are
817 ;;; considered different which is more natural for some of the
819 (defun convert-numeric-type (type)
820 (declare (type numeric-type type))
821 ;;; Only convert real float interval delimiters types.
822 (if (eq (numeric-type-complexp type) :real)
823 (let* ((lo (numeric-type-low type))
824 (lo-val (type-bound-number lo))
825 (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
826 (hi (numeric-type-high type))
827 (hi-val (type-bound-number hi))
828 (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
829 (if (or lo-float-zero-p hi-float-zero-p)
831 :class (numeric-type-class type)
832 :format (numeric-type-format type)
834 :low (if lo-float-zero-p
836 (list (float 0.0 lo-val))
839 :high (if hi-float-zero-p
841 (list (float -0.0 hi-val))
848 ;;; Convert back from the intermediate convention for which -0.0 and
849 ;;; 0.0 are considered different to the standard type convention for
851 (defun convert-back-numeric-type (type)
852 (declare (type numeric-type type))
853 ;;; Only convert real float interval delimiters types.
854 (if (eq (numeric-type-complexp type) :real)
855 (let* ((lo (numeric-type-low type))
856 (lo-val (type-bound-number lo))
858 (and lo (floatp lo-val) (= lo-val 0.0)
859 (float-sign lo-val)))
860 (hi (numeric-type-high type))
861 (hi-val (type-bound-number hi))
863 (and hi (floatp hi-val) (= hi-val 0.0)
864 (float-sign hi-val))))
866 ;; (float +0.0 +0.0) => (member 0.0)
867 ;; (float -0.0 -0.0) => (member -0.0)
868 ((and lo-float-zero-p hi-float-zero-p)
869 ;; shouldn't have exclusive bounds here..
870 (aver (and (not (consp lo)) (not (consp hi))))
871 (if (= lo-float-zero-p hi-float-zero-p)
872 ;; (float +0.0 +0.0) => (member 0.0)
873 ;; (float -0.0 -0.0) => (member -0.0)
874 (specifier-type `(member ,lo-val))
875 ;; (float -0.0 +0.0) => (float 0.0 0.0)
876 ;; (float +0.0 -0.0) => (float 0.0 0.0)
877 (make-numeric-type :class (numeric-type-class type)
878 :format (numeric-type-format type)
884 ;; (float -0.0 x) => (float 0.0 x)
885 ((and (not (consp lo)) (minusp lo-float-zero-p))
886 (make-numeric-type :class (numeric-type-class type)
887 :format (numeric-type-format type)
889 :low (float 0.0 lo-val)
891 ;; (float (+0.0) x) => (float (0.0) x)
892 ((and (consp lo) (plusp lo-float-zero-p))
893 (make-numeric-type :class (numeric-type-class type)
894 :format (numeric-type-format type)
896 :low (list (float 0.0 lo-val))
899 ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
900 ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
901 (list (make-member-type :members (list (float 0.0 lo-val)))
902 (make-numeric-type :class (numeric-type-class type)
903 :format (numeric-type-format type)
905 :low (list (float 0.0 lo-val))
909 ;; (float x +0.0) => (float x 0.0)
910 ((and (not (consp hi)) (plusp hi-float-zero-p))
911 (make-numeric-type :class (numeric-type-class type)
912 :format (numeric-type-format type)
915 :high (float 0.0 hi-val)))
916 ;; (float x (-0.0)) => (float x (0.0))
917 ((and (consp hi) (minusp hi-float-zero-p))
918 (make-numeric-type :class (numeric-type-class type)
919 :format (numeric-type-format type)
922 :high (list (float 0.0 hi-val))))
924 ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
925 ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
926 (list (make-member-type :members (list (float -0.0 hi-val)))
927 (make-numeric-type :class (numeric-type-class type)
928 :format (numeric-type-format type)
931 :high (list (float 0.0 hi-val)))))))
937 ;;; Convert back a possible list of numeric types.
938 (defun convert-back-numeric-type-list (type-list)
942 (dolist (type type-list)
943 (if (numeric-type-p type)
944 (let ((result (convert-back-numeric-type type)))
946 (setf results (append results result))
947 (push result results)))
948 (push type results)))
951 (convert-back-numeric-type type-list))
953 (convert-back-numeric-type-list (union-type-types type-list)))
957 ;;; FIXME: MAKE-CANONICAL-UNION-TYPE and CONVERT-MEMBER-TYPE probably
958 ;;; belong in the kernel's type logic, invoked always, instead of in
959 ;;; the compiler, invoked only during some type optimizations.
961 ;;; Take a list of types and return a canonical type specifier,
962 ;;; combining any MEMBER types together. If both positive and negative
963 ;;; MEMBER types are present they are converted to a float type.
964 ;;; XXX This would be far simpler if the type-union methods could handle
965 ;;; member/number unions.
966 (defun make-canonical-union-type (type-list)
969 (dolist (type type-list)
970 (if (member-type-p type)
971 (setf members (union members (member-type-members type)))
972 (push type misc-types)))
974 (when (null (set-difference '(-0l0 0l0) members))
975 (push (specifier-type '(long-float 0l0 0l0)) misc-types)
976 (setf members (set-difference members '(-0l0 0l0))))
977 (when (null (set-difference '(-0d0 0d0) members))
978 (push (specifier-type '(double-float 0d0 0d0)) misc-types)
979 (setf members (set-difference members '(-0d0 0d0))))
980 (when (null (set-difference '(-0f0 0f0) members))
981 (push (specifier-type '(single-float 0f0 0f0)) misc-types)
982 (setf members (set-difference members '(-0f0 0f0))))
984 (apply #'type-union (make-member-type :members members) misc-types)
985 (apply #'type-union misc-types))))
987 ;;; Convert a member type with a single member to a numeric type.
988 (defun convert-member-type (arg)
989 (let* ((members (member-type-members arg))
990 (member (first members))
991 (member-type (type-of member)))
992 (aver (not (rest members)))
993 (specifier-type `(,(if (subtypep member-type 'integer)
998 ;;; This is used in defoptimizers for computing the resulting type of
1001 ;;; Given the continuation ARG, derive the resulting type using the
1002 ;;; DERIVE-FCN. DERIVE-FCN takes exactly one argument which is some
1003 ;;; "atomic" continuation type like numeric-type or member-type
1004 ;;; (containing just one element). It should return the resulting
1005 ;;; type, which can be a list of types.
1007 ;;; For the case of member types, if a member-fcn is given it is
1008 ;;; called to compute the result otherwise the member type is first
1009 ;;; converted to a numeric type and the derive-fcn is call.
1010 (defun one-arg-derive-type (arg derive-fcn member-fcn
1011 &optional (convert-type t))
1012 (declare (type function derive-fcn)
1013 (type (or null function) member-fcn))
1014 (let ((arg-list (prepare-arg-for-derive-type (continuation-type arg))))
1020 (with-float-traps-masked
1021 (:underflow :overflow :divide-by-zero)
1025 (first (member-type-members x))))))
1026 ;; Otherwise convert to a numeric type.
1027 (let ((result-type-list
1028 (funcall derive-fcn (convert-member-type x))))
1030 (convert-back-numeric-type-list result-type-list)
1031 result-type-list))))
1034 (convert-back-numeric-type-list
1035 (funcall derive-fcn (convert-numeric-type x)))
1036 (funcall derive-fcn x)))
1038 *universal-type*))))
1039 ;; Run down the list of args and derive the type of each one,
1040 ;; saving all of the results in a list.
1041 (let ((results nil))
1042 (dolist (arg arg-list)
1043 (let ((result (deriver arg)))
1045 (setf results (append results result))
1046 (push result results))))
1048 (make-canonical-union-type results)
1049 (first results)))))))
1051 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1052 ;;; two arguments. DERIVE-FCN takes 3 args in this case: the two
1053 ;;; original args and a third which is T to indicate if the two args
1054 ;;; really represent the same continuation. This is useful for
1055 ;;; deriving the type of things like (* x x), which should always be
1056 ;;; positive. If we didn't do this, we wouldn't be able to tell.
1057 (defun two-arg-derive-type (arg1 arg2 derive-fcn fcn
1058 &optional (convert-type t))
1059 (declare (type function derive-fcn fcn))
1060 (flet ((deriver (x y same-arg)
1061 (cond ((and (member-type-p x) (member-type-p y))
1062 (let* ((x (first (member-type-members x)))
1063 (y (first (member-type-members y)))
1064 (result (with-float-traps-masked
1065 (:underflow :overflow :divide-by-zero
1067 (funcall fcn x y))))
1068 (cond ((null result))
1069 ((and (floatp result) (float-nan-p result))
1070 (make-numeric-type :class 'float
1071 :format (type-of result)
1074 (make-member-type :members (list result))))))
1075 ((and (member-type-p x) (numeric-type-p y))
1076 (let* ((x (convert-member-type x))
1077 (y (if convert-type (convert-numeric-type y) y))
1078 (result (funcall derive-fcn x y same-arg)))
1080 (convert-back-numeric-type-list result)
1082 ((and (numeric-type-p x) (member-type-p y))
1083 (let* ((x (if convert-type (convert-numeric-type x) x))
1084 (y (convert-member-type y))
1085 (result (funcall derive-fcn x y same-arg)))
1087 (convert-back-numeric-type-list result)
1089 ((and (numeric-type-p x) (numeric-type-p y))
1090 (let* ((x (if convert-type (convert-numeric-type x) x))
1091 (y (if convert-type (convert-numeric-type y) y))
1092 (result (funcall derive-fcn x y same-arg)))
1094 (convert-back-numeric-type-list result)
1097 *universal-type*))))
1098 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1099 (a1 (prepare-arg-for-derive-type (continuation-type arg1)))
1100 (a2 (prepare-arg-for-derive-type (continuation-type arg2))))
1102 (let ((results nil))
1104 ;; Since the args are the same continuation, just run
1107 (let ((result (deriver x x same-arg)))
1109 (setf results (append results result))
1110 (push result results))))
1111 ;; Try all pairwise combinations.
1114 (let ((result (or (deriver x y same-arg)
1115 (numeric-contagion x y))))
1117 (setf results (append results result))
1118 (push result results))))))
1120 (make-canonical-union-type results)
1121 (first results)))))))
1123 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1125 (defoptimizer (+ derive-type) ((x y))
1126 (derive-integer-type
1133 (values (frob (numeric-type-low x) (numeric-type-low y))
1134 (frob (numeric-type-high x) (numeric-type-high y)))))))
1136 (defoptimizer (- derive-type) ((x y))
1137 (derive-integer-type
1144 (values (frob (numeric-type-low x) (numeric-type-high y))
1145 (frob (numeric-type-high x) (numeric-type-low y)))))))
1147 (defoptimizer (* derive-type) ((x y))
1148 (derive-integer-type
1151 (let ((x-low (numeric-type-low x))
1152 (x-high (numeric-type-high x))
1153 (y-low (numeric-type-low y))
1154 (y-high (numeric-type-high y)))
1155 (cond ((not (and x-low y-low))
1157 ((or (minusp x-low) (minusp y-low))
1158 (if (and x-high y-high)
1159 (let ((max (* (max (abs x-low) (abs x-high))
1160 (max (abs y-low) (abs y-high)))))
1161 (values (- max) max))
1164 (values (* x-low y-low)
1165 (if (and x-high y-high)
1169 (defoptimizer (/ derive-type) ((x y))
1170 (numeric-contagion (continuation-type x) (continuation-type y)))
1174 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1176 (defun +-derive-type-aux (x y same-arg)
1177 (if (and (numeric-type-real-p x)
1178 (numeric-type-real-p y))
1181 (let ((x-int (numeric-type->interval x)))
1182 (interval-add x-int x-int))
1183 (interval-add (numeric-type->interval x)
1184 (numeric-type->interval y))))
1185 (result-type (numeric-contagion x y)))
1186 ;; If the result type is a float, we need to be sure to coerce
1187 ;; the bounds into the correct type.
1188 (when (eq (numeric-type-class result-type) 'float)
1189 (setf result (interval-func
1191 (coerce x (or (numeric-type-format result-type)
1195 :class (if (and (eq (numeric-type-class x) 'integer)
1196 (eq (numeric-type-class y) 'integer))
1197 ;; The sum of integers is always an integer.
1199 (numeric-type-class result-type))
1200 :format (numeric-type-format result-type)
1201 :low (interval-low result)
1202 :high (interval-high result)))
1203 ;; general contagion
1204 (numeric-contagion x y)))
1206 (defoptimizer (+ derive-type) ((x y))
1207 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1209 (defun --derive-type-aux (x y same-arg)
1210 (if (and (numeric-type-real-p x)
1211 (numeric-type-real-p y))
1213 ;; (- X X) is always 0.
1215 (make-interval :low 0 :high 0)
1216 (interval-sub (numeric-type->interval x)
1217 (numeric-type->interval y))))
1218 (result-type (numeric-contagion x y)))
1219 ;; If the result type is a float, we need to be sure to coerce
1220 ;; the bounds into the correct type.
1221 (when (eq (numeric-type-class result-type) 'float)
1222 (setf result (interval-func
1224 (coerce x (or (numeric-type-format result-type)
1228 :class (if (and (eq (numeric-type-class x) 'integer)
1229 (eq (numeric-type-class y) 'integer))
1230 ;; The difference of integers is always an integer.
1232 (numeric-type-class result-type))
1233 :format (numeric-type-format result-type)
1234 :low (interval-low result)
1235 :high (interval-high result)))
1236 ;; general contagion
1237 (numeric-contagion x y)))
1239 (defoptimizer (- derive-type) ((x y))
1240 (two-arg-derive-type x y #'--derive-type-aux #'-))
1242 (defun *-derive-type-aux (x y same-arg)
1243 (if (and (numeric-type-real-p x)
1244 (numeric-type-real-p y))
1246 ;; (* X X) is always positive, so take care to do it right.
1248 (interval-sqr (numeric-type->interval x))
1249 (interval-mul (numeric-type->interval x)
1250 (numeric-type->interval y))))
1251 (result-type (numeric-contagion x y)))
1252 ;; If the result type is a float, we need to be sure to coerce
1253 ;; the bounds into the correct type.
1254 (when (eq (numeric-type-class result-type) 'float)
1255 (setf result (interval-func
1257 (coerce x (or (numeric-type-format result-type)
1261 :class (if (and (eq (numeric-type-class x) 'integer)
1262 (eq (numeric-type-class y) 'integer))
1263 ;; The product of integers is always an integer.
1265 (numeric-type-class result-type))
1266 :format (numeric-type-format result-type)
1267 :low (interval-low result)
1268 :high (interval-high result)))
1269 (numeric-contagion x y)))
1271 (defoptimizer (* derive-type) ((x y))
1272 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1274 (defun /-derive-type-aux (x y same-arg)
1275 (if (and (numeric-type-real-p x)
1276 (numeric-type-real-p y))
1278 ;; (/ X X) is always 1, except if X can contain 0. In
1279 ;; that case, we shouldn't optimize the division away
1280 ;; because we want 0/0 to signal an error.
1282 (not (interval-contains-p
1283 0 (interval-closure (numeric-type->interval y)))))
1284 (make-interval :low 1 :high 1)
1285 (interval-div (numeric-type->interval x)
1286 (numeric-type->interval y))))
1287 (result-type (numeric-contagion x y)))
1288 ;; If the result type is a float, we need to be sure to coerce
1289 ;; the bounds into the correct type.
1290 (when (eq (numeric-type-class result-type) 'float)
1291 (setf result (interval-func
1293 (coerce x (or (numeric-type-format result-type)
1296 (make-numeric-type :class (numeric-type-class result-type)
1297 :format (numeric-type-format result-type)
1298 :low (interval-low result)
1299 :high (interval-high result)))
1300 (numeric-contagion x y)))
1302 (defoptimizer (/ derive-type) ((x y))
1303 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1307 (defun ash-derive-type-aux (n-type shift same-arg)
1308 (declare (ignore same-arg))
1309 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1310 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1311 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1312 ;; two bignums yielding zero) and it's hard to avoid that
1313 ;; calculation in here.
1314 #+(and cmu sb-xc-host)
1315 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1316 (typep (numeric-type-high n-type) 'bignum))
1317 (or (typep (numeric-type-low shift) 'bignum)
1318 (typep (numeric-type-high shift) 'bignum)))
1319 (return-from ash-derive-type-aux *universal-type*))
1320 (flet ((ash-outer (n s)
1321 (when (and (fixnump s)
1323 (> s sb!xc:most-negative-fixnum))
1325 ;; KLUDGE: The bare 64's here should be related to
1326 ;; symbolic machine word size values somehow.
1329 (if (and (fixnump s)
1330 (> s sb!xc:most-negative-fixnum))
1332 (if (minusp n) -1 0))))
1333 (or (and (csubtypep n-type (specifier-type 'integer))
1334 (csubtypep shift (specifier-type 'integer))
1335 (let ((n-low (numeric-type-low n-type))
1336 (n-high (numeric-type-high n-type))
1337 (s-low (numeric-type-low shift))
1338 (s-high (numeric-type-high shift)))
1339 (make-numeric-type :class 'integer :complexp :real
1342 (ash-outer n-low s-high)
1343 (ash-inner n-low s-low)))
1346 (ash-inner n-high s-low)
1347 (ash-outer n-high s-high))))))
1350 (defoptimizer (ash derive-type) ((n shift))
1351 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1353 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1354 (macrolet ((frob (fun)
1355 `#'(lambda (type type2)
1356 (declare (ignore type2))
1357 (let ((lo (numeric-type-low type))
1358 (hi (numeric-type-high type)))
1359 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1361 (defoptimizer (%negate derive-type) ((num))
1362 (derive-integer-type num num (frob -))))
1364 (defoptimizer (lognot derive-type) ((int))
1365 (derive-integer-type int int
1366 (lambda (type type2)
1367 (declare (ignore type2))
1368 (let ((lo (numeric-type-low type))
1369 (hi (numeric-type-high type)))
1370 (values (if hi (lognot hi) nil)
1371 (if lo (lognot lo) nil)
1372 (numeric-type-class type)
1373 (numeric-type-format type))))))
1375 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1376 (defoptimizer (%negate derive-type) ((num))
1377 (flet ((negate-bound (b)
1379 (set-bound (- (type-bound-number b))
1381 (one-arg-derive-type num
1383 (modified-numeric-type
1385 :low (negate-bound (numeric-type-high type))
1386 :high (negate-bound (numeric-type-low type))))
1389 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1390 (defoptimizer (abs derive-type) ((num))
1391 (let ((type (continuation-type num)))
1392 (if (and (numeric-type-p type)
1393 (eq (numeric-type-class type) 'integer)
1394 (eq (numeric-type-complexp type) :real))
1395 (let ((lo (numeric-type-low type))
1396 (hi (numeric-type-high type)))
1397 (make-numeric-type :class 'integer :complexp :real
1398 :low (cond ((and hi (minusp hi))
1404 :high (if (and hi lo)
1405 (max (abs hi) (abs lo))
1407 (numeric-contagion type type))))
1409 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1410 (defun abs-derive-type-aux (type)
1411 (cond ((eq (numeric-type-complexp type) :complex)
1412 ;; The absolute value of a complex number is always a
1413 ;; non-negative float.
1414 (let* ((format (case (numeric-type-class type)
1415 ((integer rational) 'single-float)
1416 (t (numeric-type-format type))))
1417 (bound-format (or format 'float)))
1418 (make-numeric-type :class 'float
1421 :low (coerce 0 bound-format)
1424 ;; The absolute value of a real number is a non-negative real
1425 ;; of the same type.
1426 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1427 (class (numeric-type-class type))
1428 (format (numeric-type-format type))
1429 (bound-type (or format class 'real)))
1434 :low (coerce-numeric-bound (interval-low abs-bnd) bound-type)
1435 :high (coerce-numeric-bound
1436 (interval-high abs-bnd) bound-type))))))
1438 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1439 (defoptimizer (abs derive-type) ((num))
1440 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1442 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1443 (defoptimizer (truncate derive-type) ((number divisor))
1444 (let ((number-type (continuation-type number))
1445 (divisor-type (continuation-type divisor))
1446 (integer-type (specifier-type 'integer)))
1447 (if (and (numeric-type-p number-type)
1448 (csubtypep number-type integer-type)
1449 (numeric-type-p divisor-type)
1450 (csubtypep divisor-type integer-type))
1451 (let ((number-low (numeric-type-low number-type))
1452 (number-high (numeric-type-high number-type))
1453 (divisor-low (numeric-type-low divisor-type))
1454 (divisor-high (numeric-type-high divisor-type)))
1455 (values-specifier-type
1456 `(values ,(integer-truncate-derive-type number-low number-high
1457 divisor-low divisor-high)
1458 ,(integer-rem-derive-type number-low number-high
1459 divisor-low divisor-high))))
1462 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1465 (defun rem-result-type (number-type divisor-type)
1466 ;; Figure out what the remainder type is. The remainder is an
1467 ;; integer if both args are integers; a rational if both args are
1468 ;; rational; and a float otherwise.
1469 (cond ((and (csubtypep number-type (specifier-type 'integer))
1470 (csubtypep divisor-type (specifier-type 'integer)))
1472 ((and (csubtypep number-type (specifier-type 'rational))
1473 (csubtypep divisor-type (specifier-type 'rational)))
1475 ((and (csubtypep number-type (specifier-type 'float))
1476 (csubtypep divisor-type (specifier-type 'float)))
1477 ;; Both are floats so the result is also a float, of
1478 ;; the largest type.
1479 (or (float-format-max (numeric-type-format number-type)
1480 (numeric-type-format divisor-type))
1482 ((and (csubtypep number-type (specifier-type 'float))
1483 (csubtypep divisor-type (specifier-type 'rational)))
1484 ;; One of the arguments is a float and the other is a
1485 ;; rational. The remainder is a float of the same
1487 (or (numeric-type-format number-type) 'float))
1488 ((and (csubtypep divisor-type (specifier-type 'float))
1489 (csubtypep number-type (specifier-type 'rational)))
1490 ;; One of the arguments is a float and the other is a
1491 ;; rational. The remainder is a float of the same
1493 (or (numeric-type-format divisor-type) 'float))
1495 ;; Some unhandled combination. This usually means both args
1496 ;; are REAL so the result is a REAL.
1499 (defun truncate-derive-type-quot (number-type divisor-type)
1500 (let* ((rem-type (rem-result-type number-type divisor-type))
1501 (number-interval (numeric-type->interval number-type))
1502 (divisor-interval (numeric-type->interval divisor-type)))
1503 ;;(declare (type (member '(integer rational float)) rem-type))
1504 ;; We have real numbers now.
1505 (cond ((eq rem-type 'integer)
1506 ;; Since the remainder type is INTEGER, both args are
1508 (let* ((res (integer-truncate-derive-type
1509 (interval-low number-interval)
1510 (interval-high number-interval)
1511 (interval-low divisor-interval)
1512 (interval-high divisor-interval))))
1513 (specifier-type (if (listp res) res 'integer))))
1515 (let ((quot (truncate-quotient-bound
1516 (interval-div number-interval
1517 divisor-interval))))
1518 (specifier-type `(integer ,(or (interval-low quot) '*)
1519 ,(or (interval-high quot) '*))))))))
1521 (defun truncate-derive-type-rem (number-type divisor-type)
1522 (let* ((rem-type (rem-result-type number-type divisor-type))
1523 (number-interval (numeric-type->interval number-type))
1524 (divisor-interval (numeric-type->interval divisor-type))
1525 (rem (truncate-rem-bound number-interval divisor-interval)))
1526 ;;(declare (type (member '(integer rational float)) rem-type))
1527 ;; We have real numbers now.
1528 (cond ((eq rem-type 'integer)
1529 ;; Since the remainder type is INTEGER, both args are
1531 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1532 ,(or (interval-high rem) '*))))
1534 (multiple-value-bind (class format)
1537 (values 'integer nil))
1539 (values 'rational nil))
1540 ((or single-float double-float #!+long-float long-float)
1541 (values 'float rem-type))
1543 (values 'float nil))
1546 (when (member rem-type '(float single-float double-float
1547 #!+long-float long-float))
1548 (setf rem (interval-func #'(lambda (x)
1549 (coerce x rem-type))
1551 (make-numeric-type :class class
1553 :low (interval-low rem)
1554 :high (interval-high rem)))))))
1556 (defun truncate-derive-type-quot-aux (num div same-arg)
1557 (declare (ignore same-arg))
1558 (if (and (numeric-type-real-p num)
1559 (numeric-type-real-p div))
1560 (truncate-derive-type-quot num div)
1563 (defun truncate-derive-type-rem-aux (num div same-arg)
1564 (declare (ignore same-arg))
1565 (if (and (numeric-type-real-p num)
1566 (numeric-type-real-p div))
1567 (truncate-derive-type-rem num div)
1570 (defoptimizer (truncate derive-type) ((number divisor))
1571 (let ((quot (two-arg-derive-type number divisor
1572 #'truncate-derive-type-quot-aux #'truncate))
1573 (rem (two-arg-derive-type number divisor
1574 #'truncate-derive-type-rem-aux #'rem)))
1575 (when (and quot rem)
1576 (make-values-type :required (list quot rem)))))
1578 (defun ftruncate-derive-type-quot (number-type divisor-type)
1579 ;; The bounds are the same as for truncate. However, the first
1580 ;; result is a float of some type. We need to determine what that
1581 ;; type is. Basically it's the more contagious of the two types.
1582 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1583 (res-type (numeric-contagion number-type divisor-type)))
1584 (make-numeric-type :class 'float
1585 :format (numeric-type-format res-type)
1586 :low (numeric-type-low q-type)
1587 :high (numeric-type-high q-type))))
1589 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1590 (declare (ignore same-arg))
1591 (if (and (numeric-type-real-p n)
1592 (numeric-type-real-p d))
1593 (ftruncate-derive-type-quot n d)
1596 (defoptimizer (ftruncate derive-type) ((number divisor))
1598 (two-arg-derive-type number divisor
1599 #'ftruncate-derive-type-quot-aux #'ftruncate))
1600 (rem (two-arg-derive-type number divisor
1601 #'truncate-derive-type-rem-aux #'rem)))
1602 (when (and quot rem)
1603 (make-values-type :required (list quot rem)))))
1605 (defun %unary-truncate-derive-type-aux (number)
1606 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1608 (defoptimizer (%unary-truncate derive-type) ((number))
1609 (one-arg-derive-type number
1610 #'%unary-truncate-derive-type-aux
1613 ;;; Define optimizers for FLOOR and CEILING.
1615 ((def (name q-name r-name)
1616 (let ((q-aux (symbolicate q-name "-AUX"))
1617 (r-aux (symbolicate r-name "-AUX")))
1619 ;; Compute type of quotient (first) result.
1620 (defun ,q-aux (number-type divisor-type)
1621 (let* ((number-interval
1622 (numeric-type->interval number-type))
1624 (numeric-type->interval divisor-type))
1625 (quot (,q-name (interval-div number-interval
1626 divisor-interval))))
1627 (specifier-type `(integer ,(or (interval-low quot) '*)
1628 ,(or (interval-high quot) '*)))))
1629 ;; Compute type of remainder.
1630 (defun ,r-aux (number-type divisor-type)
1631 (let* ((divisor-interval
1632 (numeric-type->interval divisor-type))
1633 (rem (,r-name divisor-interval))
1634 (result-type (rem-result-type number-type divisor-type)))
1635 (multiple-value-bind (class format)
1638 (values 'integer nil))
1640 (values 'rational nil))
1641 ((or single-float double-float #!+long-float long-float)
1642 (values 'float result-type))
1644 (values 'float nil))
1647 (when (member result-type '(float single-float double-float
1648 #!+long-float long-float))
1649 ;; Make sure that the limits on the interval have
1651 (setf rem (interval-func (lambda (x)
1652 (coerce x result-type))
1654 (make-numeric-type :class class
1656 :low (interval-low rem)
1657 :high (interval-high rem)))))
1658 ;; the optimizer itself
1659 (defoptimizer (,name derive-type) ((number divisor))
1660 (flet ((derive-q (n d same-arg)
1661 (declare (ignore same-arg))
1662 (if (and (numeric-type-real-p n)
1663 (numeric-type-real-p d))
1666 (derive-r (n d same-arg)
1667 (declare (ignore same-arg))
1668 (if (and (numeric-type-real-p n)
1669 (numeric-type-real-p d))
1672 (let ((quot (two-arg-derive-type
1673 number divisor #'derive-q #',name))
1674 (rem (two-arg-derive-type
1675 number divisor #'derive-r #'mod)))
1676 (when (and quot rem)
1677 (make-values-type :required (list quot rem))))))))))
1679 (def floor floor-quotient-bound floor-rem-bound)
1680 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1682 ;;; Define optimizers for FFLOOR and FCEILING
1683 (macrolet ((def (name q-name r-name)
1684 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1685 (r-aux (symbolicate r-name "-AUX")))
1687 ;; Compute type of quotient (first) result.
1688 (defun ,q-aux (number-type divisor-type)
1689 (let* ((number-interval
1690 (numeric-type->interval number-type))
1692 (numeric-type->interval divisor-type))
1693 (quot (,q-name (interval-div number-interval
1695 (res-type (numeric-contagion number-type
1698 :class (numeric-type-class res-type)
1699 :format (numeric-type-format res-type)
1700 :low (interval-low quot)
1701 :high (interval-high quot))))
1703 (defoptimizer (,name derive-type) ((number divisor))
1704 (flet ((derive-q (n d same-arg)
1705 (declare (ignore same-arg))
1706 (if (and (numeric-type-real-p n)
1707 (numeric-type-real-p d))
1710 (derive-r (n d same-arg)
1711 (declare (ignore same-arg))
1712 (if (and (numeric-type-real-p n)
1713 (numeric-type-real-p d))
1716 (let ((quot (two-arg-derive-type
1717 number divisor #'derive-q #',name))
1718 (rem (two-arg-derive-type
1719 number divisor #'derive-r #'mod)))
1720 (when (and quot rem)
1721 (make-values-type :required (list quot rem))))))))))
1723 (def ffloor floor-quotient-bound floor-rem-bound)
1724 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1726 ;;; functions to compute the bounds on the quotient and remainder for
1727 ;;; the FLOOR function
1728 (defun floor-quotient-bound (quot)
1729 ;; Take the floor of the quotient and then massage it into what we
1731 (let ((lo (interval-low quot))
1732 (hi (interval-high quot)))
1733 ;; Take the floor of the lower bound. The result is always a
1734 ;; closed lower bound.
1736 (floor (type-bound-number lo))
1738 ;; For the upper bound, we need to be careful.
1741 ;; An open bound. We need to be careful here because
1742 ;; the floor of '(10.0) is 9, but the floor of
1744 (multiple-value-bind (q r) (floor (first hi))
1749 ;; A closed bound, so the answer is obvious.
1753 (make-interval :low lo :high hi)))
1754 (defun floor-rem-bound (div)
1755 ;; The remainder depends only on the divisor. Try to get the
1756 ;; correct sign for the remainder if we can.
1757 (case (interval-range-info div)
1759 ;; The divisor is always positive.
1760 (let ((rem (interval-abs div)))
1761 (setf (interval-low rem) 0)
1762 (when (and (numberp (interval-high rem))
1763 (not (zerop (interval-high rem))))
1764 ;; The remainder never contains the upper bound. However,
1765 ;; watch out for the case where the high limit is zero!
1766 (setf (interval-high rem) (list (interval-high rem))))
1769 ;; The divisor is always negative.
1770 (let ((rem (interval-neg (interval-abs div))))
1771 (setf (interval-high rem) 0)
1772 (when (numberp (interval-low rem))
1773 ;; The remainder never contains the lower bound.
1774 (setf (interval-low rem) (list (interval-low rem))))
1777 ;; The divisor can be positive or negative. All bets off. The
1778 ;; magnitude of remainder is the maximum value of the divisor.
1779 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1780 ;; The bound never reaches the limit, so make the interval open.
1781 (make-interval :low (if limit
1784 :high (list limit))))))
1786 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
1787 => #S(INTERVAL :LOW 0 :HIGH 10)
1788 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1789 => #S(INTERVAL :LOW 0 :HIGH 10)
1790 (floor-quotient-bound (make-interval :low 0.3 :high 10))
1791 => #S(INTERVAL :LOW 0 :HIGH 10)
1792 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
1793 => #S(INTERVAL :LOW 0 :HIGH 9)
1794 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
1795 => #S(INTERVAL :LOW 0 :HIGH 10)
1796 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
1797 => #S(INTERVAL :LOW 0 :HIGH 10)
1798 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1799 => #S(INTERVAL :LOW -2 :HIGH 10)
1800 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1801 => #S(INTERVAL :LOW -1 :HIGH 10)
1802 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
1803 => #S(INTERVAL :LOW -1 :HIGH 10)
1805 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
1806 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1807 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
1808 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1809 (floor-rem-bound (make-interval :low -10 :high -2.3))
1810 #S(INTERVAL :LOW (-10) :HIGH 0)
1811 (floor-rem-bound (make-interval :low 0.3 :high 10))
1812 => #S(INTERVAL :LOW 0 :HIGH '(10))
1813 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
1814 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
1815 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
1816 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1819 ;;; same functions for CEILING
1820 (defun ceiling-quotient-bound (quot)
1821 ;; Take the ceiling of the quotient and then massage it into what we
1823 (let ((lo (interval-low quot))
1824 (hi (interval-high quot)))
1825 ;; Take the ceiling of the upper bound. The result is always a
1826 ;; closed upper bound.
1828 (ceiling (type-bound-number hi))
1830 ;; For the lower bound, we need to be careful.
1833 ;; An open bound. We need to be careful here because
1834 ;; the ceiling of '(10.0) is 11, but the ceiling of
1836 (multiple-value-bind (q r) (ceiling (first lo))
1841 ;; A closed bound, so the answer is obvious.
1845 (make-interval :low lo :high hi)))
1846 (defun ceiling-rem-bound (div)
1847 ;; The remainder depends only on the divisor. Try to get the
1848 ;; correct sign for the remainder if we can.
1849 (case (interval-range-info div)
1851 ;; Divisor is always positive. The remainder is negative.
1852 (let ((rem (interval-neg (interval-abs div))))
1853 (setf (interval-high rem) 0)
1854 (when (and (numberp (interval-low rem))
1855 (not (zerop (interval-low rem))))
1856 ;; The remainder never contains the upper bound. However,
1857 ;; watch out for the case when the upper bound is zero!
1858 (setf (interval-low rem) (list (interval-low rem))))
1861 ;; Divisor is always negative. The remainder is positive
1862 (let ((rem (interval-abs div)))
1863 (setf (interval-low rem) 0)
1864 (when (numberp (interval-high rem))
1865 ;; The remainder never contains the lower bound.
1866 (setf (interval-high rem) (list (interval-high rem))))
1869 ;; The divisor can be positive or negative. All bets off. The
1870 ;; magnitude of remainder is the maximum value of the divisor.
1871 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1872 ;; The bound never reaches the limit, so make the interval open.
1873 (make-interval :low (if limit
1876 :high (list limit))))))
1879 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
1880 => #S(INTERVAL :LOW 1 :HIGH 11)
1881 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1882 => #S(INTERVAL :LOW 1 :HIGH 11)
1883 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
1884 => #S(INTERVAL :LOW 1 :HIGH 10)
1885 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
1886 => #S(INTERVAL :LOW 1 :HIGH 10)
1887 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
1888 => #S(INTERVAL :LOW 1 :HIGH 11)
1889 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
1890 => #S(INTERVAL :LOW 1 :HIGH 11)
1891 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1892 => #S(INTERVAL :LOW -1 :HIGH 11)
1893 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1894 => #S(INTERVAL :LOW 0 :HIGH 11)
1895 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
1896 => #S(INTERVAL :LOW -1 :HIGH 11)
1898 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
1899 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
1900 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
1901 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1902 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
1903 => #S(INTERVAL :LOW 0 :HIGH (10))
1904 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
1905 => #S(INTERVAL :LOW (-10) :HIGH 0)
1906 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
1907 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
1908 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
1909 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1912 (defun truncate-quotient-bound (quot)
1913 ;; For positive quotients, truncate is exactly like floor. For
1914 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
1915 ;; it's the union of the two pieces.
1916 (case (interval-range-info quot)
1919 (floor-quotient-bound quot))
1921 ;; just like CEILING
1922 (ceiling-quotient-bound quot))
1924 ;; Split the interval into positive and negative pieces, compute
1925 ;; the result for each piece and put them back together.
1926 (destructuring-bind (neg pos) (interval-split 0 quot t t)
1927 (interval-merge-pair (ceiling-quotient-bound neg)
1928 (floor-quotient-bound pos))))))
1930 (defun truncate-rem-bound (num div)
1931 ;; This is significantly more complicated than FLOOR or CEILING. We
1932 ;; need both the number and the divisor to determine the range. The
1933 ;; basic idea is to split the ranges of NUM and DEN into positive
1934 ;; and negative pieces and deal with each of the four possibilities
1936 (case (interval-range-info num)
1938 (case (interval-range-info div)
1940 (floor-rem-bound div))
1942 (ceiling-rem-bound div))
1944 (destructuring-bind (neg pos) (interval-split 0 div t t)
1945 (interval-merge-pair (truncate-rem-bound num neg)
1946 (truncate-rem-bound num pos))))))
1948 (case (interval-range-info div)
1950 (ceiling-rem-bound div))
1952 (floor-rem-bound div))
1954 (destructuring-bind (neg pos) (interval-split 0 div t t)
1955 (interval-merge-pair (truncate-rem-bound num neg)
1956 (truncate-rem-bound num pos))))))
1958 (destructuring-bind (neg pos) (interval-split 0 num t t)
1959 (interval-merge-pair (truncate-rem-bound neg div)
1960 (truncate-rem-bound pos div))))))
1963 ;;; Derive useful information about the range. Returns three values:
1964 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
1965 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
1966 ;;; - The abs of the maximal value if there is one, or nil if it is
1968 (defun numeric-range-info (low high)
1969 (cond ((and low (not (minusp low)))
1970 (values '+ low high))
1971 ((and high (not (plusp high)))
1972 (values '- (- high) (if low (- low) nil)))
1974 (values nil 0 (and low high (max (- low) high))))))
1976 (defun integer-truncate-derive-type
1977 (number-low number-high divisor-low divisor-high)
1978 ;; The result cannot be larger in magnitude than the number, but the
1979 ;; sign might change. If we can determine the sign of either the
1980 ;; number or the divisor, we can eliminate some of the cases.
1981 (multiple-value-bind (number-sign number-min number-max)
1982 (numeric-range-info number-low number-high)
1983 (multiple-value-bind (divisor-sign divisor-min divisor-max)
1984 (numeric-range-info divisor-low divisor-high)
1985 (when (and divisor-max (zerop divisor-max))
1986 ;; We've got a problem: guaranteed division by zero.
1987 (return-from integer-truncate-derive-type t))
1988 (when (zerop divisor-min)
1989 ;; We'll assume that they aren't going to divide by zero.
1991 (cond ((and number-sign divisor-sign)
1992 ;; We know the sign of both.
1993 (if (eq number-sign divisor-sign)
1994 ;; Same sign, so the result will be positive.
1995 `(integer ,(if divisor-max
1996 (truncate number-min divisor-max)
1999 (truncate number-max divisor-min)
2001 ;; Different signs, the result will be negative.
2002 `(integer ,(if number-max
2003 (- (truncate number-max divisor-min))
2006 (- (truncate number-min divisor-max))
2008 ((eq divisor-sign '+)
2009 ;; The divisor is positive. Therefore, the number will just
2010 ;; become closer to zero.
2011 `(integer ,(if number-low
2012 (truncate number-low divisor-min)
2015 (truncate number-high divisor-min)
2017 ((eq divisor-sign '-)
2018 ;; The divisor is negative. Therefore, the absolute value of
2019 ;; the number will become closer to zero, but the sign will also
2021 `(integer ,(if number-high
2022 (- (truncate number-high divisor-min))
2025 (- (truncate number-low divisor-min))
2027 ;; The divisor could be either positive or negative.
2029 ;; The number we are dividing has a bound. Divide that by the
2030 ;; smallest posible divisor.
2031 (let ((bound (truncate number-max divisor-min)))
2032 `(integer ,(- bound) ,bound)))
2034 ;; The number we are dividing is unbounded, so we can't tell
2035 ;; anything about the result.
2038 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2039 (defun integer-rem-derive-type
2040 (number-low number-high divisor-low divisor-high)
2041 (if (and divisor-low divisor-high)
2042 ;; We know the range of the divisor, and the remainder must be
2043 ;; smaller than the divisor. We can tell the sign of the
2044 ;; remainer if we know the sign of the number.
2045 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2046 `(integer ,(if (or (null number-low)
2047 (minusp number-low))
2050 ,(if (or (null number-high)
2051 (plusp number-high))
2054 ;; The divisor is potentially either very positive or very
2055 ;; negative. Therefore, the remainer is unbounded, but we might
2056 ;; be able to tell something about the sign from the number.
2057 `(integer ,(if (and number-low (not (minusp number-low)))
2058 ;; The number we are dividing is positive.
2059 ;; Therefore, the remainder must be positive.
2062 ,(if (and number-high (not (plusp number-high)))
2063 ;; The number we are dividing is negative.
2064 ;; Therefore, the remainder must be negative.
2068 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2069 (defoptimizer (random derive-type) ((bound &optional state))
2070 (let ((type (continuation-type bound)))
2071 (when (numeric-type-p type)
2072 (let ((class (numeric-type-class type))
2073 (high (numeric-type-high type))
2074 (format (numeric-type-format type)))
2078 :low (coerce 0 (or format class 'real))
2079 :high (cond ((not high) nil)
2080 ((eq class 'integer) (max (1- high) 0))
2081 ((or (consp high) (zerop high)) high)
2084 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2085 (defun random-derive-type-aux (type)
2086 (let ((class (numeric-type-class type))
2087 (high (numeric-type-high type))
2088 (format (numeric-type-format type)))
2092 :low (coerce 0 (or format class 'real))
2093 :high (cond ((not high) nil)
2094 ((eq class 'integer) (max (1- high) 0))
2095 ((or (consp high) (zerop high)) high)
2098 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2099 (defoptimizer (random derive-type) ((bound &optional state))
2100 (one-arg-derive-type bound #'random-derive-type-aux nil))
2102 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2104 ;;; Return the maximum number of bits an integer of the supplied type
2105 ;;; can take up, or NIL if it is unbounded. The second (third) value
2106 ;;; is T if the integer can be positive (negative) and NIL if not.
2107 ;;; Zero counts as positive.
2108 (defun integer-type-length (type)
2109 (if (numeric-type-p type)
2110 (let ((min (numeric-type-low type))
2111 (max (numeric-type-high type)))
2112 (values (and min max (max (integer-length min) (integer-length max)))
2113 (or (null max) (not (minusp max)))
2114 (or (null min) (minusp min))))
2117 (defun logand-derive-type-aux (x y &optional same-leaf)
2118 (declare (ignore same-leaf))
2119 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2120 (declare (ignore x-pos))
2121 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2122 (declare (ignore y-pos))
2124 ;; X must be positive.
2126 ;; They must both be positive.
2127 (cond ((or (null x-len) (null y-len))
2128 (specifier-type 'unsigned-byte))
2129 ((or (zerop x-len) (zerop y-len))
2130 (specifier-type '(integer 0 0)))
2132 (specifier-type `(unsigned-byte ,(min x-len y-len)))))
2133 ;; X is positive, but Y might be negative.
2135 (specifier-type 'unsigned-byte))
2137 (specifier-type '(integer 0 0)))
2139 (specifier-type `(unsigned-byte ,x-len)))))
2140 ;; X might be negative.
2142 ;; Y must be positive.
2144 (specifier-type 'unsigned-byte))
2146 (specifier-type '(integer 0 0)))
2149 `(unsigned-byte ,y-len))))
2150 ;; Either might be negative.
2151 (if (and x-len y-len)
2152 ;; The result is bounded.
2153 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2154 ;; We can't tell squat about the result.
2155 (specifier-type 'integer)))))))
2157 (defun logior-derive-type-aux (x y &optional same-leaf)
2158 (declare (ignore same-leaf))
2159 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2160 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2162 ((and (not x-neg) (not y-neg))
2163 ;; Both are positive.
2164 (if (and x-len y-len (zerop x-len) (zerop y-len))
2165 (specifier-type '(integer 0 0))
2166 (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2170 ;; X must be negative.
2172 ;; Both are negative. The result is going to be negative
2173 ;; and be the same length or shorter than the smaller.
2174 (if (and x-len y-len)
2176 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2178 (specifier-type '(integer * -1)))
2179 ;; X is negative, but we don't know about Y. The result
2180 ;; will be negative, but no more negative than X.
2182 `(integer ,(or (numeric-type-low x) '*)
2185 ;; X might be either positive or negative.
2187 ;; But Y is negative. The result will be negative.
2189 `(integer ,(or (numeric-type-low y) '*)
2191 ;; We don't know squat about either. It won't get any bigger.
2192 (if (and x-len y-len)
2194 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2196 (specifier-type 'integer))))))))
2198 (defun logxor-derive-type-aux (x y &optional same-leaf)
2199 (declare (ignore same-leaf))
2200 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2201 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2203 ((or (and (not x-neg) (not y-neg))
2204 (and (not x-pos) (not y-pos)))
2205 ;; Either both are negative or both are positive. The result
2206 ;; will be positive, and as long as the longer.
2207 (if (and x-len y-len (zerop x-len) (zerop y-len))
2208 (specifier-type '(integer 0 0))
2209 (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2212 ((or (and (not x-pos) (not y-neg))
2213 (and (not y-neg) (not y-pos)))
2214 ;; Either X is negative and Y is positive of vice-versa. The
2215 ;; result will be negative.
2216 (specifier-type `(integer ,(if (and x-len y-len)
2217 (ash -1 (max x-len y-len))
2220 ;; We can't tell what the sign of the result is going to be.
2221 ;; All we know is that we don't create new bits.
2223 (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2225 (specifier-type 'integer))))))
2227 (macrolet ((deffrob (logfcn)
2228 (let ((fcn-aux (symbolicate logfcn "-DERIVE-TYPE-AUX")))
2229 `(defoptimizer (,logfcn derive-type) ((x y))
2230 (two-arg-derive-type x y #',fcn-aux #',logfcn)))))
2235 ;;;; miscellaneous derive-type methods
2237 (defoptimizer (integer-length derive-type) ((x))
2238 (let ((x-type (continuation-type x)))
2239 (when (and (numeric-type-p x-type)
2240 (csubtypep x-type (specifier-type 'integer)))
2241 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2242 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2243 ;; careful about LO or HI being NIL, though. Also, if 0 is
2244 ;; contained in X, the lower bound is obviously 0.
2245 (flet ((null-or-min (a b)
2246 (and a b (min (integer-length a)
2247 (integer-length b))))
2249 (and a b (max (integer-length a)
2250 (integer-length b)))))
2251 (let* ((min (numeric-type-low x-type))
2252 (max (numeric-type-high x-type))
2253 (min-len (null-or-min min max))
2254 (max-len (null-or-max min max)))
2255 (when (ctypep 0 x-type)
2257 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2259 (defoptimizer (code-char derive-type) ((code))
2260 (specifier-type 'base-char))
2262 (defoptimizer (values derive-type) ((&rest values))
2263 (values-specifier-type
2264 `(values ,@(mapcar (lambda (x)
2265 (type-specifier (continuation-type x)))
2268 ;;;; byte operations
2270 ;;;; We try to turn byte operations into simple logical operations.
2271 ;;;; First, we convert byte specifiers into separate size and position
2272 ;;;; arguments passed to internal %FOO functions. We then attempt to
2273 ;;;; transform the %FOO functions into boolean operations when the
2274 ;;;; size and position are constant and the operands are fixnums.
2276 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2277 ;; expressions that evaluate to the SIZE and POSITION of
2278 ;; the byte-specifier form SPEC. We may wrap a let around
2279 ;; the result of the body to bind some variables.
2281 ;; If the spec is a BYTE form, then bind the vars to the
2282 ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2283 ;; and BYTE-POSITION. The goal of this transformation is to
2284 ;; avoid consing up byte specifiers and then immediately
2285 ;; throwing them away.
2286 (with-byte-specifier ((size-var pos-var spec) &body body)
2287 (once-only ((spec `(macroexpand ,spec))
2289 `(if (and (consp ,spec)
2290 (eq (car ,spec) 'byte)
2291 (= (length ,spec) 3))
2292 (let ((,size-var (second ,spec))
2293 (,pos-var (third ,spec)))
2295 (let ((,size-var `(byte-size ,,temp))
2296 (,pos-var `(byte-position ,,temp)))
2297 `(let ((,,temp ,,spec))
2300 (define-source-transform ldb (spec int)
2301 (with-byte-specifier (size pos spec)
2302 `(%ldb ,size ,pos ,int)))
2304 (define-source-transform dpb (newbyte spec int)
2305 (with-byte-specifier (size pos spec)
2306 `(%dpb ,newbyte ,size ,pos ,int)))
2308 (define-source-transform mask-field (spec int)
2309 (with-byte-specifier (size pos spec)
2310 `(%mask-field ,size ,pos ,int)))
2312 (define-source-transform deposit-field (newbyte spec int)
2313 (with-byte-specifier (size pos spec)
2314 `(%deposit-field ,newbyte ,size ,pos ,int))))
2316 (defoptimizer (%ldb derive-type) ((size posn num))
2317 (let ((size (continuation-type size)))
2318 (if (and (numeric-type-p size)
2319 (csubtypep size (specifier-type 'integer)))
2320 (let ((size-high (numeric-type-high size)))
2321 (if (and size-high (<= size-high sb!vm:n-word-bits))
2322 (specifier-type `(unsigned-byte ,size-high))
2323 (specifier-type 'unsigned-byte)))
2326 (defoptimizer (%mask-field derive-type) ((size posn num))
2327 (let ((size (continuation-type size))
2328 (posn (continuation-type posn)))
2329 (if (and (numeric-type-p size)
2330 (csubtypep size (specifier-type 'integer))
2331 (numeric-type-p posn)
2332 (csubtypep posn (specifier-type 'integer)))
2333 (let ((size-high (numeric-type-high size))
2334 (posn-high (numeric-type-high posn)))
2335 (if (and size-high posn-high
2336 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2337 (specifier-type `(unsigned-byte ,(+ size-high posn-high)))
2338 (specifier-type 'unsigned-byte)))
2341 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2342 (let ((size (continuation-type size))
2343 (posn (continuation-type posn))
2344 (int (continuation-type int)))
2345 (if (and (numeric-type-p size)
2346 (csubtypep size (specifier-type 'integer))
2347 (numeric-type-p posn)
2348 (csubtypep posn (specifier-type 'integer))
2349 (numeric-type-p int)
2350 (csubtypep int (specifier-type 'integer)))
2351 (let ((size-high (numeric-type-high size))
2352 (posn-high (numeric-type-high posn))
2353 (high (numeric-type-high int))
2354 (low (numeric-type-low int)))
2355 (if (and size-high posn-high high low
2356 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2358 (list (if (minusp low) 'signed-byte 'unsigned-byte)
2359 (max (integer-length high)
2360 (integer-length low)
2361 (+ size-high posn-high))))
2365 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2366 (let ((size (continuation-type size))
2367 (posn (continuation-type posn))
2368 (int (continuation-type int)))
2369 (if (and (numeric-type-p size)
2370 (csubtypep size (specifier-type 'integer))
2371 (numeric-type-p posn)
2372 (csubtypep posn (specifier-type 'integer))
2373 (numeric-type-p int)
2374 (csubtypep int (specifier-type 'integer)))
2375 (let ((size-high (numeric-type-high size))
2376 (posn-high (numeric-type-high posn))
2377 (high (numeric-type-high int))
2378 (low (numeric-type-low int)))
2379 (if (and size-high posn-high high low
2380 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2382 (list (if (minusp low) 'signed-byte 'unsigned-byte)
2383 (max (integer-length high)
2384 (integer-length low)
2385 (+ size-high posn-high))))
2389 (deftransform %ldb ((size posn int)
2390 (fixnum fixnum integer)
2391 (unsigned-byte #.sb!vm:n-word-bits))
2392 "convert to inline logical operations"
2393 `(logand (ash int (- posn))
2394 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2395 (- size ,sb!vm:n-word-bits))))
2397 (deftransform %mask-field ((size posn int)
2398 (fixnum fixnum integer)
2399 (unsigned-byte #.sb!vm:n-word-bits))
2400 "convert to inline logical operations"
2402 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2403 (- size ,sb!vm:n-word-bits))
2406 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2407 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2408 ;;; as the result type, as that would allow result types that cover
2409 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2410 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2412 (deftransform %dpb ((new size posn int)
2414 (unsigned-byte #.sb!vm:n-word-bits))
2415 "convert to inline logical operations"
2416 `(let ((mask (ldb (byte size 0) -1)))
2417 (logior (ash (logand new mask) posn)
2418 (logand int (lognot (ash mask posn))))))
2420 (deftransform %dpb ((new size posn int)
2422 (signed-byte #.sb!vm:n-word-bits))
2423 "convert to inline logical operations"
2424 `(let ((mask (ldb (byte size 0) -1)))
2425 (logior (ash (logand new mask) posn)
2426 (logand int (lognot (ash mask posn))))))
2428 (deftransform %deposit-field ((new size posn int)
2430 (unsigned-byte #.sb!vm:n-word-bits))
2431 "convert to inline logical operations"
2432 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2433 (logior (logand new mask)
2434 (logand int (lognot mask)))))
2436 (deftransform %deposit-field ((new size posn int)
2438 (signed-byte #.sb!vm:n-word-bits))
2439 "convert to inline logical operations"
2440 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2441 (logior (logand new mask)
2442 (logand int (lognot mask)))))
2444 ;;; miscellanous numeric transforms
2446 ;;; If a constant appears as the first arg, swap the args.
2447 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
2448 (if (and (constant-continuation-p x)
2449 (not (constant-continuation-p y)))
2450 `(,(continuation-fun-name (basic-combination-fun node))
2452 ,(continuation-value x))
2453 (give-up-ir1-transform)))
2455 (dolist (x '(= char= + * logior logand logxor))
2456 (%deftransform x '(function * *) #'commutative-arg-swap
2457 "place constant arg last"))
2459 ;;; Handle the case of a constant BOOLE-CODE.
2460 (deftransform boole ((op x y) * *)
2461 "convert to inline logical operations"
2462 (unless (constant-continuation-p op)
2463 (give-up-ir1-transform "BOOLE code is not a constant."))
2464 (let ((control (continuation-value op)))
2470 (#.boole-c1 '(lognot x))
2471 (#.boole-c2 '(lognot y))
2472 (#.boole-and '(logand x y))
2473 (#.boole-ior '(logior x y))
2474 (#.boole-xor '(logxor x y))
2475 (#.boole-eqv '(logeqv x y))
2476 (#.boole-nand '(lognand x y))
2477 (#.boole-nor '(lognor x y))
2478 (#.boole-andc1 '(logandc1 x y))
2479 (#.boole-andc2 '(logandc2 x y))
2480 (#.boole-orc1 '(logorc1 x y))
2481 (#.boole-orc2 '(logorc2 x y))
2483 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
2486 ;;;; converting special case multiply/divide to shifts
2488 ;;; If arg is a constant power of two, turn * into a shift.
2489 (deftransform * ((x y) (integer integer) *)
2490 "convert x*2^k to shift"
2491 (unless (constant-continuation-p y)
2492 (give-up-ir1-transform))
2493 (let* ((y (continuation-value y))
2495 (len (1- (integer-length y-abs))))
2496 (unless (= y-abs (ash 1 len))
2497 (give-up-ir1-transform))
2502 ;;; If both arguments and the result are (UNSIGNED-BYTE 32), try to
2503 ;;; come up with a ``better'' multiplication using multiplier
2504 ;;; recoding. There are two different ways the multiplier can be
2505 ;;; recoded. The more obvious is to shift X by the correct amount for
2506 ;;; each bit set in Y and to sum the results. But if there is a string
2507 ;;; of bits that are all set, you can add X shifted by one more then
2508 ;;; the bit position of the first set bit and subtract X shifted by
2509 ;;; the bit position of the last set bit. We can't use this second
2510 ;;; method when the high order bit is bit 31 because shifting by 32
2511 ;;; doesn't work too well.
2512 (deftransform * ((x y)
2513 ((unsigned-byte 32) (unsigned-byte 32))
2515 "recode as shift and add"
2516 (unless (constant-continuation-p y)
2517 (give-up-ir1-transform))
2518 (let ((y (continuation-value y))
2521 (labels ((tub32 (x) `(truly-the (unsigned-byte 32) ,x))
2526 `(+ ,result ,(tub32 next-factor))
2528 (declare (inline add))
2529 (dotimes (bitpos 32)
2531 (when (not (logbitp bitpos y))
2532 (add (if (= (1+ first-one) bitpos)
2533 ;; There is only a single bit in the string.
2535 ;; There are at least two.
2536 `(- ,(tub32 `(ash x ,bitpos))
2537 ,(tub32 `(ash x ,first-one)))))
2538 (setf first-one nil))
2539 (when (logbitp bitpos y)
2540 (setf first-one bitpos))))
2542 (cond ((= first-one 31))
2546 (add `(- ,(tub32 '(ash x 31)) ,(tub32 `(ash x ,first-one))))))
2550 ;;; If arg is a constant power of two, turn FLOOR into a shift and
2551 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
2553 (flet ((frob (y ceil-p)
2554 (unless (constant-continuation-p y)
2555 (give-up-ir1-transform))
2556 (let* ((y (continuation-value y))
2558 (len (1- (integer-length y-abs))))
2559 (unless (= y-abs (ash 1 len))
2560 (give-up-ir1-transform))
2561 (let ((shift (- len))
2563 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
2564 `(let ((x (+ x ,delta)))
2566 `(values (ash (- x) ,shift)
2567 (- (- (logand (- x) ,mask)) ,delta))
2568 `(values (ash x ,shift)
2569 (- (logand x ,mask) ,delta))))))))
2570 (deftransform floor ((x y) (integer integer) *)
2571 "convert division by 2^k to shift"
2573 (deftransform ceiling ((x y) (integer integer) *)
2574 "convert division by 2^k to shift"
2577 ;;; Do the same for MOD.
2578 (deftransform mod ((x y) (integer integer) *)
2579 "convert remainder mod 2^k to LOGAND"
2580 (unless (constant-continuation-p y)
2581 (give-up-ir1-transform))
2582 (let* ((y (continuation-value y))
2584 (len (1- (integer-length y-abs))))
2585 (unless (= y-abs (ash 1 len))
2586 (give-up-ir1-transform))
2587 (let ((mask (1- y-abs)))
2589 `(- (logand (- x) ,mask))
2590 `(logand x ,mask)))))
2592 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
2593 (deftransform truncate ((x y) (integer integer))
2594 "convert division by 2^k to shift"
2595 (unless (constant-continuation-p y)
2596 (give-up-ir1-transform))
2597 (let* ((y (continuation-value y))
2599 (len (1- (integer-length y-abs))))
2600 (unless (= y-abs (ash 1 len))
2601 (give-up-ir1-transform))
2602 (let* ((shift (- len))
2605 (values ,(if (minusp y)
2607 `(- (ash (- x) ,shift)))
2608 (- (logand (- x) ,mask)))
2609 (values ,(if (minusp y)
2610 `(- (ash (- x) ,shift))
2612 (logand x ,mask))))))
2614 ;;; And the same for REM.
2615 (deftransform rem ((x y) (integer integer) *)
2616 "convert remainder mod 2^k to LOGAND"
2617 (unless (constant-continuation-p y)
2618 (give-up-ir1-transform))
2619 (let* ((y (continuation-value y))
2621 (len (1- (integer-length y-abs))))
2622 (unless (= y-abs (ash 1 len))
2623 (give-up-ir1-transform))
2624 (let ((mask (1- y-abs)))
2626 (- (logand (- x) ,mask))
2627 (logand x ,mask)))))
2629 ;;;; arithmetic and logical identity operation elimination
2631 ;;; Flush calls to various arith functions that convert to the
2632 ;;; identity function or a constant.
2633 (macrolet ((def (name identity result)
2634 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
2635 "fold identity operations"
2642 (def logxor -1 (lognot x))
2645 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
2646 ;;; (* 0 -4.0) is -0.0.
2647 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
2648 "convert (- 0 x) to negate"
2650 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
2651 "convert (* x 0) to 0"
2654 ;;; Return T if in an arithmetic op including continuations X and Y,
2655 ;;; the result type is not affected by the type of X. That is, Y is at
2656 ;;; least as contagious as X.
2658 (defun not-more-contagious (x y)
2659 (declare (type continuation x y))
2660 (let ((x (continuation-type x))
2661 (y (continuation-type y)))
2662 (values (type= (numeric-contagion x y)
2663 (numeric-contagion y y)))))
2664 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
2665 ;;; XXX needs more work as valid transforms are missed; some cases are
2666 ;;; specific to particular transform functions so the use of this
2667 ;;; function may need a re-think.
2668 (defun not-more-contagious (x y)
2669 (declare (type continuation x y))
2670 (flet ((simple-numeric-type (num)
2671 (and (numeric-type-p num)
2672 ;; Return non-NIL if NUM is integer, rational, or a float
2673 ;; of some type (but not FLOAT)
2674 (case (numeric-type-class num)
2678 (numeric-type-format num))
2681 (let ((x (continuation-type x))
2682 (y (continuation-type y)))
2683 (if (and (simple-numeric-type x)
2684 (simple-numeric-type y))
2685 (values (type= (numeric-contagion x y)
2686 (numeric-contagion y y)))))))
2690 ;;; If y is not constant, not zerop, or is contagious, or a positive
2691 ;;; float +0.0 then give up.
2692 (deftransform + ((x y) (t (constant-arg t)) *)
2694 (let ((val (continuation-value y)))
2695 (unless (and (zerop val)
2696 (not (and (floatp val) (plusp (float-sign val))))
2697 (not-more-contagious y x))
2698 (give-up-ir1-transform)))
2703 ;;; If y is not constant, not zerop, or is contagious, or a negative
2704 ;;; float -0.0 then give up.
2705 (deftransform - ((x y) (t (constant-arg t)) *)
2707 (let ((val (continuation-value y)))
2708 (unless (and (zerop val)
2709 (not (and (floatp val) (minusp (float-sign val))))
2710 (not-more-contagious y x))
2711 (give-up-ir1-transform)))
2714 ;;; Fold (OP x +/-1)
2715 (macrolet ((def (name result minus-result)
2716 `(deftransform ,name ((x y) (t (constant-arg real)) *)
2717 "fold identity operations"
2718 (let ((val (continuation-value y)))
2719 (unless (and (= (abs val) 1)
2720 (not-more-contagious y x))
2721 (give-up-ir1-transform))
2722 (if (minusp val) ',minus-result ',result)))))
2723 (def * x (%negate x))
2724 (def / x (%negate x))
2725 (def expt x (/ 1 x)))
2727 ;;; Fold (expt x n) into multiplications for small integral values of
2728 ;;; N; convert (expt x 1/2) to sqrt.
2729 (deftransform expt ((x y) (t (constant-arg real)) *)
2730 "recode as multiplication or sqrt"
2731 (let ((val (continuation-value y)))
2732 ;; If Y would cause the result to be promoted to the same type as
2733 ;; Y, we give up. If not, then the result will be the same type
2734 ;; as X, so we can replace the exponentiation with simple
2735 ;; multiplication and division for small integral powers.
2736 (unless (not-more-contagious y x)
2737 (give-up-ir1-transform))
2738 (cond ((zerop val) '(float 1 x))
2739 ((= val 2) '(* x x))
2740 ((= val -2) '(/ (* x x)))
2741 ((= val 3) '(* x x x))
2742 ((= val -3) '(/ (* x x x)))
2743 ((= val 1/2) '(sqrt x))
2744 ((= val -1/2) '(/ (sqrt x)))
2745 (t (give-up-ir1-transform)))))
2747 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
2748 ;;; transformations?
2749 ;;; Perhaps we should have to prove that the denominator is nonzero before
2750 ;;; doing them? -- WHN 19990917
2751 (macrolet ((def (name)
2752 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2759 (macrolet ((def (name)
2760 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2769 ;;;; character operations
2771 (deftransform char-equal ((a b) (base-char base-char))
2773 '(let* ((ac (char-code a))
2775 (sum (logxor ac bc)))
2777 (when (eql sum #x20)
2778 (let ((sum (+ ac bc)))
2779 (and (> sum 161) (< sum 213)))))))
2781 (deftransform char-upcase ((x) (base-char))
2783 '(let ((n-code (char-code x)))
2784 (if (and (> n-code #o140) ; Octal 141 is #\a.
2785 (< n-code #o173)) ; Octal 172 is #\z.
2786 (code-char (logxor #x20 n-code))
2789 (deftransform char-downcase ((x) (base-char))
2791 '(let ((n-code (char-code x)))
2792 (if (and (> n-code 64) ; 65 is #\A.
2793 (< n-code 91)) ; 90 is #\Z.
2794 (code-char (logxor #x20 n-code))
2797 ;;;; equality predicate transforms
2799 ;;; Return true if X and Y are continuations whose only use is a
2800 ;;; reference to the same leaf, and the value of the leaf cannot
2802 (defun same-leaf-ref-p (x y)
2803 (declare (type continuation x y))
2804 (let ((x-use (continuation-use x))
2805 (y-use (continuation-use y)))
2808 (eq (ref-leaf x-use) (ref-leaf y-use))
2809 (constant-reference-p x-use))))
2811 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
2812 ;;; if there is no intersection between the types of the arguments,
2813 ;;; then the result is definitely false.
2814 (deftransform simple-equality-transform ((x y) * *
2816 (cond ((same-leaf-ref-p x y)
2818 ((not (types-equal-or-intersect (continuation-type x)
2819 (continuation-type y)))
2822 (give-up-ir1-transform))))
2825 `(%deftransform ',x '(function * *) #'simple-equality-transform)))
2830 ;;; This is similar to SIMPLE-EQUALITY-PREDICATE, except that we also
2831 ;;; try to convert to a type-specific predicate or EQ:
2832 ;;; -- If both args are characters, convert to CHAR=. This is better than
2833 ;;; just converting to EQ, since CHAR= may have special compilation
2834 ;;; strategies for non-standard representations, etc.
2835 ;;; -- If either arg is definitely not a number, then we can compare
2837 ;;; -- Otherwise, we try to put the arg we know more about second. If X
2838 ;;; is constant then we put it second. If X is a subtype of Y, we put
2839 ;;; it second. These rules make it easier for the back end to match
2840 ;;; these interesting cases.
2841 ;;; -- If Y is a fixnum, then we quietly pass because the back end can
2842 ;;; handle that case, otherwise give an efficiency note.
2843 (deftransform eql ((x y) * *)
2844 "convert to simpler equality predicate"
2845 (let ((x-type (continuation-type x))
2846 (y-type (continuation-type y))
2847 (char-type (specifier-type 'character))
2848 (number-type (specifier-type 'number)))
2849 (cond ((same-leaf-ref-p x y)
2851 ((not (types-equal-or-intersect x-type y-type))
2853 ((and (csubtypep x-type char-type)
2854 (csubtypep y-type char-type))
2856 ((or (not (types-equal-or-intersect x-type number-type))
2857 (not (types-equal-or-intersect y-type number-type)))
2859 ((and (not (constant-continuation-p y))
2860 (or (constant-continuation-p x)
2861 (and (csubtypep x-type y-type)
2862 (not (csubtypep y-type x-type)))))
2865 (give-up-ir1-transform)))))
2867 ;;; Convert to EQL if both args are rational and complexp is specified
2868 ;;; and the same for both.
2869 (deftransform = ((x y) * *)
2871 (let ((x-type (continuation-type x))
2872 (y-type (continuation-type y)))
2873 (if (and (csubtypep x-type (specifier-type 'number))
2874 (csubtypep y-type (specifier-type 'number)))
2875 (cond ((or (and (csubtypep x-type (specifier-type 'float))
2876 (csubtypep y-type (specifier-type 'float)))
2877 (and (csubtypep x-type (specifier-type '(complex float)))
2878 (csubtypep y-type (specifier-type '(complex float)))))
2879 ;; They are both floats. Leave as = so that -0.0 is
2880 ;; handled correctly.
2881 (give-up-ir1-transform))
2882 ((or (and (csubtypep x-type (specifier-type 'rational))
2883 (csubtypep y-type (specifier-type 'rational)))
2884 (and (csubtypep x-type
2885 (specifier-type '(complex rational)))
2887 (specifier-type '(complex rational)))))
2888 ;; They are both rationals and complexp is the same.
2892 (give-up-ir1-transform
2893 "The operands might not be the same type.")))
2894 (give-up-ir1-transform
2895 "The operands might not be the same type."))))
2897 ;;; If CONT's type is a numeric type, then return the type, otherwise
2898 ;;; GIVE-UP-IR1-TRANSFORM.
2899 (defun numeric-type-or-lose (cont)
2900 (declare (type continuation cont))
2901 (let ((res (continuation-type cont)))
2902 (unless (numeric-type-p res) (give-up-ir1-transform))
2905 ;;; See whether we can statically determine (< X Y) using type
2906 ;;; information. If X's high bound is < Y's low, then X < Y.
2907 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
2908 ;;; NIL). If not, at least make sure any constant arg is second.
2910 ;;; FIXME: Why should constant argument be second? It would be nice to
2911 ;;; find out and explain.
2912 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2913 (defun ir1-transform-< (x y first second inverse)
2914 (if (same-leaf-ref-p x y)
2916 (let* ((x-type (numeric-type-or-lose x))
2917 (x-lo (numeric-type-low x-type))
2918 (x-hi (numeric-type-high x-type))
2919 (y-type (numeric-type-or-lose y))
2920 (y-lo (numeric-type-low y-type))
2921 (y-hi (numeric-type-high y-type)))
2922 (cond ((and x-hi y-lo (< x-hi y-lo))
2924 ((and y-hi x-lo (>= x-lo y-hi))
2926 ((and (constant-continuation-p first)
2927 (not (constant-continuation-p second)))
2930 (give-up-ir1-transform))))))
2931 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2932 (defun ir1-transform-< (x y first second inverse)
2933 (if (same-leaf-ref-p x y)
2935 (let ((xi (numeric-type->interval (numeric-type-or-lose x)))
2936 (yi (numeric-type->interval (numeric-type-or-lose y))))
2937 (cond ((interval-< xi yi)
2939 ((interval->= xi yi)
2941 ((and (constant-continuation-p first)
2942 (not (constant-continuation-p second)))
2945 (give-up-ir1-transform))))))
2947 (deftransform < ((x y) (integer integer) *)
2948 (ir1-transform-< x y x y '>))
2950 (deftransform > ((x y) (integer integer) *)
2951 (ir1-transform-< y x x y '<))
2953 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2954 (deftransform < ((x y) (float float) *)
2955 (ir1-transform-< x y x y '>))
2957 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2958 (deftransform > ((x y) (float float) *)
2959 (ir1-transform-< y x x y '<))
2961 ;;;; converting N-arg comparisons
2963 ;;;; We convert calls to N-arg comparison functions such as < into
2964 ;;;; two-arg calls. This transformation is enabled for all such
2965 ;;;; comparisons in this file. If any of these predicates are not
2966 ;;;; open-coded, then the transformation should be removed at some
2967 ;;;; point to avoid pessimization.
2969 ;;; This function is used for source transformation of N-arg
2970 ;;; comparison functions other than inequality. We deal both with
2971 ;;; converting to two-arg calls and inverting the sense of the test,
2972 ;;; if necessary. If the call has two args, then we pass or return a
2973 ;;; negated test as appropriate. If it is a degenerate one-arg call,
2974 ;;; then we transform to code that returns true. Otherwise, we bind
2975 ;;; all the arguments and expand into a bunch of IFs.
2976 (declaim (ftype (function (symbol list boolean) *) multi-compare))
2977 (defun multi-compare (predicate args not-p)
2978 (let ((nargs (length args)))
2979 (cond ((< nargs 1) (values nil t))
2980 ((= nargs 1) `(progn ,@args t))
2983 `(if (,predicate ,(first args) ,(second args)) nil t)
2986 (do* ((i (1- nargs) (1- i))
2988 (current (gensym) (gensym))
2989 (vars (list current) (cons current vars))
2991 `(if (,predicate ,current ,last)
2993 `(if (,predicate ,current ,last)
2996 `((lambda ,vars ,result) . ,args)))))))
2998 (define-source-transform = (&rest args) (multi-compare '= args nil))
2999 (define-source-transform < (&rest args) (multi-compare '< args nil))
3000 (define-source-transform > (&rest args) (multi-compare '> args nil))
3001 (define-source-transform <= (&rest args) (multi-compare '> args t))
3002 (define-source-transform >= (&rest args) (multi-compare '< args t))
3004 (define-source-transform char= (&rest args) (multi-compare 'char= args nil))
3005 (define-source-transform char< (&rest args) (multi-compare 'char< args nil))
3006 (define-source-transform char> (&rest args) (multi-compare 'char> args nil))
3007 (define-source-transform char<= (&rest args) (multi-compare 'char> args t))
3008 (define-source-transform char>= (&rest args) (multi-compare 'char< args t))
3010 (define-source-transform char-equal (&rest args)
3011 (multi-compare 'char-equal args nil))
3012 (define-source-transform char-lessp (&rest args)
3013 (multi-compare 'char-lessp args nil))
3014 (define-source-transform char-greaterp (&rest args)
3015 (multi-compare 'char-greaterp args nil))
3016 (define-source-transform char-not-greaterp (&rest args)
3017 (multi-compare 'char-greaterp args t))
3018 (define-source-transform char-not-lessp (&rest args)
3019 (multi-compare 'char-lessp args t))
3021 ;;; This function does source transformation of N-arg inequality
3022 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3023 ;;; arg cases. If there are more than two args, then we expand into
3024 ;;; the appropriate n^2 comparisons only when speed is important.
3025 (declaim (ftype (function (symbol list) *) multi-not-equal))
3026 (defun multi-not-equal (predicate args)
3027 (let ((nargs (length args)))
3028 (cond ((< nargs 1) (values nil t))
3029 ((= nargs 1) `(progn ,@args t))
3031 `(if (,predicate ,(first args) ,(second args)) nil t))
3032 ((not (policy *lexenv*
3033 (and (>= speed space)
3034 (>= speed compilation-speed))))
3037 (let ((vars (make-gensym-list nargs)))
3038 (do ((var vars next)
3039 (next (cdr vars) (cdr next))
3042 `((lambda ,vars ,result) . ,args))
3043 (let ((v1 (first var)))
3045 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3047 (define-source-transform /= (&rest args) (multi-not-equal '= args))
3048 (define-source-transform char/= (&rest args) (multi-not-equal 'char= args))
3049 (define-source-transform char-not-equal (&rest args)
3050 (multi-not-equal 'char-equal args))
3052 ;;; FIXME: can go away once bug 194 is fixed and we can use (THE REAL X)
3054 (defun error-not-a-real (x)
3055 (error 'simple-type-error
3057 :expected-type 'real
3058 :format-control "not a REAL: ~S"
3059 :format-arguments (list x)))
3061 ;;; Expand MAX and MIN into the obvious comparisons.
3062 (define-source-transform max (arg0 &rest rest)
3063 (once-only ((arg0 arg0))
3065 `(values (the real ,arg0))
3066 `(let ((maxrest (max ,@rest)))
3067 (if (> ,arg0 maxrest) ,arg0 maxrest)))))
3068 (define-source-transform min (arg0 &rest rest)
3069 (once-only ((arg0 arg0))
3071 `(values (the real ,arg0))
3072 `(let ((minrest (min ,@rest)))
3073 (if (< ,arg0 minrest) ,arg0 minrest)))))
3075 ;;;; converting N-arg arithmetic functions
3077 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3078 ;;;; versions, and degenerate cases are flushed.
3080 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3081 (declaim (ftype (function (symbol t list) list) associate-args))
3082 (defun associate-args (function first-arg more-args)
3083 (let ((next (rest more-args))
3084 (arg (first more-args)))
3086 `(,function ,first-arg ,arg)
3087 (associate-args function `(,function ,first-arg ,arg) next))))
3089 ;;; Do source transformations for transitive functions such as +.
3090 ;;; One-arg cases are replaced with the arg and zero arg cases with
3091 ;;; the identity. ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3092 ;;; ensure (with THE) that the argument in one-argument calls is.
3093 (defun source-transform-transitive (fun args identity
3094 &optional one-arg-result-type)
3095 (declare (symbol fun leaf-fun) (list args))
3098 (1 (if one-arg-result-type
3099 `(values (the ,one-arg-result-type ,(first args)))
3100 `(values ,(first args))))
3103 (associate-args fun (first args) (rest args)))))
3105 (define-source-transform + (&rest args)
3106 (source-transform-transitive '+ args 0 'number))
3107 (define-source-transform * (&rest args)
3108 (source-transform-transitive '* args 1 'number))
3109 (define-source-transform logior (&rest args)
3110 (source-transform-transitive 'logior args 0 'integer))
3111 (define-source-transform logxor (&rest args)
3112 (source-transform-transitive 'logxor args 0 'integer))
3113 (define-source-transform logand (&rest args)
3114 (source-transform-transitive 'logand args -1 'integer))
3116 (define-source-transform logeqv (&rest args)
3117 (if (evenp (length args))
3118 `(lognot (logxor ,@args))
3121 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3122 ;;; because when they are given one argument, they return its absolute
3125 (define-source-transform gcd (&rest args)
3128 (1 `(abs (the integer ,(first args))))
3130 (t (associate-args 'gcd (first args) (rest args)))))
3132 (define-source-transform lcm (&rest args)
3135 (1 `(abs (the integer ,(first args))))
3137 (t (associate-args 'lcm (first args) (rest args)))))
3139 ;;; Do source transformations for intransitive n-arg functions such as
3140 ;;; /. With one arg, we form the inverse. With two args we pass.
3141 ;;; Otherwise we associate into two-arg calls.
3142 (declaim (ftype (function (symbol list t)
3143 (values list &optional (member nil t)))
3144 source-transform-intransitive))
3145 (defun source-transform-intransitive (function args inverse)
3147 ((0 2) (values nil t))
3148 (1 `(,@inverse ,(first args)))
3149 (t (associate-args function (first args) (rest args)))))
3151 (define-source-transform - (&rest args)
3152 (source-transform-intransitive '- args '(%negate)))
3153 (define-source-transform / (&rest args)
3154 (source-transform-intransitive '/ args '(/ 1)))
3156 ;;;; transforming APPLY
3158 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3159 ;;; only needs to understand one kind of variable-argument call. It is
3160 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3161 (define-source-transform apply (fun arg &rest more-args)
3162 (let ((args (cons arg more-args)))
3163 `(multiple-value-call ,fun
3164 ,@(mapcar (lambda (x)
3167 (values-list ,(car (last args))))))
3169 ;;;; transforming FORMAT
3171 ;;;; If the control string is a compile-time constant, then replace it
3172 ;;;; with a use of the FORMATTER macro so that the control string is
3173 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3174 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3175 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3177 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3178 :policy (> speed space))
3179 (unless (constant-continuation-p control)
3180 (give-up-ir1-transform "The control string is not a constant."))
3181 (let ((arg-names (make-gensym-list (length args))))
3182 `(lambda (dest control ,@arg-names)
3183 (declare (ignore control))
3184 (format dest (formatter ,(continuation-value control)) ,@arg-names))))
3186 (deftransform format ((stream control &rest args) (stream function &rest t) *
3187 :policy (> speed space))
3188 (let ((arg-names (make-gensym-list (length args))))
3189 `(lambda (stream control ,@arg-names)
3190 (funcall control stream ,@arg-names)
3193 (deftransform format ((tee control &rest args) ((member t) function &rest t) *
3194 :policy (> speed space))
3195 (let ((arg-names (make-gensym-list (length args))))
3196 `(lambda (tee control ,@arg-names)
3197 (declare (ignore tee))
3198 (funcall control *standard-output* ,@arg-names)
3201 (defoptimizer (coerce derive-type) ((value type))
3203 ((constant-continuation-p type)
3204 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3205 ;; but dealing with the niggle that complex canonicalization gets
3206 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3208 (let* ((specifier (continuation-value type))
3209 (result-typeoid (careful-specifier-type specifier)))
3211 ((null result-typeoid) nil)
3212 ((csubtypep result-typeoid (specifier-type 'number))
3213 ;; the difficult case: we have to cope with ANSI 12.1.5.3
3214 ;; Rule of Canonical Representation for Complex Rationals,
3215 ;; which is a truly nasty delivery to field.
3217 ((csubtypep result-typeoid (specifier-type 'real))
3218 ;; cleverness required here: it would be nice to deduce
3219 ;; that something of type (INTEGER 2 3) coerced to type
3220 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3221 ;; FLOAT gets its own clause because it's implemented as
3222 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3225 ((and (numeric-type-p result-typeoid)
3226 (eq (numeric-type-complexp result-typeoid) :real))
3227 ;; FIXME: is this clause (a) necessary or (b) useful?
3229 ((or (csubtypep result-typeoid
3230 (specifier-type '(complex single-float)))
3231 (csubtypep result-typeoid
3232 (specifier-type '(complex double-float)))
3234 (csubtypep result-typeoid
3235 (specifier-type '(complex long-float))))
3236 ;; float complex types are never canonicalized.
3239 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
3240 ;; probably just a COMPLEX or equivalent. So, in that
3241 ;; case, we will return a complex or an object of the
3242 ;; provided type if it's rational:
3243 (type-union result-typeoid
3244 (type-intersection (continuation-type value)
3245 (specifier-type 'rational))))))
3246 (t result-typeoid))))
3248 ;; OK, the result-type argument isn't constant. However, there
3249 ;; are common uses where we can still do better than just
3250 ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
3251 ;; where Y is of a known type. See messages on cmucl-imp
3252 ;; 2001-02-14 and sbcl-devel 2002-12-12. We only worry here
3253 ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
3254 ;; the basis that it's unlikely that other uses are both
3255 ;; time-critical and get to this branch of the COND (non-constant
3256 ;; second argument to COERCE). -- CSR, 2002-12-16
3257 (let ((value-type (continuation-type value))
3258 (type-type (continuation-type type)))
3260 ((good-cons-type-p (cons-type)
3261 ;; Make sure the cons-type we're looking at is something
3262 ;; we're prepared to handle which is basically something
3263 ;; that array-element-type can return.
3264 (or (and (member-type-p cons-type)
3265 (null (rest (member-type-members cons-type)))
3266 (null (first (member-type-members cons-type))))
3267 (let ((car-type (cons-type-car-type cons-type)))
3268 (and (member-type-p car-type)
3269 (null (rest (member-type-members car-type)))
3270 (or (symbolp (first (member-type-members car-type)))
3271 (numberp (first (member-type-members car-type)))
3272 (and (listp (first (member-type-members
3274 (numberp (first (first (member-type-members
3276 (good-cons-type-p (cons-type-cdr-type cons-type))))))
3277 (unconsify-type (good-cons-type)
3278 ;; Convert the "printed" respresentation of a cons
3279 ;; specifier into a type specifier. That is, the
3280 ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
3281 ;; NULL)) is converted to (SIGNED-BYTE 16).
3282 (cond ((or (null good-cons-type)
3283 (eq good-cons-type 'null))
3285 ((and (eq (first good-cons-type) 'cons)
3286 (eq (first (second good-cons-type)) 'member))
3287 `(,(second (second good-cons-type))
3288 ,@(unconsify-type (caddr good-cons-type))))))
3289 (coerceable-p (c-type)
3290 ;; Can the value be coerced to the given type? Coerce is
3291 ;; complicated, so we don't handle every possible case
3292 ;; here---just the most common and easiest cases:
3294 ;; * Any REAL can be coerced to a FLOAT type.
3295 ;; * Any NUMBER can be coerced to a (COMPLEX
3296 ;; SINGLE/DOUBLE-FLOAT).
3298 ;; FIXME I: we should also be able to deal with characters
3301 ;; FIXME II: I'm not sure that anything is necessary
3302 ;; here, at least while COMPLEX is not a specialized
3303 ;; array element type in the system. Reasoning: if
3304 ;; something cannot be coerced to the requested type, an
3305 ;; error will be raised (and so any downstream compiled
3306 ;; code on the assumption of the returned type is
3307 ;; unreachable). If something can, then it will be of
3308 ;; the requested type, because (by assumption) COMPLEX
3309 ;; (and other difficult types like (COMPLEX INTEGER)
3310 ;; aren't specialized types.
3311 (let ((coerced-type c-type))
3312 (or (and (subtypep coerced-type 'float)
3313 (csubtypep value-type (specifier-type 'real)))
3314 (and (subtypep coerced-type
3315 '(or (complex single-float)
3316 (complex double-float)))
3317 (csubtypep value-type (specifier-type 'number))))))
3318 (process-types (type)
3319 ;; FIXME: This needs some work because we should be able
3320 ;; to derive the resulting type better than just the
3321 ;; type arg of coerce. That is, if X is (INTEGER 10
3322 ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
3323 ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
3325 (cond ((member-type-p type)
3326 (let ((members (member-type-members type)))
3327 (if (every #'coerceable-p members)
3328 (specifier-type `(or ,@members))
3330 ((and (cons-type-p type)
3331 (good-cons-type-p type))
3332 (let ((c-type (unconsify-type (type-specifier type))))
3333 (if (coerceable-p c-type)
3334 (specifier-type c-type)
3337 *universal-type*))))
3338 (cond ((union-type-p type-type)
3339 (apply #'type-union (mapcar #'process-types
3340 (union-type-types type-type))))
3341 ((or (member-type-p type-type)
3342 (cons-type-p type-type))
3343 (process-types type-type))
3345 *universal-type*)))))))
3347 (defoptimizer (compile derive-type) ((nameoid function))
3348 (when (csubtypep (continuation-type nameoid)
3349 (specifier-type 'null))
3350 (values-specifier-type '(values function boolean boolean))))
3352 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
3353 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
3354 ;;; optimizer, above).
3355 (defoptimizer (array-element-type derive-type) ((array))
3356 (let ((array-type (continuation-type array)))
3357 (labels ((consify (list)
3360 `(cons (eql ,(car list)) ,(consify (rest list)))))
3361 (get-element-type (a)
3363 (type-specifier (array-type-specialized-element-type a))))
3364 (cond ((eq element-type '*)
3365 (specifier-type 'type-specifier))
3366 ((symbolp element-type)
3367 (make-member-type :members (list element-type)))
3368 ((consp element-type)
3369 (specifier-type (consify element-type)))
3371 (error "can't understand type ~S~%" element-type))))))
3372 (cond ((array-type-p array-type)
3373 (get-element-type array-type))
3374 ((union-type-p array-type)
3376 (mapcar #'get-element-type (union-type-types array-type))))
3378 *universal-type*)))))
3380 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
3381 `(macrolet ((%index (x) `(truly-the index ,x))
3382 (%parent (i) `(ash ,i -1))
3383 (%left (i) `(%index (ash ,i 1)))
3384 (%right (i) `(%index (1+ (ash ,i 1))))
3387 (left (%left i) (%left i)))
3388 ((> left current-heap-size))
3389 (declare (type index i left))
3390 (let* ((i-elt (%elt i))
3391 (i-key (funcall keyfun i-elt))
3392 (left-elt (%elt left))
3393 (left-key (funcall keyfun left-elt)))
3394 (multiple-value-bind (large large-elt large-key)
3395 (if (funcall ,',predicate i-key left-key)
3396 (values left left-elt left-key)
3397 (values i i-elt i-key))
3398 (let ((right (%right i)))
3399 (multiple-value-bind (largest largest-elt)
3400 (if (> right current-heap-size)
3401 (values large large-elt)
3402 (let* ((right-elt (%elt right))
3403 (right-key (funcall keyfun right-elt)))
3404 (if (funcall ,',predicate large-key right-key)
3405 (values right right-elt)
3406 (values large large-elt))))
3407 (cond ((= largest i)
3410 (setf (%elt i) largest-elt
3411 (%elt largest) i-elt
3413 (%sort-vector (keyfun &optional (vtype 'vector))
3414 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had trouble getting
3415 ;; type inference to propagate all the way
3416 ;; through this tangled mess of
3417 ;; inlining. The TRULY-THE here works
3418 ;; around that. -- WHN
3420 `(aref (truly-the ,',vtype ,',',vector)
3421 (%index (+ (%index ,i) start-1)))))
3422 (let ((start-1 (1- ,',start)) ; Heaps prefer 1-based addressing.
3423 (current-heap-size (- ,',end ,',start))
3425 (declare (type (integer -1 #.(1- most-positive-fixnum))
3427 (declare (type index current-heap-size))
3428 (declare (type function keyfun))
3429 (loop for i of-type index
3430 from (ash current-heap-size -1) downto 1 do
3433 (when (< current-heap-size 2)
3435 (rotatef (%elt 1) (%elt current-heap-size))
3436 (decf current-heap-size)
3438 (if (typep ,vector 'simple-vector)
3439 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
3440 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
3442 ;; Special-casing the KEY=NIL case lets us avoid some
3444 (%sort-vector #'identity simple-vector)
3445 (%sort-vector ,key simple-vector))
3446 ;; It's hard to anticipate many speed-critical applications for
3447 ;; sorting vector types other than (VECTOR T), so we just lump
3448 ;; them all together in one slow dynamically typed mess.
3450 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
3451 (%sort-vector (or ,key #'identity))))))
3453 ;;;; debuggers' little helpers
3455 ;;; for debugging when transforms are behaving mysteriously,
3456 ;;; e.g. when debugging a problem with an ASH transform
3457 ;;; (defun foo (&optional s)
3458 ;;; (sb-c::/report-continuation s "S outside WHEN")
3459 ;;; (when (and (integerp s) (> s 3))
3460 ;;; (sb-c::/report-continuation s "S inside WHEN")
3461 ;;; (let ((bound (ash 1 (1- s))))
3462 ;;; (sb-c::/report-continuation bound "BOUND")
3463 ;;; (let ((x (- bound))
3465 ;;; (sb-c::/report-continuation x "X")
3466 ;;; (sb-c::/report-continuation x "Y"))
3467 ;;; `(integer ,(- bound) ,(1- bound)))))
3468 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
3469 ;;; and the function doesn't do anything at all.)
3472 (defknown /report-continuation (t t) null)
3473 (deftransform /report-continuation ((x message) (t t))
3474 (format t "~%/in /REPORT-CONTINUATION~%")
3475 (format t "/(CONTINUATION-TYPE X)=~S~%" (continuation-type x))
3476 (when (constant-continuation-p x)
3477 (format t "/(CONTINUATION-VALUE X)=~S~%" (continuation-value x)))
3478 (format t "/MESSAGE=~S~%" (continuation-value message))
3479 (give-up-ir1-transform "not a real transform"))
3480 (defun /report-continuation (&rest rest)
3481 (declare (ignore rest))))