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 (let ((rest (gensym "CONSTANTLY-REST-"))
35 (n-value (gensym "CONSTANTLY-VALUE-")))
36 `(let ((,n-value ,value))
38 (declare (ignore ,rest))
41 ;;; If the function has a known number of arguments, then return a
42 ;;; lambda with the appropriate fixed number of args. If the
43 ;;; destination is a FUNCALL, then do the &REST APPLY thing, and let
44 ;;; MV optimization figure things out.
45 (deftransform complement ((fun) * * :node node)
47 (multiple-value-bind (min max)
48 (fun-type-nargs (continuation-type fun))
50 ((and min (eql min max))
51 (let ((dums (make-gensym-list min)))
52 `#'(lambda ,dums (not (funcall fun ,@dums)))))
53 ((let* ((cont (node-cont node))
54 (dest (continuation-dest cont)))
55 (and (combination-p dest)
56 (eq (combination-fun dest) cont)))
57 '#'(lambda (&rest args)
58 (not (apply fun args))))
60 (give-up-ir1-transform
61 "The function doesn't have a fixed argument count.")))))
65 ;;; Translate CxR into CAR/CDR combos.
66 (defun source-transform-cxr (form)
67 (if (/= (length form) 2)
69 (let ((name (symbol-name (car form))))
70 (do ((i (- (length name) 2) (1- i))
72 `(,(ecase (char name i)
78 ;;; Make source transforms to turn CxR forms into combinations of CAR
79 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
81 (/show0 "about to set CxR source transforms")
82 (loop for i of-type index from 2 upto 4 do
83 ;; Iterate over BUF = all names CxR where x = an I-element
84 ;; string of #\A or #\D characters.
85 (let ((buf (make-string (+ 2 i))))
86 (setf (aref buf 0) #\C
87 (aref buf (1+ i)) #\R)
88 (dotimes (j (ash 2 i))
89 (declare (type index j))
91 (declare (type index k))
92 (setf (aref buf (1+ k))
93 (if (logbitp k j) #\A #\D)))
94 (setf (info :function :source-transform (intern buf))
95 #'source-transform-cxr))))
96 (/show0 "done setting CxR source transforms")
98 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
99 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
100 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
102 (define-source-transform first (x) `(car ,x))
103 (define-source-transform rest (x) `(cdr ,x))
104 (define-source-transform second (x) `(cadr ,x))
105 (define-source-transform third (x) `(caddr ,x))
106 (define-source-transform fourth (x) `(cadddr ,x))
107 (define-source-transform fifth (x) `(nth 4 ,x))
108 (define-source-transform sixth (x) `(nth 5 ,x))
109 (define-source-transform seventh (x) `(nth 6 ,x))
110 (define-source-transform eighth (x) `(nth 7 ,x))
111 (define-source-transform ninth (x) `(nth 8 ,x))
112 (define-source-transform tenth (x) `(nth 9 ,x))
114 ;;; Translate RPLACx to LET and SETF.
115 (define-source-transform rplaca (x y)
120 (define-source-transform rplacd (x y)
126 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
128 (defvar *default-nthcdr-open-code-limit* 6)
129 (defvar *extreme-nthcdr-open-code-limit* 20)
131 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
132 "convert NTHCDR to CAxxR"
133 (unless (constant-continuation-p n)
134 (give-up-ir1-transform))
135 (let ((n (continuation-value n)))
137 (if (policy node (and (= speed 3) (= space 0)))
138 *extreme-nthcdr-open-code-limit*
139 *default-nthcdr-open-code-limit*))
140 (give-up-ir1-transform))
145 `(cdr ,(frob (1- n))))))
148 ;;;; arithmetic and numerology
150 (define-source-transform plusp (x) `(> ,x 0))
151 (define-source-transform minusp (x) `(< ,x 0))
152 (define-source-transform zerop (x) `(= ,x 0))
154 (define-source-transform 1+ (x) `(+ ,x 1))
155 (define-source-transform 1- (x) `(- ,x 1))
157 (define-source-transform oddp (x) `(not (zerop (logand ,x 1))))
158 (define-source-transform evenp (x) `(zerop (logand ,x 1)))
160 ;;; Note that all the integer division functions are available for
161 ;;; inline expansion.
163 (macrolet ((deffrob (fun)
164 `(define-source-transform ,fun (x &optional (y nil y-p))
171 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
173 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
176 (define-source-transform lognand (x y) `(lognot (logand ,x ,y)))
177 (define-source-transform lognor (x y) `(lognot (logior ,x ,y)))
178 (define-source-transform logandc1 (x y) `(logand (lognot ,x) ,y))
179 (define-source-transform logandc2 (x y) `(logand ,x (lognot ,y)))
180 (define-source-transform logorc1 (x y) `(logior (lognot ,x) ,y))
181 (define-source-transform logorc2 (x y) `(logior ,x (lognot ,y)))
182 (define-source-transform logtest (x y) `(not (zerop (logand ,x ,y))))
183 (define-source-transform logbitp (index integer)
184 `(not (zerop (logand (ash 1 ,index) ,integer))))
185 (define-source-transform byte (size position)
186 `(cons ,size ,position))
187 (define-source-transform byte-size (spec) `(car ,spec))
188 (define-source-transform byte-position (spec) `(cdr ,spec))
189 (define-source-transform ldb-test (bytespec integer)
190 `(not (zerop (mask-field ,bytespec ,integer))))
192 ;;; With the ratio and complex accessors, we pick off the "identity"
193 ;;; case, and use a primitive to handle the cell access case.
194 (define-source-transform numerator (num)
195 (once-only ((n-num `(the rational ,num)))
199 (define-source-transform denominator (num)
200 (once-only ((n-num `(the rational ,num)))
202 (%denominator ,n-num)
205 ;;;; interval arithmetic for computing bounds
207 ;;;; This is a set of routines for operating on intervals. It
208 ;;;; implements a simple interval arithmetic package. Although SBCL
209 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
210 ;;;; for two reasons:
212 ;;;; 1. This package is simpler than NUMERIC-TYPE.
214 ;;;; 2. It makes debugging much easier because you can just strip
215 ;;;; out these routines and test them independently of SBCL. (This is a
218 ;;;; One disadvantage is a probable increase in consing because we
219 ;;;; have to create these new interval structures even though
220 ;;;; numeric-type has everything we want to know. Reason 2 wins for
223 ;;; The basic interval type. It can handle open and closed intervals.
224 ;;; A bound is open if it is a list containing a number, just like
225 ;;; Lisp says. NIL means unbounded.
226 (defstruct (interval (:constructor %make-interval)
230 (defun make-interval (&key low high)
231 (labels ((normalize-bound (val)
232 (cond ((and (floatp val)
233 (float-infinity-p val))
234 ;; Handle infinities.
238 ;; Handle any closed bounds.
241 ;; We have an open bound. Normalize the numeric
242 ;; bound. If the normalized bound is still a number
243 ;; (not nil), keep the bound open. Otherwise, the
244 ;; bound is really unbounded, so drop the openness.
245 (let ((new-val (normalize-bound (first val))))
247 ;; The bound exists, so keep it open still.
250 (error "unknown bound type in MAKE-INTERVAL")))))
251 (%make-interval :low (normalize-bound low)
252 :high (normalize-bound high))))
254 ;;; Given a number X, create a form suitable as a bound for an
255 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
256 #!-sb-fluid (declaim (inline set-bound))
257 (defun set-bound (x open-p)
258 (if (and x open-p) (list x) x))
260 ;;; Apply the function F to a bound X. If X is an open bound, then
261 ;;; the result will be open. IF X is NIL, the result is NIL.
262 (defun bound-func (f x)
263 (declare (type function f))
265 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
266 ;; With these traps masked, we might get things like infinity
267 ;; or negative infinity returned. Check for this and return
268 ;; NIL to indicate unbounded.
269 (let ((y (funcall f (type-bound-number x))))
271 (float-infinity-p y))
273 (set-bound (funcall f (type-bound-number x)) (consp x)))))))
275 ;;; Apply a binary operator OP to two bounds X and Y. The result is
276 ;;; NIL if either is NIL. Otherwise bound is computed and the result
277 ;;; is open if either X or Y is open.
279 ;;; FIXME: only used in this file, not needed in target runtime
280 (defmacro bound-binop (op x y)
282 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
283 (set-bound (,op (type-bound-number ,x)
284 (type-bound-number ,y))
285 (or (consp ,x) (consp ,y))))))
287 ;;; Convert a numeric-type object to an interval object.
288 (defun numeric-type->interval (x)
289 (declare (type numeric-type x))
290 (make-interval :low (numeric-type-low x)
291 :high (numeric-type-high x)))
293 (defun copy-interval-limit (limit)
298 (defun copy-interval (x)
299 (declare (type interval x))
300 (make-interval :low (copy-interval-limit (interval-low x))
301 :high (copy-interval-limit (interval-high x))))
303 ;;; Given a point P contained in the interval X, split X into two
304 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
305 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
306 ;;; contains P. You can specify both to be T or NIL.
307 (defun interval-split (p x &optional close-lower close-upper)
308 (declare (type number p)
310 (list (make-interval :low (copy-interval-limit (interval-low x))
311 :high (if close-lower p (list p)))
312 (make-interval :low (if close-upper (list p) p)
313 :high (copy-interval-limit (interval-high x)))))
315 ;;; Return the closure of the interval. That is, convert open bounds
316 ;;; to closed bounds.
317 (defun interval-closure (x)
318 (declare (type interval x))
319 (make-interval :low (type-bound-number (interval-low x))
320 :high (type-bound-number (interval-high x))))
322 (defun signed-zero->= (x y)
326 (>= (float-sign (float x))
327 (float-sign (float y))))))
329 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
330 ;;; '-. Otherwise return NIL.
332 (defun interval-range-info (x &optional (point 0))
333 (declare (type interval x))
334 (let ((lo (interval-low x))
335 (hi (interval-high x)))
336 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
338 ((and hi (signed-zero->= point (type-bound-number hi)))
342 (defun interval-range-info (x &optional (point 0))
343 (declare (type interval x))
344 (labels ((signed->= (x y)
345 (if (and (zerop x) (zerop y) (floatp x) (floatp y))
346 (>= (float-sign x) (float-sign y))
348 (let ((lo (interval-low x))
349 (hi (interval-high x)))
350 (cond ((and lo (signed->= (type-bound-number lo) point))
352 ((and hi (signed->= point (type-bound-number hi)))
357 ;;; Test to see whether the interval X is bounded. HOW determines the
358 ;;; test, and should be either ABOVE, BELOW, or BOTH.
359 (defun interval-bounded-p (x how)
360 (declare (type interval x))
367 (and (interval-low x) (interval-high x)))))
369 ;;; signed zero comparison functions. Use these functions if we need
370 ;;; to distinguish between signed zeroes.
371 (defun signed-zero-< (x y)
375 (< (float-sign (float x))
376 (float-sign (float y))))))
377 (defun signed-zero-> (x y)
381 (> (float-sign (float x))
382 (float-sign (float y))))))
383 (defun signed-zero-= (x y)
386 (= (float-sign (float x))
387 (float-sign (float y)))))
388 (defun signed-zero-<= (x y)
392 (<= (float-sign (float x))
393 (float-sign (float y))))))
395 ;;; See whether the interval X contains the number P, taking into
396 ;;; account that the interval might not be closed.
397 (defun interval-contains-p (p x)
398 (declare (type number p)
400 ;; Does the interval X contain the number P? This would be a lot
401 ;; easier if all intervals were closed!
402 (let ((lo (interval-low x))
403 (hi (interval-high x)))
405 ;; The interval is bounded
406 (if (and (signed-zero-<= (type-bound-number lo) p)
407 (signed-zero-<= p (type-bound-number hi)))
408 ;; P is definitely in the closure of the interval.
409 ;; We just need to check the end points now.
410 (cond ((signed-zero-= p (type-bound-number lo))
412 ((signed-zero-= p (type-bound-number hi))
417 ;; Interval with upper bound
418 (if (signed-zero-< p (type-bound-number hi))
420 (and (numberp hi) (signed-zero-= p hi))))
422 ;; Interval with lower bound
423 (if (signed-zero-> p (type-bound-number lo))
425 (and (numberp lo) (signed-zero-= p lo))))
427 ;; Interval with no bounds
430 ;;; Determine whether two intervals X and Y intersect. Return T if so.
431 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
432 ;;; were closed. Otherwise the intervals are treated as they are.
434 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
435 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
436 ;;; is T, then they do intersect because we use the closure of X = [0,
437 ;;; 1] and Y = [1, 2] to determine intersection.
438 (defun interval-intersect-p (x y &optional closed-intervals-p)
439 (declare (type interval x y))
440 (multiple-value-bind (intersect diff)
441 (interval-intersection/difference (if closed-intervals-p
444 (if closed-intervals-p
447 (declare (ignore diff))
450 ;;; Are the two intervals adjacent? That is, is there a number
451 ;;; between the two intervals that is not an element of either
452 ;;; interval? If so, they are not adjacent. For example [0, 1) and
453 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
454 ;;; between both intervals.
455 (defun interval-adjacent-p (x y)
456 (declare (type interval x y))
457 (flet ((adjacent (lo hi)
458 ;; Check to see whether lo and hi are adjacent. If either is
459 ;; nil, they can't be adjacent.
460 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
461 ;; The bounds are equal. They are adjacent if one of
462 ;; them is closed (a number). If both are open (consp),
463 ;; then there is a number that lies between them.
464 (or (numberp lo) (numberp hi)))))
465 (or (adjacent (interval-low y) (interval-high x))
466 (adjacent (interval-low x) (interval-high y)))))
468 ;;; Compute the intersection and difference between two intervals.
469 ;;; Two values are returned: the intersection and the difference.
471 ;;; Let the two intervals be X and Y, and let I and D be the two
472 ;;; values returned by this function. Then I = X intersect Y. If I
473 ;;; is NIL (the empty set), then D is X union Y, represented as the
474 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
475 ;;; - I, which is a list of two intervals.
477 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
478 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
479 (defun interval-intersection/difference (x y)
480 (declare (type interval x y))
481 (let ((x-lo (interval-low x))
482 (x-hi (interval-high x))
483 (y-lo (interval-low y))
484 (y-hi (interval-high y)))
487 ;; If p is an open bound, make it closed. If p is a closed
488 ;; bound, make it open.
493 ;; Test whether P is in the interval.
494 (when (interval-contains-p (type-bound-number p)
495 (interval-closure int))
496 (let ((lo (interval-low int))
497 (hi (interval-high int)))
498 ;; Check for endpoints.
499 (cond ((and lo (= (type-bound-number p) (type-bound-number lo)))
500 (not (and (consp p) (numberp lo))))
501 ((and hi (= (type-bound-number p) (type-bound-number hi)))
502 (not (and (numberp p) (consp hi))))
504 (test-lower-bound (p int)
505 ;; P is a lower bound of an interval.
508 (not (interval-bounded-p int 'below))))
509 (test-upper-bound (p int)
510 ;; P is an upper bound of an interval.
513 (not (interval-bounded-p int 'above)))))
514 (let ((x-lo-in-y (test-lower-bound x-lo y))
515 (x-hi-in-y (test-upper-bound x-hi y))
516 (y-lo-in-x (test-lower-bound y-lo x))
517 (y-hi-in-x (test-upper-bound y-hi x)))
518 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
519 ;; Intervals intersect. Let's compute the intersection
520 ;; and the difference.
521 (multiple-value-bind (lo left-lo left-hi)
522 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
523 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
524 (multiple-value-bind (hi right-lo right-hi)
526 (values x-hi (opposite-bound x-hi) y-hi))
528 (values y-hi (opposite-bound y-hi) x-hi)))
529 (values (make-interval :low lo :high hi)
530 (list (make-interval :low left-lo
532 (make-interval :low right-lo
535 (values nil (list x y))))))))
537 ;;; If intervals X and Y intersect, return a new interval that is the
538 ;;; union of the two. If they do not intersect, return NIL.
539 (defun interval-merge-pair (x y)
540 (declare (type interval x y))
541 ;; If x and y intersect or are adjacent, create the union.
542 ;; Otherwise return nil
543 (when (or (interval-intersect-p x y)
544 (interval-adjacent-p x y))
545 (flet ((select-bound (x1 x2 min-op max-op)
546 (let ((x1-val (type-bound-number x1))
547 (x2-val (type-bound-number x2)))
549 ;; Both bounds are finite. Select the right one.
550 (cond ((funcall min-op x1-val x2-val)
551 ;; x1 is definitely better.
553 ((funcall max-op x1-val x2-val)
554 ;; x2 is definitely better.
557 ;; Bounds are equal. Select either
558 ;; value and make it open only if
560 (set-bound x1-val (and (consp x1) (consp x2))))))
562 ;; At least one bound is not finite. The
563 ;; non-finite bound always wins.
565 (let* ((x-lo (copy-interval-limit (interval-low x)))
566 (x-hi (copy-interval-limit (interval-high x)))
567 (y-lo (copy-interval-limit (interval-low y)))
568 (y-hi (copy-interval-limit (interval-high y))))
569 (make-interval :low (select-bound x-lo y-lo #'< #'>)
570 :high (select-bound x-hi y-hi #'> #'<))))))
572 ;;; basic arithmetic operations on intervals. We probably should do
573 ;;; true interval arithmetic here, but it's complicated because we
574 ;;; have float and integer types and bounds can be open or closed.
576 ;;; the negative of an interval
577 (defun interval-neg (x)
578 (declare (type interval x))
579 (make-interval :low (bound-func #'- (interval-high x))
580 :high (bound-func #'- (interval-low x))))
582 ;;; Add two intervals.
583 (defun interval-add (x y)
584 (declare (type interval x y))
585 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
586 :high (bound-binop + (interval-high x) (interval-high y))))
588 ;;; Subtract two intervals.
589 (defun interval-sub (x y)
590 (declare (type interval x y))
591 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
592 :high (bound-binop - (interval-high x) (interval-low y))))
594 ;;; Multiply two intervals.
595 (defun interval-mul (x y)
596 (declare (type interval x y))
597 (flet ((bound-mul (x y)
598 (cond ((or (null x) (null y))
599 ;; Multiply by infinity is infinity
601 ((or (and (numberp x) (zerop x))
602 (and (numberp y) (zerop y)))
603 ;; Multiply by closed zero is special. The result
604 ;; is always a closed bound. But don't replace this
605 ;; with zero; we want the multiplication to produce
606 ;; the correct signed zero, if needed.
607 (* (type-bound-number x) (type-bound-number y)))
608 ((or (and (floatp x) (float-infinity-p x))
609 (and (floatp y) (float-infinity-p y)))
610 ;; Infinity times anything is infinity
613 ;; General multiply. The result is open if either is open.
614 (bound-binop * x y)))))
615 (let ((x-range (interval-range-info x))
616 (y-range (interval-range-info y)))
617 (cond ((null x-range)
618 ;; Split x into two and multiply each separately
619 (destructuring-bind (x- x+) (interval-split 0 x t t)
620 (interval-merge-pair (interval-mul x- y)
621 (interval-mul x+ y))))
623 ;; Split y into two and multiply each separately
624 (destructuring-bind (y- y+) (interval-split 0 y t t)
625 (interval-merge-pair (interval-mul x y-)
626 (interval-mul x y+))))
628 (interval-neg (interval-mul (interval-neg x) y)))
630 (interval-neg (interval-mul x (interval-neg y))))
631 ((and (eq x-range '+) (eq y-range '+))
632 ;; If we are here, X and Y are both positive.
634 :low (bound-mul (interval-low x) (interval-low y))
635 :high (bound-mul (interval-high x) (interval-high y))))
637 (bug "excluded case in INTERVAL-MUL"))))))
639 ;;; Divide two intervals.
640 (defun interval-div (top bot)
641 (declare (type interval top bot))
642 (flet ((bound-div (x y y-low-p)
645 ;; Divide by infinity means result is 0. However,
646 ;; we need to watch out for the sign of the result,
647 ;; to correctly handle signed zeros. We also need
648 ;; to watch out for positive or negative infinity.
649 (if (floatp (type-bound-number x))
651 (- (float-sign (type-bound-number x) 0.0))
652 (float-sign (type-bound-number x) 0.0))
654 ((zerop (type-bound-number y))
655 ;; Divide by zero means result is infinity
657 ((and (numberp x) (zerop x))
658 ;; Zero divided by anything is zero.
661 (bound-binop / x y)))))
662 (let ((top-range (interval-range-info top))
663 (bot-range (interval-range-info bot)))
664 (cond ((null bot-range)
665 ;; The denominator contains zero, so anything goes!
666 (make-interval :low nil :high nil))
668 ;; Denominator is negative so flip the sign, compute the
669 ;; result, and flip it back.
670 (interval-neg (interval-div top (interval-neg bot))))
672 ;; Split top into two positive and negative parts, and
673 ;; divide each separately
674 (destructuring-bind (top- top+) (interval-split 0 top t t)
675 (interval-merge-pair (interval-div top- bot)
676 (interval-div top+ bot))))
678 ;; Top is negative so flip the sign, divide, and flip the
679 ;; sign of the result.
680 (interval-neg (interval-div (interval-neg top) bot)))
681 ((and (eq top-range '+) (eq bot-range '+))
684 :low (bound-div (interval-low top) (interval-high bot) t)
685 :high (bound-div (interval-high top) (interval-low bot) nil)))
687 (bug "excluded case in INTERVAL-DIV"))))))
689 ;;; Apply the function F to the interval X. If X = [a, b], then the
690 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
691 ;;; result makes sense. It will if F is monotonic increasing (or
693 (defun interval-func (f x)
694 (declare (type function f)
696 (let ((lo (bound-func f (interval-low x)))
697 (hi (bound-func f (interval-high x))))
698 (make-interval :low lo :high hi)))
700 ;;; Return T if X < Y. That is every number in the interval X is
701 ;;; always less than any number in the interval Y.
702 (defun interval-< (x y)
703 (declare (type interval x y))
704 ;; X < Y only if X is bounded above, Y is bounded below, and they
706 (when (and (interval-bounded-p x 'above)
707 (interval-bounded-p y 'below))
708 ;; Intervals are bounded in the appropriate way. Make sure they
710 (let ((left (interval-high x))
711 (right (interval-low y)))
712 (cond ((> (type-bound-number left)
713 (type-bound-number right))
714 ;; The intervals definitely overlap, so result is NIL.
716 ((< (type-bound-number left)
717 (type-bound-number right))
718 ;; The intervals definitely don't touch, so result is T.
721 ;; Limits are equal. Check for open or closed bounds.
722 ;; Don't overlap if one or the other are open.
723 (or (consp left) (consp right)))))))
725 ;;; Return T if X >= Y. That is, every number in the interval X is
726 ;;; always greater than any number in the interval Y.
727 (defun interval->= (x y)
728 (declare (type interval x y))
729 ;; X >= Y if lower bound of X >= upper bound of Y
730 (when (and (interval-bounded-p x 'below)
731 (interval-bounded-p y 'above))
732 (>= (type-bound-number (interval-low x))
733 (type-bound-number (interval-high y)))))
735 ;;; Return an interval that is the absolute value of X. Thus, if
736 ;;; X = [-1 10], the result is [0, 10].
737 (defun interval-abs (x)
738 (declare (type interval x))
739 (case (interval-range-info x)
745 (destructuring-bind (x- x+) (interval-split 0 x t t)
746 (interval-merge-pair (interval-neg x-) x+)))))
748 ;;; Compute the square of an interval.
749 (defun interval-sqr (x)
750 (declare (type interval x))
751 (interval-func (lambda (x) (* x x))
754 ;;;; numeric DERIVE-TYPE methods
756 ;;; a utility for defining derive-type methods of integer operations. If
757 ;;; the types of both X and Y are integer types, then we compute a new
758 ;;; integer type with bounds determined Fun when applied to X and Y.
759 ;;; Otherwise, we use Numeric-Contagion.
760 (defun derive-integer-type (x y fun)
761 (declare (type continuation x y) (type function fun))
762 (let ((x (continuation-type x))
763 (y (continuation-type y)))
764 (if (and (numeric-type-p x) (numeric-type-p y)
765 (eq (numeric-type-class x) 'integer)
766 (eq (numeric-type-class y) 'integer)
767 (eq (numeric-type-complexp x) :real)
768 (eq (numeric-type-complexp y) :real))
769 (multiple-value-bind (low high) (funcall fun x y)
770 (make-numeric-type :class 'integer
774 (numeric-contagion x y))))
776 ;;; simple utility to flatten a list
777 (defun flatten-list (x)
778 (labels ((flatten-helper (x r);; 'r' is the stuff to the 'right'.
782 (t (flatten-helper (car x)
783 (flatten-helper (cdr x) r))))))
784 (flatten-helper x nil)))
786 ;;; Take some type of continuation and massage it so that we get a
787 ;;; list of the constituent types. If ARG is *EMPTY-TYPE*, return NIL
788 ;;; to indicate failure.
789 (defun prepare-arg-for-derive-type (arg)
790 (flet ((listify (arg)
795 (union-type-types arg))
798 (unless (eq arg *empty-type*)
799 ;; Make sure all args are some type of numeric-type. For member
800 ;; types, convert the list of members into a union of equivalent
801 ;; single-element member-type's.
802 (let ((new-args nil))
803 (dolist (arg (listify arg))
804 (if (member-type-p arg)
805 ;; Run down the list of members and convert to a list of
807 (dolist (member (member-type-members arg))
808 (push (if (numberp member)
809 (make-member-type :members (list member))
812 (push arg new-args)))
813 (unless (member *empty-type* new-args)
816 ;;; Convert from the standard type convention for which -0.0 and 0.0
817 ;;; are equal to an intermediate convention for which they are
818 ;;; considered different which is more natural for some of the
820 (defun convert-numeric-type (type)
821 (declare (type numeric-type type))
822 ;;; Only convert real float interval delimiters types.
823 (if (eq (numeric-type-complexp type) :real)
824 (let* ((lo (numeric-type-low type))
825 (lo-val (type-bound-number lo))
826 (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
827 (hi (numeric-type-high type))
828 (hi-val (type-bound-number hi))
829 (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
830 (if (or lo-float-zero-p hi-float-zero-p)
832 :class (numeric-type-class type)
833 :format (numeric-type-format type)
835 :low (if lo-float-zero-p
837 (list (float 0.0 lo-val))
840 :high (if hi-float-zero-p
842 (list (float -0.0 hi-val))
849 ;;; Convert back from the intermediate convention for which -0.0 and
850 ;;; 0.0 are considered different to the standard type convention for
852 (defun convert-back-numeric-type (type)
853 (declare (type numeric-type type))
854 ;;; Only convert real float interval delimiters types.
855 (if (eq (numeric-type-complexp type) :real)
856 (let* ((lo (numeric-type-low type))
857 (lo-val (type-bound-number lo))
859 (and lo (floatp lo-val) (= lo-val 0.0)
860 (float-sign lo-val)))
861 (hi (numeric-type-high type))
862 (hi-val (type-bound-number hi))
864 (and hi (floatp hi-val) (= hi-val 0.0)
865 (float-sign hi-val))))
867 ;; (float +0.0 +0.0) => (member 0.0)
868 ;; (float -0.0 -0.0) => (member -0.0)
869 ((and lo-float-zero-p hi-float-zero-p)
870 ;; shouldn't have exclusive bounds here..
871 (aver (and (not (consp lo)) (not (consp hi))))
872 (if (= lo-float-zero-p hi-float-zero-p)
873 ;; (float +0.0 +0.0) => (member 0.0)
874 ;; (float -0.0 -0.0) => (member -0.0)
875 (specifier-type `(member ,lo-val))
876 ;; (float -0.0 +0.0) => (float 0.0 0.0)
877 ;; (float +0.0 -0.0) => (float 0.0 0.0)
878 (make-numeric-type :class (numeric-type-class type)
879 :format (numeric-type-format type)
885 ;; (float -0.0 x) => (float 0.0 x)
886 ((and (not (consp lo)) (minusp lo-float-zero-p))
887 (make-numeric-type :class (numeric-type-class type)
888 :format (numeric-type-format type)
890 :low (float 0.0 lo-val)
892 ;; (float (+0.0) x) => (float (0.0) x)
893 ((and (consp lo) (plusp lo-float-zero-p))
894 (make-numeric-type :class (numeric-type-class type)
895 :format (numeric-type-format type)
897 :low (list (float 0.0 lo-val))
900 ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
901 ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
902 (list (make-member-type :members (list (float 0.0 lo-val)))
903 (make-numeric-type :class (numeric-type-class type)
904 :format (numeric-type-format type)
906 :low (list (float 0.0 lo-val))
910 ;; (float x +0.0) => (float x 0.0)
911 ((and (not (consp hi)) (plusp hi-float-zero-p))
912 (make-numeric-type :class (numeric-type-class type)
913 :format (numeric-type-format type)
916 :high (float 0.0 hi-val)))
917 ;; (float x (-0.0)) => (float x (0.0))
918 ((and (consp hi) (minusp hi-float-zero-p))
919 (make-numeric-type :class (numeric-type-class type)
920 :format (numeric-type-format type)
923 :high (list (float 0.0 hi-val))))
925 ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
926 ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
927 (list (make-member-type :members (list (float -0.0 hi-val)))
928 (make-numeric-type :class (numeric-type-class type)
929 :format (numeric-type-format type)
932 :high (list (float 0.0 hi-val)))))))
938 ;;; Convert back a possible list of numeric types.
939 (defun convert-back-numeric-type-list (type-list)
943 (dolist (type type-list)
944 (if (numeric-type-p type)
945 (let ((result (convert-back-numeric-type type)))
947 (setf results (append results result))
948 (push result results)))
949 (push type results)))
952 (convert-back-numeric-type type-list))
954 (convert-back-numeric-type-list (union-type-types type-list)))
958 ;;; FIXME: MAKE-CANONICAL-UNION-TYPE and CONVERT-MEMBER-TYPE probably
959 ;;; belong in the kernel's type logic, invoked always, instead of in
960 ;;; the compiler, invoked only during some type optimizations.
962 ;;; Take a list of types and return a canonical type specifier,
963 ;;; combining any MEMBER types together. If both positive and negative
964 ;;; MEMBER types are present they are converted to a float type.
965 ;;; XXX This would be far simpler if the type-union methods could handle
966 ;;; member/number unions.
967 (defun make-canonical-union-type (type-list)
970 (dolist (type type-list)
971 (if (member-type-p type)
972 (setf members (union members (member-type-members type)))
973 (push type misc-types)))
975 (when (null (set-difference '(-0l0 0l0) members))
976 (push (specifier-type '(long-float 0l0 0l0)) misc-types)
977 (setf members (set-difference members '(-0l0 0l0))))
978 (when (null (set-difference '(-0d0 0d0) members))
979 (push (specifier-type '(double-float 0d0 0d0)) misc-types)
980 (setf members (set-difference members '(-0d0 0d0))))
981 (when (null (set-difference '(-0f0 0f0) members))
982 (push (specifier-type '(single-float 0f0 0f0)) misc-types)
983 (setf members (set-difference members '(-0f0 0f0))))
985 (apply #'type-union (make-member-type :members members) misc-types)
986 (apply #'type-union misc-types))))
988 ;;; Convert a member type with a single member to a numeric type.
989 (defun convert-member-type (arg)
990 (let* ((members (member-type-members arg))
991 (member (first members))
992 (member-type (type-of member)))
993 (aver (not (rest members)))
994 (specifier-type `(,(if (subtypep member-type 'integer)
999 ;;; This is used in defoptimizers for computing the resulting type of
1002 ;;; Given the continuation ARG, derive the resulting type using the
1003 ;;; DERIVE-FCN. DERIVE-FCN takes exactly one argument which is some
1004 ;;; "atomic" continuation type like numeric-type or member-type
1005 ;;; (containing just one element). It should return the resulting
1006 ;;; type, which can be a list of types.
1008 ;;; For the case of member types, if a member-fcn is given it is
1009 ;;; called to compute the result otherwise the member type is first
1010 ;;; converted to a numeric type and the derive-fcn is call.
1011 (defun one-arg-derive-type (arg derive-fcn member-fcn
1012 &optional (convert-type t))
1013 (declare (type function derive-fcn)
1014 (type (or null function) member-fcn))
1015 (let ((arg-list (prepare-arg-for-derive-type (continuation-type arg))))
1021 (with-float-traps-masked
1022 (:underflow :overflow :divide-by-zero)
1026 (first (member-type-members x))))))
1027 ;; Otherwise convert to a numeric type.
1028 (let ((result-type-list
1029 (funcall derive-fcn (convert-member-type x))))
1031 (convert-back-numeric-type-list result-type-list)
1032 result-type-list))))
1035 (convert-back-numeric-type-list
1036 (funcall derive-fcn (convert-numeric-type x)))
1037 (funcall derive-fcn x)))
1039 *universal-type*))))
1040 ;; Run down the list of args and derive the type of each one,
1041 ;; saving all of the results in a list.
1042 (let ((results nil))
1043 (dolist (arg arg-list)
1044 (let ((result (deriver arg)))
1046 (setf results (append results result))
1047 (push result results))))
1049 (make-canonical-union-type results)
1050 (first results)))))))
1052 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1053 ;;; two arguments. DERIVE-FCN takes 3 args in this case: the two
1054 ;;; original args and a third which is T to indicate if the two args
1055 ;;; really represent the same continuation. This is useful for
1056 ;;; deriving the type of things like (* x x), which should always be
1057 ;;; positive. If we didn't do this, we wouldn't be able to tell.
1058 (defun two-arg-derive-type (arg1 arg2 derive-fcn fcn
1059 &optional (convert-type t))
1060 (declare (type function derive-fcn fcn))
1061 (flet ((deriver (x y same-arg)
1062 (cond ((and (member-type-p x) (member-type-p y))
1063 (let* ((x (first (member-type-members x)))
1064 (y (first (member-type-members y)))
1065 (result (with-float-traps-masked
1066 (:underflow :overflow :divide-by-zero
1068 (funcall fcn x y))))
1069 (cond ((null result))
1070 ((and (floatp result) (float-nan-p result))
1071 (make-numeric-type :class 'float
1072 :format (type-of result)
1075 (make-member-type :members (list result))))))
1076 ((and (member-type-p x) (numeric-type-p y))
1077 (let* ((x (convert-member-type x))
1078 (y (if convert-type (convert-numeric-type y) y))
1079 (result (funcall derive-fcn x y same-arg)))
1081 (convert-back-numeric-type-list result)
1083 ((and (numeric-type-p x) (member-type-p y))
1084 (let* ((x (if convert-type (convert-numeric-type x) x))
1085 (y (convert-member-type y))
1086 (result (funcall derive-fcn x y same-arg)))
1088 (convert-back-numeric-type-list result)
1090 ((and (numeric-type-p x) (numeric-type-p y))
1091 (let* ((x (if convert-type (convert-numeric-type x) x))
1092 (y (if convert-type (convert-numeric-type y) y))
1093 (result (funcall derive-fcn x y same-arg)))
1095 (convert-back-numeric-type-list result)
1098 *universal-type*))))
1099 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1100 (a1 (prepare-arg-for-derive-type (continuation-type arg1)))
1101 (a2 (prepare-arg-for-derive-type (continuation-type arg2))))
1103 (let ((results nil))
1105 ;; Since the args are the same continuation, just run
1108 (let ((result (deriver x x same-arg)))
1110 (setf results (append results result))
1111 (push result results))))
1112 ;; Try all pairwise combinations.
1115 (let ((result (or (deriver x y same-arg)
1116 (numeric-contagion x y))))
1118 (setf results (append results result))
1119 (push result results))))))
1121 (make-canonical-union-type results)
1122 (first results)))))))
1124 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1126 (defoptimizer (+ derive-type) ((x y))
1127 (derive-integer-type
1134 (values (frob (numeric-type-low x) (numeric-type-low y))
1135 (frob (numeric-type-high x) (numeric-type-high y)))))))
1137 (defoptimizer (- derive-type) ((x y))
1138 (derive-integer-type
1145 (values (frob (numeric-type-low x) (numeric-type-high y))
1146 (frob (numeric-type-high x) (numeric-type-low y)))))))
1148 (defoptimizer (* derive-type) ((x y))
1149 (derive-integer-type
1152 (let ((x-low (numeric-type-low x))
1153 (x-high (numeric-type-high x))
1154 (y-low (numeric-type-low y))
1155 (y-high (numeric-type-high y)))
1156 (cond ((not (and x-low y-low))
1158 ((or (minusp x-low) (minusp y-low))
1159 (if (and x-high y-high)
1160 (let ((max (* (max (abs x-low) (abs x-high))
1161 (max (abs y-low) (abs y-high)))))
1162 (values (- max) max))
1165 (values (* x-low y-low)
1166 (if (and x-high y-high)
1170 (defoptimizer (/ derive-type) ((x y))
1171 (numeric-contagion (continuation-type x) (continuation-type y)))
1175 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1177 (defun +-derive-type-aux (x y same-arg)
1178 (if (and (numeric-type-real-p x)
1179 (numeric-type-real-p y))
1182 (let ((x-int (numeric-type->interval x)))
1183 (interval-add x-int x-int))
1184 (interval-add (numeric-type->interval x)
1185 (numeric-type->interval y))))
1186 (result-type (numeric-contagion x y)))
1187 ;; If the result type is a float, we need to be sure to coerce
1188 ;; the bounds into the correct type.
1189 (when (eq (numeric-type-class result-type) 'float)
1190 (setf result (interval-func
1192 (coerce x (or (numeric-type-format result-type)
1196 :class (if (and (eq (numeric-type-class x) 'integer)
1197 (eq (numeric-type-class y) 'integer))
1198 ;; The sum of integers is always an integer.
1200 (numeric-type-class result-type))
1201 :format (numeric-type-format result-type)
1202 :low (interval-low result)
1203 :high (interval-high result)))
1204 ;; general contagion
1205 (numeric-contagion x y)))
1207 (defoptimizer (+ derive-type) ((x y))
1208 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1210 (defun --derive-type-aux (x y same-arg)
1211 (if (and (numeric-type-real-p x)
1212 (numeric-type-real-p y))
1214 ;; (- X X) is always 0.
1216 (make-interval :low 0 :high 0)
1217 (interval-sub (numeric-type->interval x)
1218 (numeric-type->interval y))))
1219 (result-type (numeric-contagion x y)))
1220 ;; If the result type is a float, we need to be sure to coerce
1221 ;; the bounds into the correct type.
1222 (when (eq (numeric-type-class result-type) 'float)
1223 (setf result (interval-func
1225 (coerce x (or (numeric-type-format result-type)
1229 :class (if (and (eq (numeric-type-class x) 'integer)
1230 (eq (numeric-type-class y) 'integer))
1231 ;; The difference of integers is always an integer.
1233 (numeric-type-class result-type))
1234 :format (numeric-type-format result-type)
1235 :low (interval-low result)
1236 :high (interval-high result)))
1237 ;; general contagion
1238 (numeric-contagion x y)))
1240 (defoptimizer (- derive-type) ((x y))
1241 (two-arg-derive-type x y #'--derive-type-aux #'-))
1243 (defun *-derive-type-aux (x y same-arg)
1244 (if (and (numeric-type-real-p x)
1245 (numeric-type-real-p y))
1247 ;; (* X X) is always positive, so take care to do it right.
1249 (interval-sqr (numeric-type->interval x))
1250 (interval-mul (numeric-type->interval x)
1251 (numeric-type->interval y))))
1252 (result-type (numeric-contagion x y)))
1253 ;; If the result type is a float, we need to be sure to coerce
1254 ;; the bounds into the correct type.
1255 (when (eq (numeric-type-class result-type) 'float)
1256 (setf result (interval-func
1258 (coerce x (or (numeric-type-format result-type)
1262 :class (if (and (eq (numeric-type-class x) 'integer)
1263 (eq (numeric-type-class y) 'integer))
1264 ;; The product of integers is always an integer.
1266 (numeric-type-class result-type))
1267 :format (numeric-type-format result-type)
1268 :low (interval-low result)
1269 :high (interval-high result)))
1270 (numeric-contagion x y)))
1272 (defoptimizer (* derive-type) ((x y))
1273 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1275 (defun /-derive-type-aux (x y same-arg)
1276 (if (and (numeric-type-real-p x)
1277 (numeric-type-real-p y))
1279 ;; (/ X X) is always 1, except if X can contain 0. In
1280 ;; that case, we shouldn't optimize the division away
1281 ;; because we want 0/0 to signal an error.
1283 (not (interval-contains-p
1284 0 (interval-closure (numeric-type->interval y)))))
1285 (make-interval :low 1 :high 1)
1286 (interval-div (numeric-type->interval x)
1287 (numeric-type->interval y))))
1288 (result-type (numeric-contagion x y)))
1289 ;; If the result type is a float, we need to be sure to coerce
1290 ;; the bounds into the correct type.
1291 (when (eq (numeric-type-class result-type) 'float)
1292 (setf result (interval-func
1294 (coerce x (or (numeric-type-format result-type)
1297 (make-numeric-type :class (numeric-type-class result-type)
1298 :format (numeric-type-format result-type)
1299 :low (interval-low result)
1300 :high (interval-high result)))
1301 (numeric-contagion x y)))
1303 (defoptimizer (/ derive-type) ((x y))
1304 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1308 (defun ash-derive-type-aux (n-type shift same-arg)
1309 (declare (ignore same-arg))
1310 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1311 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1312 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1313 ;; two bignums yielding zero) and it's hard to avoid that
1314 ;; calculation in here.
1315 #+(and cmu sb-xc-host)
1316 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1317 (typep (numeric-type-high n-type) 'bignum))
1318 (or (typep (numeric-type-low shift) 'bignum)
1319 (typep (numeric-type-high shift) 'bignum)))
1320 (return-from ash-derive-type-aux *universal-type*))
1321 (flet ((ash-outer (n s)
1322 (when (and (fixnump s)
1324 (> s sb!xc:most-negative-fixnum))
1326 ;; KLUDGE: The bare 64's here should be related to
1327 ;; symbolic machine word size values somehow.
1330 (if (and (fixnump s)
1331 (> s sb!xc:most-negative-fixnum))
1333 (if (minusp n) -1 0))))
1334 (or (and (csubtypep n-type (specifier-type 'integer))
1335 (csubtypep shift (specifier-type 'integer))
1336 (let ((n-low (numeric-type-low n-type))
1337 (n-high (numeric-type-high n-type))
1338 (s-low (numeric-type-low shift))
1339 (s-high (numeric-type-high shift)))
1340 (make-numeric-type :class 'integer :complexp :real
1343 (ash-outer n-low s-high)
1344 (ash-inner n-low s-low)))
1347 (ash-inner n-high s-low)
1348 (ash-outer n-high s-high))))))
1351 (defoptimizer (ash derive-type) ((n shift))
1352 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1354 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1355 (macrolet ((frob (fun)
1356 `#'(lambda (type type2)
1357 (declare (ignore type2))
1358 (let ((lo (numeric-type-low type))
1359 (hi (numeric-type-high type)))
1360 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1362 (defoptimizer (%negate derive-type) ((num))
1363 (derive-integer-type num num (frob -))))
1365 (defoptimizer (lognot derive-type) ((int))
1366 (derive-integer-type int int
1367 (lambda (type type2)
1368 (declare (ignore type2))
1369 (let ((lo (numeric-type-low type))
1370 (hi (numeric-type-high type)))
1371 (values (if hi (lognot hi) nil)
1372 (if lo (lognot lo) nil)
1373 (numeric-type-class type)
1374 (numeric-type-format type))))))
1376 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1377 (defoptimizer (%negate derive-type) ((num))
1378 (flet ((negate-bound (b)
1380 (set-bound (- (type-bound-number b))
1382 (one-arg-derive-type num
1384 (modified-numeric-type
1386 :low (negate-bound (numeric-type-high type))
1387 :high (negate-bound (numeric-type-low type))))
1390 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1391 (defoptimizer (abs derive-type) ((num))
1392 (let ((type (continuation-type num)))
1393 (if (and (numeric-type-p type)
1394 (eq (numeric-type-class type) 'integer)
1395 (eq (numeric-type-complexp type) :real))
1396 (let ((lo (numeric-type-low type))
1397 (hi (numeric-type-high type)))
1398 (make-numeric-type :class 'integer :complexp :real
1399 :low (cond ((and hi (minusp hi))
1405 :high (if (and hi lo)
1406 (max (abs hi) (abs lo))
1408 (numeric-contagion type type))))
1410 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1411 (defun abs-derive-type-aux (type)
1412 (cond ((eq (numeric-type-complexp type) :complex)
1413 ;; The absolute value of a complex number is always a
1414 ;; non-negative float.
1415 (let* ((format (case (numeric-type-class type)
1416 ((integer rational) 'single-float)
1417 (t (numeric-type-format type))))
1418 (bound-format (or format 'float)))
1419 (make-numeric-type :class 'float
1422 :low (coerce 0 bound-format)
1425 ;; The absolute value of a real number is a non-negative real
1426 ;; of the same type.
1427 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1428 (class (numeric-type-class type))
1429 (format (numeric-type-format type))
1430 (bound-type (or format class 'real)))
1435 :low (coerce-numeric-bound (interval-low abs-bnd) bound-type)
1436 :high (coerce-numeric-bound
1437 (interval-high abs-bnd) bound-type))))))
1439 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1440 (defoptimizer (abs derive-type) ((num))
1441 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1443 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1444 (defoptimizer (truncate derive-type) ((number divisor))
1445 (let ((number-type (continuation-type number))
1446 (divisor-type (continuation-type divisor))
1447 (integer-type (specifier-type 'integer)))
1448 (if (and (numeric-type-p number-type)
1449 (csubtypep number-type integer-type)
1450 (numeric-type-p divisor-type)
1451 (csubtypep divisor-type integer-type))
1452 (let ((number-low (numeric-type-low number-type))
1453 (number-high (numeric-type-high number-type))
1454 (divisor-low (numeric-type-low divisor-type))
1455 (divisor-high (numeric-type-high divisor-type)))
1456 (values-specifier-type
1457 `(values ,(integer-truncate-derive-type number-low number-high
1458 divisor-low divisor-high)
1459 ,(integer-rem-derive-type number-low number-high
1460 divisor-low divisor-high))))
1463 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1466 (defun rem-result-type (number-type divisor-type)
1467 ;; Figure out what the remainder type is. The remainder is an
1468 ;; integer if both args are integers; a rational if both args are
1469 ;; rational; and a float otherwise.
1470 (cond ((and (csubtypep number-type (specifier-type 'integer))
1471 (csubtypep divisor-type (specifier-type 'integer)))
1473 ((and (csubtypep number-type (specifier-type 'rational))
1474 (csubtypep divisor-type (specifier-type 'rational)))
1476 ((and (csubtypep number-type (specifier-type 'float))
1477 (csubtypep divisor-type (specifier-type 'float)))
1478 ;; Both are floats so the result is also a float, of
1479 ;; the largest type.
1480 (or (float-format-max (numeric-type-format number-type)
1481 (numeric-type-format divisor-type))
1483 ((and (csubtypep number-type (specifier-type 'float))
1484 (csubtypep divisor-type (specifier-type 'rational)))
1485 ;; One of the arguments is a float and the other is a
1486 ;; rational. The remainder is a float of the same
1488 (or (numeric-type-format number-type) 'float))
1489 ((and (csubtypep divisor-type (specifier-type 'float))
1490 (csubtypep number-type (specifier-type 'rational)))
1491 ;; One of the arguments is a float and the other is a
1492 ;; rational. The remainder is a float of the same
1494 (or (numeric-type-format divisor-type) 'float))
1496 ;; Some unhandled combination. This usually means both args
1497 ;; are REAL so the result is a REAL.
1500 (defun truncate-derive-type-quot (number-type divisor-type)
1501 (let* ((rem-type (rem-result-type number-type divisor-type))
1502 (number-interval (numeric-type->interval number-type))
1503 (divisor-interval (numeric-type->interval divisor-type)))
1504 ;;(declare (type (member '(integer rational float)) rem-type))
1505 ;; We have real numbers now.
1506 (cond ((eq rem-type 'integer)
1507 ;; Since the remainder type is INTEGER, both args are
1509 (let* ((res (integer-truncate-derive-type
1510 (interval-low number-interval)
1511 (interval-high number-interval)
1512 (interval-low divisor-interval)
1513 (interval-high divisor-interval))))
1514 (specifier-type (if (listp res) res 'integer))))
1516 (let ((quot (truncate-quotient-bound
1517 (interval-div number-interval
1518 divisor-interval))))
1519 (specifier-type `(integer ,(or (interval-low quot) '*)
1520 ,(or (interval-high quot) '*))))))))
1522 (defun truncate-derive-type-rem (number-type divisor-type)
1523 (let* ((rem-type (rem-result-type number-type divisor-type))
1524 (number-interval (numeric-type->interval number-type))
1525 (divisor-interval (numeric-type->interval divisor-type))
1526 (rem (truncate-rem-bound number-interval divisor-interval)))
1527 ;;(declare (type (member '(integer rational float)) rem-type))
1528 ;; We have real numbers now.
1529 (cond ((eq rem-type 'integer)
1530 ;; Since the remainder type is INTEGER, both args are
1532 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1533 ,(or (interval-high rem) '*))))
1535 (multiple-value-bind (class format)
1538 (values 'integer nil))
1540 (values 'rational nil))
1541 ((or single-float double-float #!+long-float long-float)
1542 (values 'float rem-type))
1544 (values 'float nil))
1547 (when (member rem-type '(float single-float double-float
1548 #!+long-float long-float))
1549 (setf rem (interval-func #'(lambda (x)
1550 (coerce x rem-type))
1552 (make-numeric-type :class class
1554 :low (interval-low rem)
1555 :high (interval-high rem)))))))
1557 (defun truncate-derive-type-quot-aux (num div same-arg)
1558 (declare (ignore same-arg))
1559 (if (and (numeric-type-real-p num)
1560 (numeric-type-real-p div))
1561 (truncate-derive-type-quot num div)
1564 (defun truncate-derive-type-rem-aux (num div same-arg)
1565 (declare (ignore same-arg))
1566 (if (and (numeric-type-real-p num)
1567 (numeric-type-real-p div))
1568 (truncate-derive-type-rem num div)
1571 (defoptimizer (truncate derive-type) ((number divisor))
1572 (let ((quot (two-arg-derive-type number divisor
1573 #'truncate-derive-type-quot-aux #'truncate))
1574 (rem (two-arg-derive-type number divisor
1575 #'truncate-derive-type-rem-aux #'rem)))
1576 (when (and quot rem)
1577 (make-values-type :required (list quot rem)))))
1579 (defun ftruncate-derive-type-quot (number-type divisor-type)
1580 ;; The bounds are the same as for truncate. However, the first
1581 ;; result is a float of some type. We need to determine what that
1582 ;; type is. Basically it's the more contagious of the two types.
1583 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1584 (res-type (numeric-contagion number-type divisor-type)))
1585 (make-numeric-type :class 'float
1586 :format (numeric-type-format res-type)
1587 :low (numeric-type-low q-type)
1588 :high (numeric-type-high q-type))))
1590 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1591 (declare (ignore same-arg))
1592 (if (and (numeric-type-real-p n)
1593 (numeric-type-real-p d))
1594 (ftruncate-derive-type-quot n d)
1597 (defoptimizer (ftruncate derive-type) ((number divisor))
1599 (two-arg-derive-type number divisor
1600 #'ftruncate-derive-type-quot-aux #'ftruncate))
1601 (rem (two-arg-derive-type number divisor
1602 #'truncate-derive-type-rem-aux #'rem)))
1603 (when (and quot rem)
1604 (make-values-type :required (list quot rem)))))
1606 (defun %unary-truncate-derive-type-aux (number)
1607 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1609 (defoptimizer (%unary-truncate derive-type) ((number))
1610 (one-arg-derive-type number
1611 #'%unary-truncate-derive-type-aux
1614 ;;; Define optimizers for FLOOR and CEILING.
1616 ((def (name q-name r-name)
1617 (let ((q-aux (symbolicate q-name "-AUX"))
1618 (r-aux (symbolicate r-name "-AUX")))
1620 ;; Compute type of quotient (first) result.
1621 (defun ,q-aux (number-type divisor-type)
1622 (let* ((number-interval
1623 (numeric-type->interval number-type))
1625 (numeric-type->interval divisor-type))
1626 (quot (,q-name (interval-div number-interval
1627 divisor-interval))))
1628 (specifier-type `(integer ,(or (interval-low quot) '*)
1629 ,(or (interval-high quot) '*)))))
1630 ;; Compute type of remainder.
1631 (defun ,r-aux (number-type divisor-type)
1632 (let* ((divisor-interval
1633 (numeric-type->interval divisor-type))
1634 (rem (,r-name divisor-interval))
1635 (result-type (rem-result-type number-type divisor-type)))
1636 (multiple-value-bind (class format)
1639 (values 'integer nil))
1641 (values 'rational nil))
1642 ((or single-float double-float #!+long-float long-float)
1643 (values 'float result-type))
1645 (values 'float nil))
1648 (when (member result-type '(float single-float double-float
1649 #!+long-float long-float))
1650 ;; Make sure that the limits on the interval have
1652 (setf rem (interval-func (lambda (x)
1653 (coerce x result-type))
1655 (make-numeric-type :class class
1657 :low (interval-low rem)
1658 :high (interval-high rem)))))
1659 ;; the optimizer itself
1660 (defoptimizer (,name derive-type) ((number divisor))
1661 (flet ((derive-q (n d same-arg)
1662 (declare (ignore same-arg))
1663 (if (and (numeric-type-real-p n)
1664 (numeric-type-real-p d))
1667 (derive-r (n d same-arg)
1668 (declare (ignore same-arg))
1669 (if (and (numeric-type-real-p n)
1670 (numeric-type-real-p d))
1673 (let ((quot (two-arg-derive-type
1674 number divisor #'derive-q #',name))
1675 (rem (two-arg-derive-type
1676 number divisor #'derive-r #'mod)))
1677 (when (and quot rem)
1678 (make-values-type :required (list quot rem))))))))))
1680 (def floor floor-quotient-bound floor-rem-bound)
1681 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1683 ;;; Define optimizers for FFLOOR and FCEILING
1684 (macrolet ((def (name q-name r-name)
1685 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1686 (r-aux (symbolicate r-name "-AUX")))
1688 ;; Compute type of quotient (first) result.
1689 (defun ,q-aux (number-type divisor-type)
1690 (let* ((number-interval
1691 (numeric-type->interval number-type))
1693 (numeric-type->interval divisor-type))
1694 (quot (,q-name (interval-div number-interval
1696 (res-type (numeric-contagion number-type
1699 :class (numeric-type-class res-type)
1700 :format (numeric-type-format res-type)
1701 :low (interval-low quot)
1702 :high (interval-high quot))))
1704 (defoptimizer (,name derive-type) ((number divisor))
1705 (flet ((derive-q (n d same-arg)
1706 (declare (ignore same-arg))
1707 (if (and (numeric-type-real-p n)
1708 (numeric-type-real-p d))
1711 (derive-r (n d same-arg)
1712 (declare (ignore same-arg))
1713 (if (and (numeric-type-real-p n)
1714 (numeric-type-real-p d))
1717 (let ((quot (two-arg-derive-type
1718 number divisor #'derive-q #',name))
1719 (rem (two-arg-derive-type
1720 number divisor #'derive-r #'mod)))
1721 (when (and quot rem)
1722 (make-values-type :required (list quot rem))))))))))
1724 (def ffloor floor-quotient-bound floor-rem-bound)
1725 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1727 ;;; functions to compute the bounds on the quotient and remainder for
1728 ;;; the FLOOR function
1729 (defun floor-quotient-bound (quot)
1730 ;; Take the floor of the quotient and then massage it into what we
1732 (let ((lo (interval-low quot))
1733 (hi (interval-high quot)))
1734 ;; Take the floor of the lower bound. The result is always a
1735 ;; closed lower bound.
1737 (floor (type-bound-number lo))
1739 ;; For the upper bound, we need to be careful.
1742 ;; An open bound. We need to be careful here because
1743 ;; the floor of '(10.0) is 9, but the floor of
1745 (multiple-value-bind (q r) (floor (first hi))
1750 ;; A closed bound, so the answer is obvious.
1754 (make-interval :low lo :high hi)))
1755 (defun floor-rem-bound (div)
1756 ;; The remainder depends only on the divisor. Try to get the
1757 ;; correct sign for the remainder if we can.
1758 (case (interval-range-info div)
1760 ;; The divisor is always positive.
1761 (let ((rem (interval-abs div)))
1762 (setf (interval-low rem) 0)
1763 (when (and (numberp (interval-high rem))
1764 (not (zerop (interval-high rem))))
1765 ;; The remainder never contains the upper bound. However,
1766 ;; watch out for the case where the high limit is zero!
1767 (setf (interval-high rem) (list (interval-high rem))))
1770 ;; The divisor is always negative.
1771 (let ((rem (interval-neg (interval-abs div))))
1772 (setf (interval-high rem) 0)
1773 (when (numberp (interval-low rem))
1774 ;; The remainder never contains the lower bound.
1775 (setf (interval-low rem) (list (interval-low rem))))
1778 ;; The divisor can be positive or negative. All bets off. The
1779 ;; magnitude of remainder is the maximum value of the divisor.
1780 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1781 ;; The bound never reaches the limit, so make the interval open.
1782 (make-interval :low (if limit
1785 :high (list limit))))))
1787 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
1788 => #S(INTERVAL :LOW 0 :HIGH 10)
1789 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1790 => #S(INTERVAL :LOW 0 :HIGH 10)
1791 (floor-quotient-bound (make-interval :low 0.3 :high 10))
1792 => #S(INTERVAL :LOW 0 :HIGH 10)
1793 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
1794 => #S(INTERVAL :LOW 0 :HIGH 9)
1795 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
1796 => #S(INTERVAL :LOW 0 :HIGH 10)
1797 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
1798 => #S(INTERVAL :LOW 0 :HIGH 10)
1799 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1800 => #S(INTERVAL :LOW -2 :HIGH 10)
1801 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1802 => #S(INTERVAL :LOW -1 :HIGH 10)
1803 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
1804 => #S(INTERVAL :LOW -1 :HIGH 10)
1806 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
1807 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1808 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
1809 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1810 (floor-rem-bound (make-interval :low -10 :high -2.3))
1811 #S(INTERVAL :LOW (-10) :HIGH 0)
1812 (floor-rem-bound (make-interval :low 0.3 :high 10))
1813 => #S(INTERVAL :LOW 0 :HIGH '(10))
1814 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
1815 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
1816 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
1817 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1820 ;;; same functions for CEILING
1821 (defun ceiling-quotient-bound (quot)
1822 ;; Take the ceiling of the quotient and then massage it into what we
1824 (let ((lo (interval-low quot))
1825 (hi (interval-high quot)))
1826 ;; Take the ceiling of the upper bound. The result is always a
1827 ;; closed upper bound.
1829 (ceiling (type-bound-number hi))
1831 ;; For the lower bound, we need to be careful.
1834 ;; An open bound. We need to be careful here because
1835 ;; the ceiling of '(10.0) is 11, but the ceiling of
1837 (multiple-value-bind (q r) (ceiling (first lo))
1842 ;; A closed bound, so the answer is obvious.
1846 (make-interval :low lo :high hi)))
1847 (defun ceiling-rem-bound (div)
1848 ;; The remainder depends only on the divisor. Try to get the
1849 ;; correct sign for the remainder if we can.
1850 (case (interval-range-info div)
1852 ;; Divisor is always positive. The remainder is negative.
1853 (let ((rem (interval-neg (interval-abs div))))
1854 (setf (interval-high rem) 0)
1855 (when (and (numberp (interval-low rem))
1856 (not (zerop (interval-low rem))))
1857 ;; The remainder never contains the upper bound. However,
1858 ;; watch out for the case when the upper bound is zero!
1859 (setf (interval-low rem) (list (interval-low rem))))
1862 ;; Divisor is always negative. The remainder is positive
1863 (let ((rem (interval-abs div)))
1864 (setf (interval-low rem) 0)
1865 (when (numberp (interval-high rem))
1866 ;; The remainder never contains the lower bound.
1867 (setf (interval-high rem) (list (interval-high rem))))
1870 ;; The divisor can be positive or negative. All bets off. The
1871 ;; magnitude of remainder is the maximum value of the divisor.
1872 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1873 ;; The bound never reaches the limit, so make the interval open.
1874 (make-interval :low (if limit
1877 :high (list limit))))))
1880 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
1881 => #S(INTERVAL :LOW 1 :HIGH 11)
1882 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1883 => #S(INTERVAL :LOW 1 :HIGH 11)
1884 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
1885 => #S(INTERVAL :LOW 1 :HIGH 10)
1886 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
1887 => #S(INTERVAL :LOW 1 :HIGH 10)
1888 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
1889 => #S(INTERVAL :LOW 1 :HIGH 11)
1890 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
1891 => #S(INTERVAL :LOW 1 :HIGH 11)
1892 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1893 => #S(INTERVAL :LOW -1 :HIGH 11)
1894 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1895 => #S(INTERVAL :LOW 0 :HIGH 11)
1896 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
1897 => #S(INTERVAL :LOW -1 :HIGH 11)
1899 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
1900 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
1901 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
1902 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1903 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
1904 => #S(INTERVAL :LOW 0 :HIGH (10))
1905 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
1906 => #S(INTERVAL :LOW (-10) :HIGH 0)
1907 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
1908 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
1909 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
1910 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1913 (defun truncate-quotient-bound (quot)
1914 ;; For positive quotients, truncate is exactly like floor. For
1915 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
1916 ;; it's the union of the two pieces.
1917 (case (interval-range-info quot)
1920 (floor-quotient-bound quot))
1922 ;; just like CEILING
1923 (ceiling-quotient-bound quot))
1925 ;; Split the interval into positive and negative pieces, compute
1926 ;; the result for each piece and put them back together.
1927 (destructuring-bind (neg pos) (interval-split 0 quot t t)
1928 (interval-merge-pair (ceiling-quotient-bound neg)
1929 (floor-quotient-bound pos))))))
1931 (defun truncate-rem-bound (num div)
1932 ;; This is significantly more complicated than FLOOR or CEILING. We
1933 ;; need both the number and the divisor to determine the range. The
1934 ;; basic idea is to split the ranges of NUM and DEN into positive
1935 ;; and negative pieces and deal with each of the four possibilities
1937 (case (interval-range-info num)
1939 (case (interval-range-info div)
1941 (floor-rem-bound div))
1943 (ceiling-rem-bound div))
1945 (destructuring-bind (neg pos) (interval-split 0 div t t)
1946 (interval-merge-pair (truncate-rem-bound num neg)
1947 (truncate-rem-bound num pos))))))
1949 (case (interval-range-info div)
1951 (ceiling-rem-bound div))
1953 (floor-rem-bound div))
1955 (destructuring-bind (neg pos) (interval-split 0 div t t)
1956 (interval-merge-pair (truncate-rem-bound num neg)
1957 (truncate-rem-bound num pos))))))
1959 (destructuring-bind (neg pos) (interval-split 0 num t t)
1960 (interval-merge-pair (truncate-rem-bound neg div)
1961 (truncate-rem-bound pos div))))))
1964 ;;; Derive useful information about the range. Returns three values:
1965 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
1966 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
1967 ;;; - The abs of the maximal value if there is one, or nil if it is
1969 (defun numeric-range-info (low high)
1970 (cond ((and low (not (minusp low)))
1971 (values '+ low high))
1972 ((and high (not (plusp high)))
1973 (values '- (- high) (if low (- low) nil)))
1975 (values nil 0 (and low high (max (- low) high))))))
1977 (defun integer-truncate-derive-type
1978 (number-low number-high divisor-low divisor-high)
1979 ;; The result cannot be larger in magnitude than the number, but the
1980 ;; sign might change. If we can determine the sign of either the
1981 ;; number or the divisor, we can eliminate some of the cases.
1982 (multiple-value-bind (number-sign number-min number-max)
1983 (numeric-range-info number-low number-high)
1984 (multiple-value-bind (divisor-sign divisor-min divisor-max)
1985 (numeric-range-info divisor-low divisor-high)
1986 (when (and divisor-max (zerop divisor-max))
1987 ;; We've got a problem: guaranteed division by zero.
1988 (return-from integer-truncate-derive-type t))
1989 (when (zerop divisor-min)
1990 ;; We'll assume that they aren't going to divide by zero.
1992 (cond ((and number-sign divisor-sign)
1993 ;; We know the sign of both.
1994 (if (eq number-sign divisor-sign)
1995 ;; Same sign, so the result will be positive.
1996 `(integer ,(if divisor-max
1997 (truncate number-min divisor-max)
2000 (truncate number-max divisor-min)
2002 ;; Different signs, the result will be negative.
2003 `(integer ,(if number-max
2004 (- (truncate number-max divisor-min))
2007 (- (truncate number-min divisor-max))
2009 ((eq divisor-sign '+)
2010 ;; The divisor is positive. Therefore, the number will just
2011 ;; become closer to zero.
2012 `(integer ,(if number-low
2013 (truncate number-low divisor-min)
2016 (truncate number-high divisor-min)
2018 ((eq divisor-sign '-)
2019 ;; The divisor is negative. Therefore, the absolute value of
2020 ;; the number will become closer to zero, but the sign will also
2022 `(integer ,(if number-high
2023 (- (truncate number-high divisor-min))
2026 (- (truncate number-low divisor-min))
2028 ;; The divisor could be either positive or negative.
2030 ;; The number we are dividing has a bound. Divide that by the
2031 ;; smallest posible divisor.
2032 (let ((bound (truncate number-max divisor-min)))
2033 `(integer ,(- bound) ,bound)))
2035 ;; The number we are dividing is unbounded, so we can't tell
2036 ;; anything about the result.
2039 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2040 (defun integer-rem-derive-type
2041 (number-low number-high divisor-low divisor-high)
2042 (if (and divisor-low divisor-high)
2043 ;; We know the range of the divisor, and the remainder must be
2044 ;; smaller than the divisor. We can tell the sign of the
2045 ;; remainer if we know the sign of the number.
2046 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2047 `(integer ,(if (or (null number-low)
2048 (minusp number-low))
2051 ,(if (or (null number-high)
2052 (plusp number-high))
2055 ;; The divisor is potentially either very positive or very
2056 ;; negative. Therefore, the remainer is unbounded, but we might
2057 ;; be able to tell something about the sign from the number.
2058 `(integer ,(if (and number-low (not (minusp number-low)))
2059 ;; The number we are dividing is positive.
2060 ;; Therefore, the remainder must be positive.
2063 ,(if (and number-high (not (plusp number-high)))
2064 ;; The number we are dividing is negative.
2065 ;; Therefore, the remainder must be negative.
2069 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2070 (defoptimizer (random derive-type) ((bound &optional state))
2071 (let ((type (continuation-type bound)))
2072 (when (numeric-type-p type)
2073 (let ((class (numeric-type-class type))
2074 (high (numeric-type-high type))
2075 (format (numeric-type-format type)))
2079 :low (coerce 0 (or format class 'real))
2080 :high (cond ((not high) nil)
2081 ((eq class 'integer) (max (1- high) 0))
2082 ((or (consp high) (zerop high)) high)
2085 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2086 (defun random-derive-type-aux (type)
2087 (let ((class (numeric-type-class type))
2088 (high (numeric-type-high type))
2089 (format (numeric-type-format type)))
2093 :low (coerce 0 (or format class 'real))
2094 :high (cond ((not high) nil)
2095 ((eq class 'integer) (max (1- high) 0))
2096 ((or (consp high) (zerop high)) high)
2099 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2100 (defoptimizer (random derive-type) ((bound &optional state))
2101 (one-arg-derive-type bound #'random-derive-type-aux nil))
2103 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2105 ;;; Return the maximum number of bits an integer of the supplied type
2106 ;;; can take up, or NIL if it is unbounded. The second (third) value
2107 ;;; is T if the integer can be positive (negative) and NIL if not.
2108 ;;; Zero counts as positive.
2109 (defun integer-type-length (type)
2110 (if (numeric-type-p type)
2111 (let ((min (numeric-type-low type))
2112 (max (numeric-type-high type)))
2113 (values (and min max (max (integer-length min) (integer-length max)))
2114 (or (null max) (not (minusp max)))
2115 (or (null min) (minusp min))))
2118 (defun logand-derive-type-aux (x y &optional same-leaf)
2119 (declare (ignore same-leaf))
2120 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2121 (declare (ignore x-pos))
2122 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2123 (declare (ignore y-pos))
2125 ;; X must be positive.
2127 ;; They must both be positive.
2128 (cond ((or (null x-len) (null y-len))
2129 (specifier-type 'unsigned-byte))
2130 ((or (zerop x-len) (zerop y-len))
2131 (specifier-type '(integer 0 0)))
2133 (specifier-type `(unsigned-byte ,(min x-len y-len)))))
2134 ;; X is positive, but Y might be negative.
2136 (specifier-type 'unsigned-byte))
2138 (specifier-type '(integer 0 0)))
2140 (specifier-type `(unsigned-byte ,x-len)))))
2141 ;; X might be negative.
2143 ;; Y must be positive.
2145 (specifier-type 'unsigned-byte))
2147 (specifier-type '(integer 0 0)))
2150 `(unsigned-byte ,y-len))))
2151 ;; Either might be negative.
2152 (if (and x-len y-len)
2153 ;; The result is bounded.
2154 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2155 ;; We can't tell squat about the result.
2156 (specifier-type 'integer)))))))
2158 (defun logior-derive-type-aux (x y &optional same-leaf)
2159 (declare (ignore same-leaf))
2160 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2161 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2163 ((and (not x-neg) (not y-neg))
2164 ;; Both are positive.
2165 (if (and x-len y-len (zerop x-len) (zerop y-len))
2166 (specifier-type '(integer 0 0))
2167 (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2171 ;; X must be negative.
2173 ;; Both are negative. The result is going to be negative
2174 ;; and be the same length or shorter than the smaller.
2175 (if (and x-len y-len)
2177 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2179 (specifier-type '(integer * -1)))
2180 ;; X is negative, but we don't know about Y. The result
2181 ;; will be negative, but no more negative than X.
2183 `(integer ,(or (numeric-type-low x) '*)
2186 ;; X might be either positive or negative.
2188 ;; But Y is negative. The result will be negative.
2190 `(integer ,(or (numeric-type-low y) '*)
2192 ;; We don't know squat about either. It won't get any bigger.
2193 (if (and x-len y-len)
2195 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2197 (specifier-type 'integer))))))))
2199 (defun logxor-derive-type-aux (x y &optional same-leaf)
2200 (declare (ignore same-leaf))
2201 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2202 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2204 ((or (and (not x-neg) (not y-neg))
2205 (and (not x-pos) (not y-pos)))
2206 ;; Either both are negative or both are positive. The result
2207 ;; will be positive, and as long as the longer.
2208 (if (and x-len y-len (zerop x-len) (zerop y-len))
2209 (specifier-type '(integer 0 0))
2210 (specifier-type `(unsigned-byte ,(if (and x-len y-len)
2213 ((or (and (not x-pos) (not y-neg))
2214 (and (not y-neg) (not y-pos)))
2215 ;; Either X is negative and Y is positive of vice-versa. The
2216 ;; result will be negative.
2217 (specifier-type `(integer ,(if (and x-len y-len)
2218 (ash -1 (max x-len y-len))
2221 ;; We can't tell what the sign of the result is going to be.
2222 ;; All we know is that we don't create new bits.
2224 (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2226 (specifier-type 'integer))))))
2228 (macrolet ((deffrob (logfcn)
2229 (let ((fcn-aux (symbolicate logfcn "-DERIVE-TYPE-AUX")))
2230 `(defoptimizer (,logfcn derive-type) ((x y))
2231 (two-arg-derive-type x y #',fcn-aux #',logfcn)))))
2236 ;;;; miscellaneous derive-type methods
2238 (defoptimizer (integer-length derive-type) ((x))
2239 (let ((x-type (continuation-type x)))
2240 (when (and (numeric-type-p x-type)
2241 (csubtypep x-type (specifier-type 'integer)))
2242 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2243 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2244 ;; careful about LO or HI being NIL, though. Also, if 0 is
2245 ;; contained in X, the lower bound is obviously 0.
2246 (flet ((null-or-min (a b)
2247 (and a b (min (integer-length a)
2248 (integer-length b))))
2250 (and a b (max (integer-length a)
2251 (integer-length b)))))
2252 (let* ((min (numeric-type-low x-type))
2253 (max (numeric-type-high x-type))
2254 (min-len (null-or-min min max))
2255 (max-len (null-or-max min max)))
2256 (when (ctypep 0 x-type)
2258 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2260 (defoptimizer (code-char derive-type) ((code))
2261 (specifier-type 'base-char))
2263 (defoptimizer (values derive-type) ((&rest values))
2264 (values-specifier-type
2265 `(values ,@(mapcar (lambda (x)
2266 (type-specifier (continuation-type x)))
2269 ;;;; byte operations
2271 ;;;; We try to turn byte operations into simple logical operations.
2272 ;;;; First, we convert byte specifiers into separate size and position
2273 ;;;; arguments passed to internal %FOO functions. We then attempt to
2274 ;;;; transform the %FOO functions into boolean operations when the
2275 ;;;; size and position are constant and the operands are fixnums.
2277 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2278 ;; expressions that evaluate to the SIZE and POSITION of
2279 ;; the byte-specifier form SPEC. We may wrap a let around
2280 ;; the result of the body to bind some variables.
2282 ;; If the spec is a BYTE form, then bind the vars to the
2283 ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2284 ;; and BYTE-POSITION. The goal of this transformation is to
2285 ;; avoid consing up byte specifiers and then immediately
2286 ;; throwing them away.
2287 (with-byte-specifier ((size-var pos-var spec) &body body)
2288 (once-only ((spec `(macroexpand ,spec))
2290 `(if (and (consp ,spec)
2291 (eq (car ,spec) 'byte)
2292 (= (length ,spec) 3))
2293 (let ((,size-var (second ,spec))
2294 (,pos-var (third ,spec)))
2296 (let ((,size-var `(byte-size ,,temp))
2297 (,pos-var `(byte-position ,,temp)))
2298 `(let ((,,temp ,,spec))
2301 (define-source-transform ldb (spec int)
2302 (with-byte-specifier (size pos spec)
2303 `(%ldb ,size ,pos ,int)))
2305 (define-source-transform dpb (newbyte spec int)
2306 (with-byte-specifier (size pos spec)
2307 `(%dpb ,newbyte ,size ,pos ,int)))
2309 (define-source-transform mask-field (spec int)
2310 (with-byte-specifier (size pos spec)
2311 `(%mask-field ,size ,pos ,int)))
2313 (define-source-transform deposit-field (newbyte spec int)
2314 (with-byte-specifier (size pos spec)
2315 `(%deposit-field ,newbyte ,size ,pos ,int))))
2317 (defoptimizer (%ldb derive-type) ((size posn num))
2318 (let ((size (continuation-type size)))
2319 (if (and (numeric-type-p size)
2320 (csubtypep size (specifier-type 'integer)))
2321 (let ((size-high (numeric-type-high size)))
2322 (if (and size-high (<= size-high sb!vm:n-word-bits))
2323 (specifier-type `(unsigned-byte ,size-high))
2324 (specifier-type 'unsigned-byte)))
2327 (defoptimizer (%mask-field derive-type) ((size posn num))
2328 (let ((size (continuation-type size))
2329 (posn (continuation-type posn)))
2330 (if (and (numeric-type-p size)
2331 (csubtypep size (specifier-type 'integer))
2332 (numeric-type-p posn)
2333 (csubtypep posn (specifier-type 'integer)))
2334 (let ((size-high (numeric-type-high size))
2335 (posn-high (numeric-type-high posn)))
2336 (if (and size-high posn-high
2337 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2338 (specifier-type `(unsigned-byte ,(+ size-high posn-high)))
2339 (specifier-type 'unsigned-byte)))
2342 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2343 (let ((size (continuation-type size))
2344 (posn (continuation-type posn))
2345 (int (continuation-type int)))
2346 (if (and (numeric-type-p size)
2347 (csubtypep size (specifier-type 'integer))
2348 (numeric-type-p posn)
2349 (csubtypep posn (specifier-type 'integer))
2350 (numeric-type-p int)
2351 (csubtypep int (specifier-type 'integer)))
2352 (let ((size-high (numeric-type-high size))
2353 (posn-high (numeric-type-high posn))
2354 (high (numeric-type-high int))
2355 (low (numeric-type-low int)))
2356 (if (and size-high posn-high high low
2357 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2359 (list (if (minusp low) 'signed-byte 'unsigned-byte)
2360 (max (integer-length high)
2361 (integer-length low)
2362 (+ size-high posn-high))))
2366 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2367 (let ((size (continuation-type size))
2368 (posn (continuation-type posn))
2369 (int (continuation-type int)))
2370 (if (and (numeric-type-p size)
2371 (csubtypep size (specifier-type 'integer))
2372 (numeric-type-p posn)
2373 (csubtypep posn (specifier-type 'integer))
2374 (numeric-type-p int)
2375 (csubtypep int (specifier-type 'integer)))
2376 (let ((size-high (numeric-type-high size))
2377 (posn-high (numeric-type-high posn))
2378 (high (numeric-type-high int))
2379 (low (numeric-type-low int)))
2380 (if (and size-high posn-high high low
2381 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2383 (list (if (minusp low) 'signed-byte 'unsigned-byte)
2384 (max (integer-length high)
2385 (integer-length low)
2386 (+ size-high posn-high))))
2390 (deftransform %ldb ((size posn int)
2391 (fixnum fixnum integer)
2392 (unsigned-byte #.sb!vm:n-word-bits))
2393 "convert to inline logical operations"
2394 `(logand (ash int (- posn))
2395 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2396 (- size ,sb!vm:n-word-bits))))
2398 (deftransform %mask-field ((size posn int)
2399 (fixnum fixnum integer)
2400 (unsigned-byte #.sb!vm:n-word-bits))
2401 "convert to inline logical operations"
2403 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2404 (- size ,sb!vm:n-word-bits))
2407 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2408 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2409 ;;; as the result type, as that would allow result types that cover
2410 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2411 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2413 (deftransform %dpb ((new size posn int)
2415 (unsigned-byte #.sb!vm:n-word-bits))
2416 "convert to inline logical operations"
2417 `(let ((mask (ldb (byte size 0) -1)))
2418 (logior (ash (logand new mask) posn)
2419 (logand int (lognot (ash mask posn))))))
2421 (deftransform %dpb ((new size posn int)
2423 (signed-byte #.sb!vm:n-word-bits))
2424 "convert to inline logical operations"
2425 `(let ((mask (ldb (byte size 0) -1)))
2426 (logior (ash (logand new mask) posn)
2427 (logand int (lognot (ash mask posn))))))
2429 (deftransform %deposit-field ((new size posn int)
2431 (unsigned-byte #.sb!vm:n-word-bits))
2432 "convert to inline logical operations"
2433 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2434 (logior (logand new mask)
2435 (logand int (lognot mask)))))
2437 (deftransform %deposit-field ((new size posn int)
2439 (signed-byte #.sb!vm:n-word-bits))
2440 "convert to inline logical operations"
2441 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2442 (logior (logand new mask)
2443 (logand int (lognot mask)))))
2445 ;;; miscellanous numeric transforms
2447 ;;; If a constant appears as the first arg, swap the args.
2448 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
2449 (if (and (constant-continuation-p x)
2450 (not (constant-continuation-p y)))
2451 `(,(continuation-fun-name (basic-combination-fun node))
2453 ,(continuation-value x))
2454 (give-up-ir1-transform)))
2456 (dolist (x '(= char= + * logior logand logxor))
2457 (%deftransform x '(function * *) #'commutative-arg-swap
2458 "place constant arg last"))
2460 ;;; Handle the case of a constant BOOLE-CODE.
2461 (deftransform boole ((op x y) * *)
2462 "convert to inline logical operations"
2463 (unless (constant-continuation-p op)
2464 (give-up-ir1-transform "BOOLE code is not a constant."))
2465 (let ((control (continuation-value op)))
2471 (#.boole-c1 '(lognot x))
2472 (#.boole-c2 '(lognot y))
2473 (#.boole-and '(logand x y))
2474 (#.boole-ior '(logior x y))
2475 (#.boole-xor '(logxor x y))
2476 (#.boole-eqv '(logeqv x y))
2477 (#.boole-nand '(lognand x y))
2478 (#.boole-nor '(lognor x y))
2479 (#.boole-andc1 '(logandc1 x y))
2480 (#.boole-andc2 '(logandc2 x y))
2481 (#.boole-orc1 '(logorc1 x y))
2482 (#.boole-orc2 '(logorc2 x y))
2484 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
2487 ;;;; converting special case multiply/divide to shifts
2489 ;;; If arg is a constant power of two, turn * into a shift.
2490 (deftransform * ((x y) (integer integer) *)
2491 "convert x*2^k to shift"
2492 (unless (constant-continuation-p y)
2493 (give-up-ir1-transform))
2494 (let* ((y (continuation-value y))
2496 (len (1- (integer-length y-abs))))
2497 (unless (= y-abs (ash 1 len))
2498 (give-up-ir1-transform))
2503 ;;; If both arguments and the result are (UNSIGNED-BYTE 32), try to
2504 ;;; come up with a ``better'' multiplication using multiplier
2505 ;;; recoding. There are two different ways the multiplier can be
2506 ;;; recoded. The more obvious is to shift X by the correct amount for
2507 ;;; each bit set in Y and to sum the results. But if there is a string
2508 ;;; of bits that are all set, you can add X shifted by one more then
2509 ;;; the bit position of the first set bit and subtract X shifted by
2510 ;;; the bit position of the last set bit. We can't use this second
2511 ;;; method when the high order bit is bit 31 because shifting by 32
2512 ;;; doesn't work too well.
2513 (deftransform * ((x y)
2514 ((unsigned-byte 32) (unsigned-byte 32))
2516 "recode as shift and add"
2517 (unless (constant-continuation-p y)
2518 (give-up-ir1-transform))
2519 (let ((y (continuation-value y))
2522 (labels ((tub32 (x) `(truly-the (unsigned-byte 32) ,x))
2527 `(+ ,result ,(tub32 next-factor))
2529 (declare (inline add))
2530 (dotimes (bitpos 32)
2532 (when (not (logbitp bitpos y))
2533 (add (if (= (1+ first-one) bitpos)
2534 ;; There is only a single bit in the string.
2536 ;; There are at least two.
2537 `(- ,(tub32 `(ash x ,bitpos))
2538 ,(tub32 `(ash x ,first-one)))))
2539 (setf first-one nil))
2540 (when (logbitp bitpos y)
2541 (setf first-one bitpos))))
2543 (cond ((= first-one 31))
2547 (add `(- ,(tub32 '(ash x 31)) ,(tub32 `(ash x ,first-one))))))
2551 ;;; If arg is a constant power of two, turn FLOOR into a shift and
2552 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
2554 (flet ((frob (y ceil-p)
2555 (unless (constant-continuation-p y)
2556 (give-up-ir1-transform))
2557 (let* ((y (continuation-value y))
2559 (len (1- (integer-length y-abs))))
2560 (unless (= y-abs (ash 1 len))
2561 (give-up-ir1-transform))
2562 (let ((shift (- len))
2564 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
2565 `(let ((x (+ x ,delta)))
2567 `(values (ash (- x) ,shift)
2568 (- (- (logand (- x) ,mask)) ,delta))
2569 `(values (ash x ,shift)
2570 (- (logand x ,mask) ,delta))))))))
2571 (deftransform floor ((x y) (integer integer) *)
2572 "convert division by 2^k to shift"
2574 (deftransform ceiling ((x y) (integer integer) *)
2575 "convert division by 2^k to shift"
2578 ;;; Do the same for MOD.
2579 (deftransform mod ((x y) (integer integer) *)
2580 "convert remainder mod 2^k to LOGAND"
2581 (unless (constant-continuation-p y)
2582 (give-up-ir1-transform))
2583 (let* ((y (continuation-value y))
2585 (len (1- (integer-length y-abs))))
2586 (unless (= y-abs (ash 1 len))
2587 (give-up-ir1-transform))
2588 (let ((mask (1- y-abs)))
2590 `(- (logand (- x) ,mask))
2591 `(logand x ,mask)))))
2593 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
2594 (deftransform truncate ((x y) (integer integer))
2595 "convert division by 2^k to shift"
2596 (unless (constant-continuation-p y)
2597 (give-up-ir1-transform))
2598 (let* ((y (continuation-value y))
2600 (len (1- (integer-length y-abs))))
2601 (unless (= y-abs (ash 1 len))
2602 (give-up-ir1-transform))
2603 (let* ((shift (- len))
2606 (values ,(if (minusp y)
2608 `(- (ash (- x) ,shift)))
2609 (- (logand (- x) ,mask)))
2610 (values ,(if (minusp y)
2611 `(- (ash (- x) ,shift))
2613 (logand x ,mask))))))
2615 ;;; And the same for REM.
2616 (deftransform rem ((x y) (integer integer) *)
2617 "convert remainder mod 2^k to LOGAND"
2618 (unless (constant-continuation-p y)
2619 (give-up-ir1-transform))
2620 (let* ((y (continuation-value y))
2622 (len (1- (integer-length y-abs))))
2623 (unless (= y-abs (ash 1 len))
2624 (give-up-ir1-transform))
2625 (let ((mask (1- y-abs)))
2627 (- (logand (- x) ,mask))
2628 (logand x ,mask)))))
2630 ;;;; arithmetic and logical identity operation elimination
2632 ;;; Flush calls to various arith functions that convert to the
2633 ;;; identity function or a constant.
2634 (macrolet ((def (name identity result)
2635 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
2636 "fold identity operations"
2643 (def logxor -1 (lognot x))
2646 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
2647 ;;; (* 0 -4.0) is -0.0.
2648 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
2649 "convert (- 0 x) to negate"
2651 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
2652 "convert (* x 0) to 0"
2655 ;;; Return T if in an arithmetic op including continuations X and Y,
2656 ;;; the result type is not affected by the type of X. That is, Y is at
2657 ;;; least as contagious as X.
2659 (defun not-more-contagious (x y)
2660 (declare (type continuation x y))
2661 (let ((x (continuation-type x))
2662 (y (continuation-type y)))
2663 (values (type= (numeric-contagion x y)
2664 (numeric-contagion y y)))))
2665 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
2666 ;;; XXX needs more work as valid transforms are missed; some cases are
2667 ;;; specific to particular transform functions so the use of this
2668 ;;; function may need a re-think.
2669 (defun not-more-contagious (x y)
2670 (declare (type continuation x y))
2671 (flet ((simple-numeric-type (num)
2672 (and (numeric-type-p num)
2673 ;; Return non-NIL if NUM is integer, rational, or a float
2674 ;; of some type (but not FLOAT)
2675 (case (numeric-type-class num)
2679 (numeric-type-format num))
2682 (let ((x (continuation-type x))
2683 (y (continuation-type y)))
2684 (if (and (simple-numeric-type x)
2685 (simple-numeric-type y))
2686 (values (type= (numeric-contagion x y)
2687 (numeric-contagion y y)))))))
2691 ;;; If y is not constant, not zerop, or is contagious, or a positive
2692 ;;; float +0.0 then give up.
2693 (deftransform + ((x y) (t (constant-arg t)) *)
2695 (let ((val (continuation-value y)))
2696 (unless (and (zerop val)
2697 (not (and (floatp val) (plusp (float-sign val))))
2698 (not-more-contagious y x))
2699 (give-up-ir1-transform)))
2704 ;;; If y is not constant, not zerop, or is contagious, or a negative
2705 ;;; float -0.0 then give up.
2706 (deftransform - ((x y) (t (constant-arg t)) *)
2708 (let ((val (continuation-value y)))
2709 (unless (and (zerop val)
2710 (not (and (floatp val) (minusp (float-sign val))))
2711 (not-more-contagious y x))
2712 (give-up-ir1-transform)))
2715 ;;; Fold (OP x +/-1)
2716 (macrolet ((def (name result minus-result)
2717 `(deftransform ,name ((x y) (t (constant-arg real)) *)
2718 "fold identity operations"
2719 (let ((val (continuation-value y)))
2720 (unless (and (= (abs val) 1)
2721 (not-more-contagious y x))
2722 (give-up-ir1-transform))
2723 (if (minusp val) ',minus-result ',result)))))
2724 (def * x (%negate x))
2725 (def / x (%negate x))
2726 (def expt x (/ 1 x)))
2728 ;;; Fold (expt x n) into multiplications for small integral values of
2729 ;;; N; convert (expt x 1/2) to sqrt.
2730 (deftransform expt ((x y) (t (constant-arg real)) *)
2731 "recode as multiplication or sqrt"
2732 (let ((val (continuation-value y)))
2733 ;; If Y would cause the result to be promoted to the same type as
2734 ;; Y, we give up. If not, then the result will be the same type
2735 ;; as X, so we can replace the exponentiation with simple
2736 ;; multiplication and division for small integral powers.
2737 (unless (not-more-contagious y x)
2738 (give-up-ir1-transform))
2739 (cond ((zerop val) '(float 1 x))
2740 ((= val 2) '(* x x))
2741 ((= val -2) '(/ (* x x)))
2742 ((= val 3) '(* x x x))
2743 ((= val -3) '(/ (* x x x)))
2744 ((= val 1/2) '(sqrt x))
2745 ((= val -1/2) '(/ (sqrt x)))
2746 (t (give-up-ir1-transform)))))
2748 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
2749 ;;; transformations?
2750 ;;; Perhaps we should have to prove that the denominator is nonzero before
2751 ;;; doing them? -- WHN 19990917
2752 (macrolet ((def (name)
2753 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2760 (macrolet ((def (name)
2761 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2770 ;;;; character operations
2772 (deftransform char-equal ((a b) (base-char base-char))
2774 '(let* ((ac (char-code a))
2776 (sum (logxor ac bc)))
2778 (when (eql sum #x20)
2779 (let ((sum (+ ac bc)))
2780 (and (> sum 161) (< sum 213)))))))
2782 (deftransform char-upcase ((x) (base-char))
2784 '(let ((n-code (char-code x)))
2785 (if (and (> n-code #o140) ; Octal 141 is #\a.
2786 (< n-code #o173)) ; Octal 172 is #\z.
2787 (code-char (logxor #x20 n-code))
2790 (deftransform char-downcase ((x) (base-char))
2792 '(let ((n-code (char-code x)))
2793 (if (and (> n-code 64) ; 65 is #\A.
2794 (< n-code 91)) ; 90 is #\Z.
2795 (code-char (logxor #x20 n-code))
2798 ;;;; equality predicate transforms
2800 ;;; Return true if X and Y are continuations whose only use is a
2801 ;;; reference to the same leaf, and the value of the leaf cannot
2803 (defun same-leaf-ref-p (x y)
2804 (declare (type continuation x y))
2805 (let ((x-use (continuation-use x))
2806 (y-use (continuation-use y)))
2809 (eq (ref-leaf x-use) (ref-leaf y-use))
2810 (constant-reference-p x-use))))
2812 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
2813 ;;; if there is no intersection between the types of the arguments,
2814 ;;; then the result is definitely false.
2815 (deftransform simple-equality-transform ((x y) * *
2817 (cond ((same-leaf-ref-p x y)
2819 ((not (types-equal-or-intersect (continuation-type x)
2820 (continuation-type y)))
2823 (give-up-ir1-transform))))
2826 `(%deftransform ',x '(function * *) #'simple-equality-transform)))
2831 ;;; This is similar to SIMPLE-EQUALITY-PREDICATE, except that we also
2832 ;;; try to convert to a type-specific predicate or EQ:
2833 ;;; -- If both args are characters, convert to CHAR=. This is better than
2834 ;;; just converting to EQ, since CHAR= may have special compilation
2835 ;;; strategies for non-standard representations, etc.
2836 ;;; -- If either arg is definitely not a number, then we can compare
2838 ;;; -- Otherwise, we try to put the arg we know more about second. If X
2839 ;;; is constant then we put it second. If X is a subtype of Y, we put
2840 ;;; it second. These rules make it easier for the back end to match
2841 ;;; these interesting cases.
2842 ;;; -- If Y is a fixnum, then we quietly pass because the back end can
2843 ;;; handle that case, otherwise give an efficiency note.
2844 (deftransform eql ((x y) * *)
2845 "convert to simpler equality predicate"
2846 (let ((x-type (continuation-type x))
2847 (y-type (continuation-type y))
2848 (char-type (specifier-type 'character))
2849 (number-type (specifier-type 'number)))
2850 (cond ((same-leaf-ref-p x y)
2852 ((not (types-equal-or-intersect x-type y-type))
2854 ((and (csubtypep x-type char-type)
2855 (csubtypep y-type char-type))
2857 ((or (not (types-equal-or-intersect x-type number-type))
2858 (not (types-equal-or-intersect y-type number-type)))
2860 ((and (not (constant-continuation-p y))
2861 (or (constant-continuation-p x)
2862 (and (csubtypep x-type y-type)
2863 (not (csubtypep y-type x-type)))))
2866 (give-up-ir1-transform)))))
2868 ;;; Convert to EQL if both args are rational and complexp is specified
2869 ;;; and the same for both.
2870 (deftransform = ((x y) * *)
2872 (let ((x-type (continuation-type x))
2873 (y-type (continuation-type y)))
2874 (if (and (csubtypep x-type (specifier-type 'number))
2875 (csubtypep y-type (specifier-type 'number)))
2876 (cond ((or (and (csubtypep x-type (specifier-type 'float))
2877 (csubtypep y-type (specifier-type 'float)))
2878 (and (csubtypep x-type (specifier-type '(complex float)))
2879 (csubtypep y-type (specifier-type '(complex float)))))
2880 ;; They are both floats. Leave as = so that -0.0 is
2881 ;; handled correctly.
2882 (give-up-ir1-transform))
2883 ((or (and (csubtypep x-type (specifier-type 'rational))
2884 (csubtypep y-type (specifier-type 'rational)))
2885 (and (csubtypep x-type
2886 (specifier-type '(complex rational)))
2888 (specifier-type '(complex rational)))))
2889 ;; They are both rationals and complexp is the same.
2893 (give-up-ir1-transform
2894 "The operands might not be the same type.")))
2895 (give-up-ir1-transform
2896 "The operands might not be the same type."))))
2898 ;;; If CONT's type is a numeric type, then return the type, otherwise
2899 ;;; GIVE-UP-IR1-TRANSFORM.
2900 (defun numeric-type-or-lose (cont)
2901 (declare (type continuation cont))
2902 (let ((res (continuation-type cont)))
2903 (unless (numeric-type-p res) (give-up-ir1-transform))
2906 ;;; See whether we can statically determine (< X Y) using type
2907 ;;; information. If X's high bound is < Y's low, then X < Y.
2908 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
2909 ;;; NIL). If not, at least make sure any constant arg is second.
2911 ;;; FIXME: Why should constant argument be second? It would be nice to
2912 ;;; find out and explain.
2913 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2914 (defun ir1-transform-< (x y first second inverse)
2915 (if (same-leaf-ref-p x y)
2917 (let* ((x-type (numeric-type-or-lose x))
2918 (x-lo (numeric-type-low x-type))
2919 (x-hi (numeric-type-high x-type))
2920 (y-type (numeric-type-or-lose y))
2921 (y-lo (numeric-type-low y-type))
2922 (y-hi (numeric-type-high y-type)))
2923 (cond ((and x-hi y-lo (< x-hi y-lo))
2925 ((and y-hi x-lo (>= x-lo y-hi))
2927 ((and (constant-continuation-p first)
2928 (not (constant-continuation-p second)))
2931 (give-up-ir1-transform))))))
2932 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2933 (defun ir1-transform-< (x y first second inverse)
2934 (if (same-leaf-ref-p x y)
2936 (let ((xi (numeric-type->interval (numeric-type-or-lose x)))
2937 (yi (numeric-type->interval (numeric-type-or-lose y))))
2938 (cond ((interval-< xi yi)
2940 ((interval->= xi yi)
2942 ((and (constant-continuation-p first)
2943 (not (constant-continuation-p second)))
2946 (give-up-ir1-transform))))))
2948 (deftransform < ((x y) (integer integer) *)
2949 (ir1-transform-< x y x y '>))
2951 (deftransform > ((x y) (integer integer) *)
2952 (ir1-transform-< y x x y '<))
2954 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2955 (deftransform < ((x y) (float float) *)
2956 (ir1-transform-< x y x y '>))
2958 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2959 (deftransform > ((x y) (float float) *)
2960 (ir1-transform-< y x x y '<))
2962 ;;;; converting N-arg comparisons
2964 ;;;; We convert calls to N-arg comparison functions such as < into
2965 ;;;; two-arg calls. This transformation is enabled for all such
2966 ;;;; comparisons in this file. If any of these predicates are not
2967 ;;;; open-coded, then the transformation should be removed at some
2968 ;;;; point to avoid pessimization.
2970 ;;; This function is used for source transformation of N-arg
2971 ;;; comparison functions other than inequality. We deal both with
2972 ;;; converting to two-arg calls and inverting the sense of the test,
2973 ;;; if necessary. If the call has two args, then we pass or return a
2974 ;;; negated test as appropriate. If it is a degenerate one-arg call,
2975 ;;; then we transform to code that returns true. Otherwise, we bind
2976 ;;; all the arguments and expand into a bunch of IFs.
2977 (declaim (ftype (function (symbol list boolean) *) multi-compare))
2978 (defun multi-compare (predicate args not-p)
2979 (let ((nargs (length args)))
2980 (cond ((< nargs 1) (values nil t))
2981 ((= nargs 1) `(progn ,@args t))
2984 `(if (,predicate ,(first args) ,(second args)) nil t)
2987 (do* ((i (1- nargs) (1- i))
2989 (current (gensym) (gensym))
2990 (vars (list current) (cons current vars))
2992 `(if (,predicate ,current ,last)
2994 `(if (,predicate ,current ,last)
2997 `((lambda ,vars ,result) . ,args)))))))
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 nil))
3002 (define-source-transform <= (&rest args) (multi-compare '> args t))
3003 (define-source-transform >= (&rest args) (multi-compare '< args t))
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 nil))
3008 (define-source-transform char<= (&rest args) (multi-compare 'char> args t))
3009 (define-source-transform char>= (&rest args) (multi-compare 'char< args t))
3011 (define-source-transform char-equal (&rest args)
3012 (multi-compare 'char-equal args nil))
3013 (define-source-transform char-lessp (&rest args)
3014 (multi-compare 'char-lessp args nil))
3015 (define-source-transform char-greaterp (&rest args)
3016 (multi-compare 'char-greaterp args nil))
3017 (define-source-transform char-not-greaterp (&rest args)
3018 (multi-compare 'char-greaterp args t))
3019 (define-source-transform char-not-lessp (&rest args)
3020 (multi-compare 'char-lessp args t))
3022 ;;; This function does source transformation of N-arg inequality
3023 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3024 ;;; arg cases. If there are more than two args, then we expand into
3025 ;;; the appropriate n^2 comparisons only when speed is important.
3026 (declaim (ftype (function (symbol list) *) multi-not-equal))
3027 (defun multi-not-equal (predicate args)
3028 (let ((nargs (length args)))
3029 (cond ((< nargs 1) (values nil t))
3030 ((= nargs 1) `(progn ,@args t))
3032 `(if (,predicate ,(first args) ,(second args)) nil t))
3033 ((not (policy *lexenv*
3034 (and (>= speed space)
3035 (>= speed compilation-speed))))
3038 (let ((vars (make-gensym-list nargs)))
3039 (do ((var vars next)
3040 (next (cdr vars) (cdr next))
3043 `((lambda ,vars ,result) . ,args))
3044 (let ((v1 (first var)))
3046 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3048 (define-source-transform /= (&rest args) (multi-not-equal '= args))
3049 (define-source-transform char/= (&rest args) (multi-not-equal 'char= args))
3050 (define-source-transform char-not-equal (&rest args)
3051 (multi-not-equal 'char-equal args))
3053 ;;; FIXME: can go away once bug 194 is fixed and we can use (THE REAL X)
3055 (defun error-not-a-real (x)
3056 (error 'simple-type-error
3058 :expected-type 'real
3059 :format-control "not a REAL: ~S"
3060 :format-arguments (list x)))
3062 ;;; Expand MAX and MIN into the obvious comparisons.
3063 (define-source-transform max (arg0 &rest rest)
3064 (once-only ((arg0 arg0))
3066 `(values (the real ,arg0))
3067 `(let ((maxrest (max ,@rest)))
3068 (if (> ,arg0 maxrest) ,arg0 maxrest)))))
3069 (define-source-transform min (arg0 &rest rest)
3070 (once-only ((arg0 arg0))
3072 `(values (the real ,arg0))
3073 `(let ((minrest (min ,@rest)))
3074 (if (< ,arg0 minrest) ,arg0 minrest)))))
3076 ;;;; converting N-arg arithmetic functions
3078 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3079 ;;;; versions, and degenerate cases are flushed.
3081 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3082 (declaim (ftype (function (symbol t list) list) associate-args))
3083 (defun associate-args (function first-arg more-args)
3084 (let ((next (rest more-args))
3085 (arg (first more-args)))
3087 `(,function ,first-arg ,arg)
3088 (associate-args function `(,function ,first-arg ,arg) next))))
3090 ;;; Do source transformations for transitive functions such as +.
3091 ;;; One-arg cases are replaced with the arg and zero arg cases with
3092 ;;; the identity. ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3093 ;;; ensure (with THE) that the argument in one-argument calls is.
3094 (defun source-transform-transitive (fun args identity
3095 &optional one-arg-result-type)
3096 (declare (symbol fun leaf-fun) (list args))
3099 (1 (if one-arg-result-type
3100 `(values (the ,one-arg-result-type ,(first args)))
3101 `(values ,(first args))))
3104 (associate-args fun (first args) (rest args)))))
3106 (define-source-transform + (&rest args)
3107 (source-transform-transitive '+ args 0 'number))
3108 (define-source-transform * (&rest args)
3109 (source-transform-transitive '* args 1 'number))
3110 (define-source-transform logior (&rest args)
3111 (source-transform-transitive 'logior args 0 'integer))
3112 (define-source-transform logxor (&rest args)
3113 (source-transform-transitive 'logxor args 0 'integer))
3114 (define-source-transform logand (&rest args)
3115 (source-transform-transitive 'logand args -1 'integer))
3117 (define-source-transform logeqv (&rest args)
3118 (if (evenp (length args))
3119 `(lognot (logxor ,@args))
3122 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3123 ;;; because when they are given one argument, they return its absolute
3126 (define-source-transform gcd (&rest args)
3129 (1 `(abs (the integer ,(first args))))
3131 (t (associate-args 'gcd (first args) (rest args)))))
3133 (define-source-transform lcm (&rest args)
3136 (1 `(abs (the integer ,(first args))))
3138 (t (associate-args 'lcm (first args) (rest args)))))
3140 ;;; Do source transformations for intransitive n-arg functions such as
3141 ;;; /. With one arg, we form the inverse. With two args we pass.
3142 ;;; Otherwise we associate into two-arg calls.
3143 (declaim (ftype (function (symbol list t)
3144 (values list &optional (member nil t)))
3145 source-transform-intransitive))
3146 (defun source-transform-intransitive (function args inverse)
3148 ((0 2) (values nil t))
3149 (1 `(,@inverse ,(first args)))
3150 (t (associate-args function (first args) (rest args)))))
3152 (define-source-transform - (&rest args)
3153 (source-transform-intransitive '- args '(%negate)))
3154 (define-source-transform / (&rest args)
3155 (source-transform-intransitive '/ args '(/ 1)))
3157 ;;;; transforming APPLY
3159 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3160 ;;; only needs to understand one kind of variable-argument call. It is
3161 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3162 (define-source-transform apply (fun arg &rest more-args)
3163 (let ((args (cons arg more-args)))
3164 `(multiple-value-call ,fun
3165 ,@(mapcar (lambda (x)
3168 (values-list ,(car (last args))))))
3170 ;;;; transforming FORMAT
3172 ;;;; If the control string is a compile-time constant, then replace it
3173 ;;;; with a use of the FORMATTER macro so that the control string is
3174 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3175 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3176 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3178 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3179 :policy (> speed space))
3180 (unless (constant-continuation-p control)
3181 (give-up-ir1-transform "The control string is not a constant."))
3182 (let ((arg-names (make-gensym-list (length args))))
3183 `(lambda (dest control ,@arg-names)
3184 (declare (ignore control))
3185 (format dest (formatter ,(continuation-value control)) ,@arg-names))))
3187 (deftransform format ((stream control &rest args) (stream function &rest t) *
3188 :policy (> speed space))
3189 (let ((arg-names (make-gensym-list (length args))))
3190 `(lambda (stream control ,@arg-names)
3191 (funcall control stream ,@arg-names)
3194 (deftransform format ((tee control &rest args) ((member t) function &rest t) *
3195 :policy (> speed space))
3196 (let ((arg-names (make-gensym-list (length args))))
3197 `(lambda (tee control ,@arg-names)
3198 (declare (ignore tee))
3199 (funcall control *standard-output* ,@arg-names)
3202 (defoptimizer (coerce derive-type) ((value type))
3204 ((constant-continuation-p type)
3205 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3206 ;; but dealing with the niggle that complex canonicalization gets
3207 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3209 (let* ((specifier (continuation-value type))
3210 (result-typeoid (careful-specifier-type specifier)))
3212 ((null result-typeoid) nil)
3213 ((csubtypep result-typeoid (specifier-type 'number))
3214 ;; the difficult case: we have to cope with ANSI 12.1.5.3
3215 ;; Rule of Canonical Representation for Complex Rationals,
3216 ;; which is a truly nasty delivery to field.
3218 ((csubtypep result-typeoid (specifier-type 'real))
3219 ;; cleverness required here: it would be nice to deduce
3220 ;; that something of type (INTEGER 2 3) coerced to type
3221 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3222 ;; FLOAT gets its own clause because it's implemented as
3223 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3226 ((and (numeric-type-p result-typeoid)
3227 (eq (numeric-type-complexp result-typeoid) :real))
3228 ;; FIXME: is this clause (a) necessary or (b) useful?
3230 ((or (csubtypep result-typeoid
3231 (specifier-type '(complex single-float)))
3232 (csubtypep result-typeoid
3233 (specifier-type '(complex double-float)))
3235 (csubtypep result-typeoid
3236 (specifier-type '(complex long-float))))
3237 ;; float complex types are never canonicalized.
3240 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
3241 ;; probably just a COMPLEX or equivalent. So, in that
3242 ;; case, we will return a complex or an object of the
3243 ;; provided type if it's rational:
3244 (type-union result-typeoid
3245 (type-intersection (continuation-type value)
3246 (specifier-type 'rational))))))
3247 (t result-typeoid))))
3249 ;; OK, the result-type argument isn't constant. However, there
3250 ;; are common uses where we can still do better than just
3251 ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
3252 ;; where Y is of a known type. See messages on cmucl-imp
3253 ;; 2001-02-14 and sbcl-devel 2002-12-12. We only worry here
3254 ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
3255 ;; the basis that it's unlikely that other uses are both
3256 ;; time-critical and get to this branch of the COND (non-constant
3257 ;; second argument to COERCE). -- CSR, 2002-12-16
3258 (let ((value-type (continuation-type value))
3259 (type-type (continuation-type type)))
3261 ((good-cons-type-p (cons-type)
3262 ;; Make sure the cons-type we're looking at is something
3263 ;; we're prepared to handle which is basically something
3264 ;; that array-element-type can return.
3265 (or (and (member-type-p cons-type)
3266 (null (rest (member-type-members cons-type)))
3267 (null (first (member-type-members cons-type))))
3268 (let ((car-type (cons-type-car-type cons-type)))
3269 (and (member-type-p car-type)
3270 (null (rest (member-type-members car-type)))
3271 (or (symbolp (first (member-type-members car-type)))
3272 (numberp (first (member-type-members car-type)))
3273 (and (listp (first (member-type-members
3275 (numberp (first (first (member-type-members
3277 (good-cons-type-p (cons-type-cdr-type cons-type))))))
3278 (unconsify-type (good-cons-type)
3279 ;; Convert the "printed" respresentation of a cons
3280 ;; specifier into a type specifier. That is, the
3281 ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
3282 ;; NULL)) is converted to (SIGNED-BYTE 16).
3283 (cond ((or (null good-cons-type)
3284 (eq good-cons-type 'null))
3286 ((and (eq (first good-cons-type) 'cons)
3287 (eq (first (second good-cons-type)) 'member))
3288 `(,(second (second good-cons-type))
3289 ,@(unconsify-type (caddr good-cons-type))))))
3290 (coerceable-p (c-type)
3291 ;; Can the value be coerced to the given type? Coerce is
3292 ;; complicated, so we don't handle every possible case
3293 ;; here---just the most common and easiest cases:
3295 ;; * Any REAL can be coerced to a FLOAT type.
3296 ;; * Any NUMBER can be coerced to a (COMPLEX
3297 ;; SINGLE/DOUBLE-FLOAT).
3299 ;; FIXME I: we should also be able to deal with characters
3302 ;; FIXME II: I'm not sure that anything is necessary
3303 ;; here, at least while COMPLEX is not a specialized
3304 ;; array element type in the system. Reasoning: if
3305 ;; something cannot be coerced to the requested type, an
3306 ;; error will be raised (and so any downstream compiled
3307 ;; code on the assumption of the returned type is
3308 ;; unreachable). If something can, then it will be of
3309 ;; the requested type, because (by assumption) COMPLEX
3310 ;; (and other difficult types like (COMPLEX INTEGER)
3311 ;; aren't specialized types.
3312 (let ((coerced-type c-type))
3313 (or (and (subtypep coerced-type 'float)
3314 (csubtypep value-type (specifier-type 'real)))
3315 (and (subtypep coerced-type
3316 '(or (complex single-float)
3317 (complex double-float)))
3318 (csubtypep value-type (specifier-type 'number))))))
3319 (process-types (type)
3320 ;; FIXME: This needs some work because we should be able
3321 ;; to derive the resulting type better than just the
3322 ;; type arg of coerce. That is, if X is (INTEGER 10
3323 ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
3324 ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
3326 (cond ((member-type-p type)
3327 (let ((members (member-type-members type)))
3328 (if (every #'coerceable-p members)
3329 (specifier-type `(or ,@members))
3331 ((and (cons-type-p type)
3332 (good-cons-type-p type))
3333 (let ((c-type (unconsify-type (type-specifier type))))
3334 (if (coerceable-p c-type)
3335 (specifier-type c-type)
3338 *universal-type*))))
3339 (cond ((union-type-p type-type)
3340 (apply #'type-union (mapcar #'process-types
3341 (union-type-types type-type))))
3342 ((or (member-type-p type-type)
3343 (cons-type-p type-type))
3344 (process-types type-type))
3346 *universal-type*)))))))
3348 (defoptimizer (compile derive-type) ((nameoid function))
3349 (when (csubtypep (continuation-type nameoid)
3350 (specifier-type 'null))
3351 (values-specifier-type '(values function boolean boolean))))
3353 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
3354 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
3355 ;;; optimizer, above).
3356 (defoptimizer (array-element-type derive-type) ((array))
3357 (let ((array-type (continuation-type array)))
3358 (labels ((consify (list)
3361 `(cons (eql ,(car list)) ,(consify (rest list)))))
3362 (get-element-type (a)
3364 (type-specifier (array-type-specialized-element-type a))))
3365 (cond ((eq element-type '*)
3366 (specifier-type 'type-specifier))
3367 ((symbolp element-type)
3368 (make-member-type :members (list element-type)))
3369 ((consp element-type)
3370 (specifier-type (consify element-type)))
3372 (error "can't understand type ~S~%" element-type))))))
3373 (cond ((array-type-p array-type)
3374 (get-element-type array-type))
3375 ((union-type-p array-type)
3377 (mapcar #'get-element-type (union-type-types array-type))))
3379 *universal-type*)))))
3381 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
3382 `(macrolet ((%index (x) `(truly-the index ,x))
3383 (%parent (i) `(ash ,i -1))
3384 (%left (i) `(%index (ash ,i 1)))
3385 (%right (i) `(%index (1+ (ash ,i 1))))
3388 (left (%left i) (%left i)))
3389 ((> left current-heap-size))
3390 (declare (type index i left))
3391 (let* ((i-elt (%elt i))
3392 (i-key (funcall keyfun i-elt))
3393 (left-elt (%elt left))
3394 (left-key (funcall keyfun left-elt)))
3395 (multiple-value-bind (large large-elt large-key)
3396 (if (funcall ,',predicate i-key left-key)
3397 (values left left-elt left-key)
3398 (values i i-elt i-key))
3399 (let ((right (%right i)))
3400 (multiple-value-bind (largest largest-elt)
3401 (if (> right current-heap-size)
3402 (values large large-elt)
3403 (let* ((right-elt (%elt right))
3404 (right-key (funcall keyfun right-elt)))
3405 (if (funcall ,',predicate large-key right-key)
3406 (values right right-elt)
3407 (values large large-elt))))
3408 (cond ((= largest i)
3411 (setf (%elt i) largest-elt
3412 (%elt largest) i-elt
3414 (%sort-vector (keyfun &optional (vtype 'vector))
3415 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had trouble getting
3416 ;; type inference to propagate all the way
3417 ;; through this tangled mess of
3418 ;; inlining. The TRULY-THE here works
3419 ;; around that. -- WHN
3421 `(aref (truly-the ,',vtype ,',',vector)
3422 (%index (+ (%index ,i) start-1)))))
3423 (let ((start-1 (1- ,',start)) ; Heaps prefer 1-based addressing.
3424 (current-heap-size (- ,',end ,',start))
3426 (declare (type (integer -1 #.(1- most-positive-fixnum))
3428 (declare (type index current-heap-size))
3429 (declare (type function keyfun))
3430 (loop for i of-type index
3431 from (ash current-heap-size -1) downto 1 do
3434 (when (< current-heap-size 2)
3436 (rotatef (%elt 1) (%elt current-heap-size))
3437 (decf current-heap-size)
3439 (if (typep ,vector 'simple-vector)
3440 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
3441 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
3443 ;; Special-casing the KEY=NIL case lets us avoid some
3445 (%sort-vector #'identity simple-vector)
3446 (%sort-vector ,key simple-vector))
3447 ;; It's hard to anticipate many speed-critical applications for
3448 ;; sorting vector types other than (VECTOR T), so we just lump
3449 ;; them all together in one slow dynamically typed mess.
3451 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
3452 (%sort-vector (or ,key #'identity))))))
3454 ;;;; debuggers' little helpers
3456 ;;; for debugging when transforms are behaving mysteriously,
3457 ;;; e.g. when debugging a problem with an ASH transform
3458 ;;; (defun foo (&optional s)
3459 ;;; (sb-c::/report-continuation s "S outside WHEN")
3460 ;;; (when (and (integerp s) (> s 3))
3461 ;;; (sb-c::/report-continuation s "S inside WHEN")
3462 ;;; (let ((bound (ash 1 (1- s))))
3463 ;;; (sb-c::/report-continuation bound "BOUND")
3464 ;;; (let ((x (- bound))
3466 ;;; (sb-c::/report-continuation x "X")
3467 ;;; (sb-c::/report-continuation x "Y"))
3468 ;;; `(integer ,(- bound) ,(1- bound)))))
3469 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
3470 ;;; and the function doesn't do anything at all.)
3473 (defknown /report-continuation (t t) null)
3474 (deftransform /report-continuation ((x message) (t t))
3475 (format t "~%/in /REPORT-CONTINUATION~%")
3476 (format t "/(CONTINUATION-TYPE X)=~S~%" (continuation-type x))
3477 (when (constant-continuation-p x)
3478 (format t "/(CONTINUATION-VALUE X)=~S~%" (continuation-value x)))
3479 (format t "/MESSAGE=~S~%" (continuation-value message))
3480 (give-up-ir1-transform "not a real transform"))
3481 (defun /report-continuation (&rest rest)
3482 (declare (ignore rest))))