1 ;;;; This file contains macro-like source transformations which
2 ;;;; convert uses of certain functions into the canonical form desired
3 ;;;; within the compiler. FIXME: and other IR1 transforms and stuff.
5 ;;;; This software is part of the SBCL system. See the README file for
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
16 ;;; Convert into an IF so that IF optimizations will eliminate redundant
18 (define-source-transform not (x) `(if ,x nil t))
19 (define-source-transform null (x) `(if ,x nil t))
21 ;;; ENDP is just NULL with a LIST assertion. The assertion will be
22 ;;; optimized away when SAFETY optimization is low; hopefully that
23 ;;; is consistent with ANSI's "should return an error".
24 (define-source-transform endp (x) `(null (the list ,x)))
26 ;;; We turn IDENTITY into PROG1 so that it is obvious that it just
27 ;;; returns the first value of its argument. Ditto for VALUES with one
29 (define-source-transform identity (x) `(prog1 ,x))
30 (define-source-transform values (x) `(prog1 ,x))
32 ;;; Bind the value and make a closure that returns it.
33 (define-source-transform constantly (value)
34 (with-unique-names (rest n-value)
35 `(let ((,n-value ,value))
37 (declare (ignore ,rest))
40 ;;; If the function has a known number of arguments, then return a
41 ;;; lambda with the appropriate fixed number of args. If the
42 ;;; destination is a FUNCALL, then do the &REST APPLY thing, and let
43 ;;; MV optimization figure things out.
44 (deftransform complement ((fun) * * :node node)
46 (multiple-value-bind (min max)
47 (fun-type-nargs (lvar-type fun))
49 ((and min (eql min max))
50 (let ((dums (make-gensym-list min)))
51 `#'(lambda ,dums (not (funcall fun ,@dums)))))
52 ((awhen (node-lvar node)
53 (let ((dest (lvar-dest it)))
54 (and (combination-p dest)
55 (eq (combination-fun dest) it))))
56 '#'(lambda (&rest args)
57 (not (apply fun args))))
59 (give-up-ir1-transform
60 "The function doesn't have a fixed argument count.")))))
64 ;;; Translate CxR into CAR/CDR combos.
65 (defun source-transform-cxr (form)
66 (if (/= (length form) 2)
68 (let ((name (symbol-name (car form))))
69 (do ((i (- (length name) 2) (1- i))
71 `(,(ecase (char name i)
77 ;;; Make source transforms to turn CxR forms into combinations of CAR
78 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
80 (/show0 "about to set CxR source transforms")
81 (loop for i of-type index from 2 upto 4 do
82 ;; Iterate over BUF = all names CxR where x = an I-element
83 ;; string of #\A or #\D characters.
84 (let ((buf (make-string (+ 2 i))))
85 (setf (aref buf 0) #\C
86 (aref buf (1+ i)) #\R)
87 (dotimes (j (ash 2 i))
88 (declare (type index j))
90 (declare (type index k))
91 (setf (aref buf (1+ k))
92 (if (logbitp k j) #\A #\D)))
93 (setf (info :function :source-transform (intern buf))
94 #'source-transform-cxr))))
95 (/show0 "done setting CxR source transforms")
97 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
98 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
99 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
101 (define-source-transform first (x) `(car ,x))
102 (define-source-transform rest (x) `(cdr ,x))
103 (define-source-transform second (x) `(cadr ,x))
104 (define-source-transform third (x) `(caddr ,x))
105 (define-source-transform fourth (x) `(cadddr ,x))
106 (define-source-transform fifth (x) `(nth 4 ,x))
107 (define-source-transform sixth (x) `(nth 5 ,x))
108 (define-source-transform seventh (x) `(nth 6 ,x))
109 (define-source-transform eighth (x) `(nth 7 ,x))
110 (define-source-transform ninth (x) `(nth 8 ,x))
111 (define-source-transform tenth (x) `(nth 9 ,x))
113 ;;; Translate RPLACx to LET and SETF.
114 (define-source-transform rplaca (x y)
119 (define-source-transform rplacd (x y)
125 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
127 (defvar *default-nthcdr-open-code-limit* 6)
128 (defvar *extreme-nthcdr-open-code-limit* 20)
130 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
131 "convert NTHCDR to CAxxR"
132 (unless (constant-lvar-p n)
133 (give-up-ir1-transform))
134 (let ((n (lvar-value n)))
136 (if (policy node (and (= speed 3) (= space 0)))
137 *extreme-nthcdr-open-code-limit*
138 *default-nthcdr-open-code-limit*))
139 (give-up-ir1-transform))
144 `(cdr ,(frob (1- n))))))
147 ;;;; arithmetic and numerology
149 (define-source-transform plusp (x) `(> ,x 0))
150 (define-source-transform minusp (x) `(< ,x 0))
151 (define-source-transform zerop (x) `(= ,x 0))
153 (define-source-transform 1+ (x) `(+ ,x 1))
154 (define-source-transform 1- (x) `(- ,x 1))
156 (define-source-transform oddp (x) `(not (zerop (logand ,x 1))))
157 (define-source-transform evenp (x) `(zerop (logand ,x 1)))
159 ;;; Note that all the integer division functions are available for
160 ;;; inline expansion.
162 (macrolet ((deffrob (fun)
163 `(define-source-transform ,fun (x &optional (y nil y-p))
170 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
172 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
175 (define-source-transform lognand (x y) `(lognot (logand ,x ,y)))
176 (define-source-transform lognor (x y) `(lognot (logior ,x ,y)))
177 (define-source-transform logandc1 (x y) `(logand (lognot ,x) ,y))
178 (define-source-transform logandc2 (x y) `(logand ,x (lognot ,y)))
179 (define-source-transform logorc1 (x y) `(logior (lognot ,x) ,y))
180 (define-source-transform logorc2 (x y) `(logior ,x (lognot ,y)))
181 (define-source-transform logtest (x y) `(not (zerop (logand ,x ,y))))
183 (deftransform logbitp
184 ((index integer) (unsigned-byte (or (signed-byte #.sb!vm:n-word-bits)
185 (unsigned-byte #.sb!vm:n-word-bits))))
186 `(if (>= index #.sb!vm:n-word-bits)
188 (not (zerop (logand integer (ash 1 index))))))
190 (define-source-transform byte (size position)
191 `(cons ,size ,position))
192 (define-source-transform byte-size (spec) `(car ,spec))
193 (define-source-transform byte-position (spec) `(cdr ,spec))
194 (define-source-transform ldb-test (bytespec integer)
195 `(not (zerop (mask-field ,bytespec ,integer))))
197 ;;; With the ratio and complex accessors, we pick off the "identity"
198 ;;; case, and use a primitive to handle the cell access case.
199 (define-source-transform numerator (num)
200 (once-only ((n-num `(the rational ,num)))
204 (define-source-transform denominator (num)
205 (once-only ((n-num `(the rational ,num)))
207 (%denominator ,n-num)
210 ;;;; interval arithmetic for computing bounds
212 ;;;; This is a set of routines for operating on intervals. It
213 ;;;; implements a simple interval arithmetic package. Although SBCL
214 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
215 ;;;; for two reasons:
217 ;;;; 1. This package is simpler than NUMERIC-TYPE.
219 ;;;; 2. It makes debugging much easier because you can just strip
220 ;;;; out these routines and test them independently of SBCL. (This is a
223 ;;;; One disadvantage is a probable increase in consing because we
224 ;;;; have to create these new interval structures even though
225 ;;;; numeric-type has everything we want to know. Reason 2 wins for
228 ;;; Support operations that mimic real arithmetic comparison
229 ;;; operators, but imposing a total order on the floating points such
230 ;;; that negative zeros are strictly less than positive zeros.
231 (macrolet ((def (name op)
234 (if (and (floatp x) (floatp y) (zerop x) (zerop y))
235 (,op (float-sign x) (float-sign y))
237 (def signed-zero->= >=)
238 (def signed-zero-> >)
239 (def signed-zero-= =)
240 (def signed-zero-< <)
241 (def signed-zero-<= <=))
243 ;;; The basic interval type. It can handle open and closed intervals.
244 ;;; A bound is open if it is a list containing a number, just like
245 ;;; Lisp says. NIL means unbounded.
246 (defstruct (interval (:constructor %make-interval)
250 (defun make-interval (&key low high)
251 (labels ((normalize-bound (val)
252 (cond ((and (floatp val)
253 (float-infinity-p val))
254 ;; Handle infinities.
258 ;; Handle any closed bounds.
261 ;; We have an open bound. Normalize the numeric
262 ;; bound. If the normalized bound is still a number
263 ;; (not nil), keep the bound open. Otherwise, the
264 ;; bound is really unbounded, so drop the openness.
265 (let ((new-val (normalize-bound (first val))))
267 ;; The bound exists, so keep it open still.
270 (error "unknown bound type in MAKE-INTERVAL")))))
271 (%make-interval :low (normalize-bound low)
272 :high (normalize-bound high))))
274 ;;; Given a number X, create a form suitable as a bound for an
275 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
276 #!-sb-fluid (declaim (inline set-bound))
277 (defun set-bound (x open-p)
278 (if (and x open-p) (list x) x))
280 ;;; Apply the function F to a bound X. If X is an open bound, then
281 ;;; the result will be open. IF X is NIL, the result is NIL.
282 (defun bound-func (f x)
283 (declare (type function f))
285 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
286 ;; With these traps masked, we might get things like infinity
287 ;; or negative infinity returned. Check for this and return
288 ;; NIL to indicate unbounded.
289 (let ((y (funcall f (type-bound-number x))))
291 (float-infinity-p y))
293 (set-bound (funcall f (type-bound-number x)) (consp x)))))))
295 ;;; Apply a binary operator OP to two bounds X and Y. The result is
296 ;;; NIL if either is NIL. Otherwise bound is computed and the result
297 ;;; is open if either X or Y is open.
299 ;;; FIXME: only used in this file, not needed in target runtime
300 (defmacro bound-binop (op x y)
302 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
303 (set-bound (,op (type-bound-number ,x)
304 (type-bound-number ,y))
305 (or (consp ,x) (consp ,y))))))
307 ;;; Convert a numeric-type object to an interval object.
308 (defun numeric-type->interval (x)
309 (declare (type numeric-type x))
310 (make-interval :low (numeric-type-low x)
311 :high (numeric-type-high x)))
313 (defun copy-interval-limit (limit)
318 (defun copy-interval (x)
319 (declare (type interval x))
320 (make-interval :low (copy-interval-limit (interval-low x))
321 :high (copy-interval-limit (interval-high x))))
323 ;;; Given a point P contained in the interval X, split X into two
324 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
325 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
326 ;;; contains P. You can specify both to be T or NIL.
327 (defun interval-split (p x &optional close-lower close-upper)
328 (declare (type number p)
330 (list (make-interval :low (copy-interval-limit (interval-low x))
331 :high (if close-lower p (list p)))
332 (make-interval :low (if close-upper (list p) p)
333 :high (copy-interval-limit (interval-high x)))))
335 ;;; Return the closure of the interval. That is, convert open bounds
336 ;;; to closed bounds.
337 (defun interval-closure (x)
338 (declare (type interval x))
339 (make-interval :low (type-bound-number (interval-low x))
340 :high (type-bound-number (interval-high x))))
342 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
343 ;;; '-. Otherwise return NIL.
344 (defun interval-range-info (x &optional (point 0))
345 (declare (type interval x))
346 (let ((lo (interval-low x))
347 (hi (interval-high x)))
348 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
350 ((and hi (signed-zero->= point (type-bound-number hi)))
355 ;;; Test to see whether the interval X is bounded. HOW determines the
356 ;;; test, and should be either ABOVE, BELOW, or BOTH.
357 (defun interval-bounded-p (x how)
358 (declare (type interval x))
365 (and (interval-low x) (interval-high x)))))
367 ;;; See whether the interval X contains the number P, taking into
368 ;;; account that the interval might not be closed.
369 (defun interval-contains-p (p x)
370 (declare (type number p)
372 ;; Does the interval X contain the number P? This would be a lot
373 ;; easier if all intervals were closed!
374 (let ((lo (interval-low x))
375 (hi (interval-high x)))
377 ;; The interval is bounded
378 (if (and (signed-zero-<= (type-bound-number lo) p)
379 (signed-zero-<= p (type-bound-number hi)))
380 ;; P is definitely in the closure of the interval.
381 ;; We just need to check the end points now.
382 (cond ((signed-zero-= p (type-bound-number lo))
384 ((signed-zero-= p (type-bound-number hi))
389 ;; Interval with upper bound
390 (if (signed-zero-< p (type-bound-number hi))
392 (and (numberp hi) (signed-zero-= p hi))))
394 ;; Interval with lower bound
395 (if (signed-zero-> p (type-bound-number lo))
397 (and (numberp lo) (signed-zero-= p lo))))
399 ;; Interval with no bounds
402 ;;; Determine whether two intervals X and Y intersect. Return T if so.
403 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
404 ;;; were closed. Otherwise the intervals are treated as they are.
406 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
407 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
408 ;;; is T, then they do intersect because we use the closure of X = [0,
409 ;;; 1] and Y = [1, 2] to determine intersection.
410 (defun interval-intersect-p (x y &optional closed-intervals-p)
411 (declare (type interval x y))
412 (multiple-value-bind (intersect diff)
413 (interval-intersection/difference (if closed-intervals-p
416 (if closed-intervals-p
419 (declare (ignore diff))
422 ;;; Are the two intervals adjacent? That is, is there a number
423 ;;; between the two intervals that is not an element of either
424 ;;; interval? If so, they are not adjacent. For example [0, 1) and
425 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
426 ;;; between both intervals.
427 (defun interval-adjacent-p (x y)
428 (declare (type interval x y))
429 (flet ((adjacent (lo hi)
430 ;; Check to see whether lo and hi are adjacent. If either is
431 ;; nil, they can't be adjacent.
432 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
433 ;; The bounds are equal. They are adjacent if one of
434 ;; them is closed (a number). If both are open (consp),
435 ;; then there is a number that lies between them.
436 (or (numberp lo) (numberp hi)))))
437 (or (adjacent (interval-low y) (interval-high x))
438 (adjacent (interval-low x) (interval-high y)))))
440 ;;; Compute the intersection and difference between two intervals.
441 ;;; Two values are returned: the intersection and the difference.
443 ;;; Let the two intervals be X and Y, and let I and D be the two
444 ;;; values returned by this function. Then I = X intersect Y. If I
445 ;;; is NIL (the empty set), then D is X union Y, represented as the
446 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
447 ;;; - I, which is a list of two intervals.
449 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
450 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
451 (defun interval-intersection/difference (x y)
452 (declare (type interval x y))
453 (let ((x-lo (interval-low x))
454 (x-hi (interval-high x))
455 (y-lo (interval-low y))
456 (y-hi (interval-high y)))
459 ;; If p is an open bound, make it closed. If p is a closed
460 ;; bound, make it open.
465 ;; Test whether P is in the interval.
466 (when (interval-contains-p (type-bound-number p)
467 (interval-closure int))
468 (let ((lo (interval-low int))
469 (hi (interval-high int)))
470 ;; Check for endpoints.
471 (cond ((and lo (= (type-bound-number p) (type-bound-number lo)))
472 (not (and (consp p) (numberp lo))))
473 ((and hi (= (type-bound-number p) (type-bound-number hi)))
474 (not (and (numberp p) (consp hi))))
476 (test-lower-bound (p int)
477 ;; P is a lower bound of an interval.
480 (not (interval-bounded-p int 'below))))
481 (test-upper-bound (p int)
482 ;; P is an upper bound of an interval.
485 (not (interval-bounded-p int 'above)))))
486 (let ((x-lo-in-y (test-lower-bound x-lo y))
487 (x-hi-in-y (test-upper-bound x-hi y))
488 (y-lo-in-x (test-lower-bound y-lo x))
489 (y-hi-in-x (test-upper-bound y-hi x)))
490 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
491 ;; Intervals intersect. Let's compute the intersection
492 ;; and the difference.
493 (multiple-value-bind (lo left-lo left-hi)
494 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
495 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
496 (multiple-value-bind (hi right-lo right-hi)
498 (values x-hi (opposite-bound x-hi) y-hi))
500 (values y-hi (opposite-bound y-hi) x-hi)))
501 (values (make-interval :low lo :high hi)
502 (list (make-interval :low left-lo
504 (make-interval :low right-lo
507 (values nil (list x y))))))))
509 ;;; If intervals X and Y intersect, return a new interval that is the
510 ;;; union of the two. If they do not intersect, return NIL.
511 (defun interval-merge-pair (x y)
512 (declare (type interval x y))
513 ;; If x and y intersect or are adjacent, create the union.
514 ;; Otherwise return nil
515 (when (or (interval-intersect-p x y)
516 (interval-adjacent-p x y))
517 (flet ((select-bound (x1 x2 min-op max-op)
518 (let ((x1-val (type-bound-number x1))
519 (x2-val (type-bound-number x2)))
521 ;; Both bounds are finite. Select the right one.
522 (cond ((funcall min-op x1-val x2-val)
523 ;; x1 is definitely better.
525 ((funcall max-op x1-val x2-val)
526 ;; x2 is definitely better.
529 ;; Bounds are equal. Select either
530 ;; value and make it open only if
532 (set-bound x1-val (and (consp x1) (consp x2))))))
534 ;; At least one bound is not finite. The
535 ;; non-finite bound always wins.
537 (let* ((x-lo (copy-interval-limit (interval-low x)))
538 (x-hi (copy-interval-limit (interval-high x)))
539 (y-lo (copy-interval-limit (interval-low y)))
540 (y-hi (copy-interval-limit (interval-high y))))
541 (make-interval :low (select-bound x-lo y-lo #'< #'>)
542 :high (select-bound x-hi y-hi #'> #'<))))))
544 ;;; basic arithmetic operations on intervals. We probably should do
545 ;;; true interval arithmetic here, but it's complicated because we
546 ;;; have float and integer types and bounds can be open or closed.
548 ;;; the negative of an interval
549 (defun interval-neg (x)
550 (declare (type interval x))
551 (make-interval :low (bound-func #'- (interval-high x))
552 :high (bound-func #'- (interval-low x))))
554 ;;; Add two intervals.
555 (defun interval-add (x y)
556 (declare (type interval x y))
557 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
558 :high (bound-binop + (interval-high x) (interval-high y))))
560 ;;; Subtract two intervals.
561 (defun interval-sub (x y)
562 (declare (type interval x y))
563 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
564 :high (bound-binop - (interval-high x) (interval-low y))))
566 ;;; Multiply two intervals.
567 (defun interval-mul (x y)
568 (declare (type interval x y))
569 (flet ((bound-mul (x y)
570 (cond ((or (null x) (null y))
571 ;; Multiply by infinity is infinity
573 ((or (and (numberp x) (zerop x))
574 (and (numberp y) (zerop y)))
575 ;; Multiply by closed zero is special. The result
576 ;; is always a closed bound. But don't replace this
577 ;; with zero; we want the multiplication to produce
578 ;; the correct signed zero, if needed.
579 (* (type-bound-number x) (type-bound-number y)))
580 ((or (and (floatp x) (float-infinity-p x))
581 (and (floatp y) (float-infinity-p y)))
582 ;; Infinity times anything is infinity
585 ;; General multiply. The result is open if either is open.
586 (bound-binop * x y)))))
587 (let ((x-range (interval-range-info x))
588 (y-range (interval-range-info y)))
589 (cond ((null x-range)
590 ;; Split x into two and multiply each separately
591 (destructuring-bind (x- x+) (interval-split 0 x t t)
592 (interval-merge-pair (interval-mul x- y)
593 (interval-mul x+ y))))
595 ;; Split y into two and multiply each separately
596 (destructuring-bind (y- y+) (interval-split 0 y t t)
597 (interval-merge-pair (interval-mul x y-)
598 (interval-mul x y+))))
600 (interval-neg (interval-mul (interval-neg x) y)))
602 (interval-neg (interval-mul x (interval-neg y))))
603 ((and (eq x-range '+) (eq y-range '+))
604 ;; If we are here, X and Y are both positive.
606 :low (bound-mul (interval-low x) (interval-low y))
607 :high (bound-mul (interval-high x) (interval-high y))))
609 (bug "excluded case in INTERVAL-MUL"))))))
611 ;;; Divide two intervals.
612 (defun interval-div (top bot)
613 (declare (type interval top bot))
614 (flet ((bound-div (x y y-low-p)
617 ;; Divide by infinity means result is 0. However,
618 ;; we need to watch out for the sign of the result,
619 ;; to correctly handle signed zeros. We also need
620 ;; to watch out for positive or negative infinity.
621 (if (floatp (type-bound-number x))
623 (- (float-sign (type-bound-number x) 0.0))
624 (float-sign (type-bound-number x) 0.0))
626 ((zerop (type-bound-number y))
627 ;; Divide by zero means result is infinity
629 ((and (numberp x) (zerop x))
630 ;; Zero divided by anything is zero.
633 (bound-binop / x y)))))
634 (let ((top-range (interval-range-info top))
635 (bot-range (interval-range-info bot)))
636 (cond ((null bot-range)
637 ;; The denominator contains zero, so anything goes!
638 (make-interval :low nil :high nil))
640 ;; Denominator is negative so flip the sign, compute the
641 ;; result, and flip it back.
642 (interval-neg (interval-div top (interval-neg bot))))
644 ;; Split top into two positive and negative parts, and
645 ;; divide each separately
646 (destructuring-bind (top- top+) (interval-split 0 top t t)
647 (interval-merge-pair (interval-div top- bot)
648 (interval-div top+ bot))))
650 ;; Top is negative so flip the sign, divide, and flip the
651 ;; sign of the result.
652 (interval-neg (interval-div (interval-neg top) bot)))
653 ((and (eq top-range '+) (eq bot-range '+))
656 :low (bound-div (interval-low top) (interval-high bot) t)
657 :high (bound-div (interval-high top) (interval-low bot) nil)))
659 (bug "excluded case in INTERVAL-DIV"))))))
661 ;;; Apply the function F to the interval X. If X = [a, b], then the
662 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
663 ;;; result makes sense. It will if F is monotonic increasing (or
665 (defun interval-func (f x)
666 (declare (type function f)
668 (let ((lo (bound-func f (interval-low x)))
669 (hi (bound-func f (interval-high x))))
670 (make-interval :low lo :high hi)))
672 ;;; Return T if X < Y. That is every number in the interval X is
673 ;;; always less than any number in the interval Y.
674 (defun interval-< (x y)
675 (declare (type interval x y))
676 ;; X < Y only if X is bounded above, Y is bounded below, and they
678 (when (and (interval-bounded-p x 'above)
679 (interval-bounded-p y 'below))
680 ;; Intervals are bounded in the appropriate way. Make sure they
682 (let ((left (interval-high x))
683 (right (interval-low y)))
684 (cond ((> (type-bound-number left)
685 (type-bound-number right))
686 ;; The intervals definitely overlap, so result is NIL.
688 ((< (type-bound-number left)
689 (type-bound-number right))
690 ;; The intervals definitely don't touch, so result is T.
693 ;; Limits are equal. Check for open or closed bounds.
694 ;; Don't overlap if one or the other are open.
695 (or (consp left) (consp right)))))))
697 ;;; Return T if X >= Y. That is, every number in the interval X is
698 ;;; always greater than any number in the interval Y.
699 (defun interval->= (x y)
700 (declare (type interval x y))
701 ;; X >= Y if lower bound of X >= upper bound of Y
702 (when (and (interval-bounded-p x 'below)
703 (interval-bounded-p y 'above))
704 (>= (type-bound-number (interval-low x))
705 (type-bound-number (interval-high y)))))
707 ;;; Return an interval that is the absolute value of X. Thus, if
708 ;;; X = [-1 10], the result is [0, 10].
709 (defun interval-abs (x)
710 (declare (type interval x))
711 (case (interval-range-info x)
717 (destructuring-bind (x- x+) (interval-split 0 x t t)
718 (interval-merge-pair (interval-neg x-) x+)))))
720 ;;; Compute the square of an interval.
721 (defun interval-sqr (x)
722 (declare (type interval x))
723 (interval-func (lambda (x) (* x x))
726 ;;;; numeric DERIVE-TYPE methods
728 ;;; a utility for defining derive-type methods of integer operations. If
729 ;;; the types of both X and Y are integer types, then we compute a new
730 ;;; integer type with bounds determined Fun when applied to X and Y.
731 ;;; Otherwise, we use Numeric-Contagion.
732 (defun derive-integer-type (x y fun)
733 (declare (type lvar x y) (type function fun))
734 (let ((x (lvar-type x))
736 (if (and (numeric-type-p x) (numeric-type-p y)
737 (eq (numeric-type-class x) 'integer)
738 (eq (numeric-type-class y) 'integer)
739 (eq (numeric-type-complexp x) :real)
740 (eq (numeric-type-complexp y) :real))
741 (multiple-value-bind (low high) (funcall fun x y)
742 (make-numeric-type :class 'integer
746 (numeric-contagion x y))))
748 ;;; simple utility to flatten a list
749 (defun flatten-list (x)
750 (labels ((flatten-helper (x r);; 'r' is the stuff to the 'right'.
754 (t (flatten-helper (car x)
755 (flatten-helper (cdr x) r))))))
756 (flatten-helper x nil)))
758 ;;; Take some type of continuation and massage it so that we get a
759 ;;; list of the constituent types. If ARG is *EMPTY-TYPE*, return NIL
760 ;;; to indicate failure.
761 (defun prepare-arg-for-derive-type (arg)
762 (flet ((listify (arg)
767 (union-type-types arg))
770 (unless (eq arg *empty-type*)
771 ;; Make sure all args are some type of numeric-type. For member
772 ;; types, convert the list of members into a union of equivalent
773 ;; single-element member-type's.
774 (let ((new-args nil))
775 (dolist (arg (listify arg))
776 (if (member-type-p arg)
777 ;; Run down the list of members and convert to a list of
779 (dolist (member (member-type-members arg))
780 (push (if (numberp member)
781 (make-member-type :members (list member))
784 (push arg new-args)))
785 (unless (member *empty-type* new-args)
788 ;;; Convert from the standard type convention for which -0.0 and 0.0
789 ;;; are equal to an intermediate convention for which they are
790 ;;; considered different which is more natural for some of the
792 (defun convert-numeric-type (type)
793 (declare (type numeric-type type))
794 ;;; Only convert real float interval delimiters types.
795 (if (eq (numeric-type-complexp type) :real)
796 (let* ((lo (numeric-type-low type))
797 (lo-val (type-bound-number lo))
798 (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
799 (hi (numeric-type-high type))
800 (hi-val (type-bound-number hi))
801 (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
802 (if (or lo-float-zero-p hi-float-zero-p)
804 :class (numeric-type-class type)
805 :format (numeric-type-format type)
807 :low (if lo-float-zero-p
809 (list (float 0.0 lo-val))
810 (float (load-time-value (make-unportable-float :single-float-negative-zero)) lo-val))
812 :high (if hi-float-zero-p
814 (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val))
821 ;;; Convert back from the intermediate convention for which -0.0 and
822 ;;; 0.0 are considered different to the standard type convention for
824 (defun convert-back-numeric-type (type)
825 (declare (type numeric-type type))
826 ;;; Only convert real float interval delimiters types.
827 (if (eq (numeric-type-complexp type) :real)
828 (let* ((lo (numeric-type-low type))
829 (lo-val (type-bound-number lo))
831 (and lo (floatp lo-val) (= lo-val 0.0)
832 (float-sign lo-val)))
833 (hi (numeric-type-high type))
834 (hi-val (type-bound-number hi))
836 (and hi (floatp hi-val) (= hi-val 0.0)
837 (float-sign hi-val))))
839 ;; (float +0.0 +0.0) => (member 0.0)
840 ;; (float -0.0 -0.0) => (member -0.0)
841 ((and lo-float-zero-p hi-float-zero-p)
842 ;; shouldn't have exclusive bounds here..
843 (aver (and (not (consp lo)) (not (consp hi))))
844 (if (= lo-float-zero-p hi-float-zero-p)
845 ;; (float +0.0 +0.0) => (member 0.0)
846 ;; (float -0.0 -0.0) => (member -0.0)
847 (specifier-type `(member ,lo-val))
848 ;; (float -0.0 +0.0) => (float 0.0 0.0)
849 ;; (float +0.0 -0.0) => (float 0.0 0.0)
850 (make-numeric-type :class (numeric-type-class type)
851 :format (numeric-type-format type)
857 ;; (float -0.0 x) => (float 0.0 x)
858 ((and (not (consp lo)) (minusp lo-float-zero-p))
859 (make-numeric-type :class (numeric-type-class type)
860 :format (numeric-type-format type)
862 :low (float 0.0 lo-val)
864 ;; (float (+0.0) x) => (float (0.0) x)
865 ((and (consp lo) (plusp lo-float-zero-p))
866 (make-numeric-type :class (numeric-type-class type)
867 :format (numeric-type-format type)
869 :low (list (float 0.0 lo-val))
872 ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
873 ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
874 (list (make-member-type :members (list (float 0.0 lo-val)))
875 (make-numeric-type :class (numeric-type-class type)
876 :format (numeric-type-format type)
878 :low (list (float 0.0 lo-val))
882 ;; (float x +0.0) => (float x 0.0)
883 ((and (not (consp hi)) (plusp hi-float-zero-p))
884 (make-numeric-type :class (numeric-type-class type)
885 :format (numeric-type-format type)
888 :high (float 0.0 hi-val)))
889 ;; (float x (-0.0)) => (float x (0.0))
890 ((and (consp hi) (minusp hi-float-zero-p))
891 (make-numeric-type :class (numeric-type-class type)
892 :format (numeric-type-format type)
895 :high (list (float 0.0 hi-val))))
897 ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
898 ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
899 (list (make-member-type :members (list (float -0.0 hi-val)))
900 (make-numeric-type :class (numeric-type-class type)
901 :format (numeric-type-format type)
904 :high (list (float 0.0 hi-val)))))))
910 ;;; Convert back a possible list of numeric types.
911 (defun convert-back-numeric-type-list (type-list)
915 (dolist (type type-list)
916 (if (numeric-type-p type)
917 (let ((result (convert-back-numeric-type type)))
919 (setf results (append results result))
920 (push result results)))
921 (push type results)))
924 (convert-back-numeric-type type-list))
926 (convert-back-numeric-type-list (union-type-types type-list)))
930 ;;; FIXME: MAKE-CANONICAL-UNION-TYPE and CONVERT-MEMBER-TYPE probably
931 ;;; belong in the kernel's type logic, invoked always, instead of in
932 ;;; the compiler, invoked only during some type optimizations. (In
933 ;;; fact, as of 0.pre8.100 or so they probably are, under
934 ;;; MAKE-MEMBER-TYPE, so probably this code can be deleted)
936 ;;; Take a list of types and return a canonical type specifier,
937 ;;; combining any MEMBER types together. If both positive and negative
938 ;;; MEMBER types are present they are converted to a float type.
939 ;;; XXX This would be far simpler if the type-union methods could handle
940 ;;; member/number unions.
941 (defun make-canonical-union-type (type-list)
944 (dolist (type type-list)
945 (if (member-type-p type)
946 (setf members (union members (member-type-members type)))
947 (push type misc-types)))
949 (when (null (set-difference `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0) members))
950 (push (specifier-type '(long-float 0.0l0 0.0l0)) misc-types)
951 (setf members (set-difference members `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0))))
952 (when (null (set-difference `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0) members))
953 (push (specifier-type '(double-float 0.0d0 0.0d0)) misc-types)
954 (setf members (set-difference members `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0))))
955 (when (null (set-difference `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0) members))
956 (push (specifier-type '(single-float 0.0f0 0.0f0)) misc-types)
957 (setf members (set-difference members `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0))))
959 (apply #'type-union (make-member-type :members members) misc-types)
960 (apply #'type-union misc-types))))
962 ;;; Convert a member type with a single member to a numeric type.
963 (defun convert-member-type (arg)
964 (let* ((members (member-type-members arg))
965 (member (first members))
966 (member-type (type-of member)))
967 (aver (not (rest members)))
968 (specifier-type (cond ((typep member 'integer)
969 `(integer ,member ,member))
970 ((memq member-type '(short-float single-float
971 double-float long-float))
972 `(,member-type ,member ,member))
976 ;;; This is used in defoptimizers for computing the resulting type of
979 ;;; Given the continuation ARG, derive the resulting type using the
980 ;;; DERIVE-FUN. DERIVE-FUN takes exactly one argument which is some
981 ;;; "atomic" continuation type like numeric-type or member-type
982 ;;; (containing just one element). It should return the resulting
983 ;;; type, which can be a list of types.
985 ;;; For the case of member types, if a MEMBER-FUN is given it is
986 ;;; called to compute the result otherwise the member type is first
987 ;;; converted to a numeric type and the DERIVE-FUN is called.
988 (defun one-arg-derive-type (arg derive-fun member-fun
989 &optional (convert-type t))
990 (declare (type function derive-fun)
991 (type (or null function) member-fun))
992 (let ((arg-list (prepare-arg-for-derive-type (lvar-type arg))))
998 (with-float-traps-masked
999 (:underflow :overflow :divide-by-zero)
1003 (first (member-type-members x))))))
1004 ;; Otherwise convert to a numeric type.
1005 (let ((result-type-list
1006 (funcall derive-fun (convert-member-type x))))
1008 (convert-back-numeric-type-list result-type-list)
1009 result-type-list))))
1012 (convert-back-numeric-type-list
1013 (funcall derive-fun (convert-numeric-type x)))
1014 (funcall derive-fun x)))
1016 *universal-type*))))
1017 ;; Run down the list of args and derive the type of each one,
1018 ;; saving all of the results in a list.
1019 (let ((results nil))
1020 (dolist (arg arg-list)
1021 (let ((result (deriver arg)))
1023 (setf results (append results result))
1024 (push result results))))
1026 (make-canonical-union-type results)
1027 (first results)))))))
1029 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1030 ;;; two arguments. DERIVE-FUN takes 3 args in this case: the two
1031 ;;; original args and a third which is T to indicate if the two args
1032 ;;; really represent the same continuation. This is useful for
1033 ;;; deriving the type of things like (* x x), which should always be
1034 ;;; positive. If we didn't do this, we wouldn't be able to tell.
1035 (defun two-arg-derive-type (arg1 arg2 derive-fun fun
1036 &optional (convert-type t))
1037 (declare (type function derive-fun fun))
1038 (flet ((deriver (x y same-arg)
1039 (cond ((and (member-type-p x) (member-type-p y))
1040 (let* ((x (first (member-type-members x)))
1041 (y (first (member-type-members y)))
1042 (result (with-float-traps-masked
1043 (:underflow :overflow :divide-by-zero
1045 (funcall fun x y))))
1046 (cond ((null result))
1047 ((and (floatp result) (float-nan-p result))
1048 (make-numeric-type :class 'float
1049 :format (type-of result)
1052 (make-member-type :members (list result))))))
1053 ((and (member-type-p x) (numeric-type-p y))
1054 (let* ((x (convert-member-type x))
1055 (y (if convert-type (convert-numeric-type y) y))
1056 (result (funcall derive-fun x y same-arg)))
1058 (convert-back-numeric-type-list result)
1060 ((and (numeric-type-p x) (member-type-p y))
1061 (let* ((x (if convert-type (convert-numeric-type x) x))
1062 (y (convert-member-type y))
1063 (result (funcall derive-fun x y same-arg)))
1065 (convert-back-numeric-type-list result)
1067 ((and (numeric-type-p x) (numeric-type-p y))
1068 (let* ((x (if convert-type (convert-numeric-type x) x))
1069 (y (if convert-type (convert-numeric-type y) y))
1070 (result (funcall derive-fun x y same-arg)))
1072 (convert-back-numeric-type-list result)
1075 *universal-type*))))
1076 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1077 (a1 (prepare-arg-for-derive-type (lvar-type arg1)))
1078 (a2 (prepare-arg-for-derive-type (lvar-type arg2))))
1080 (let ((results nil))
1082 ;; Since the args are the same continuation, just run
1085 (let ((result (deriver x x same-arg)))
1087 (setf results (append results result))
1088 (push result results))))
1089 ;; Try all pairwise combinations.
1092 (let ((result (or (deriver x y same-arg)
1093 (numeric-contagion x y))))
1095 (setf results (append results result))
1096 (push result results))))))
1098 (make-canonical-union-type results)
1099 (first results)))))))
1101 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1103 (defoptimizer (+ derive-type) ((x y))
1104 (derive-integer-type
1111 (values (frob (numeric-type-low x) (numeric-type-low y))
1112 (frob (numeric-type-high x) (numeric-type-high y)))))))
1114 (defoptimizer (- derive-type) ((x y))
1115 (derive-integer-type
1122 (values (frob (numeric-type-low x) (numeric-type-high y))
1123 (frob (numeric-type-high x) (numeric-type-low y)))))))
1125 (defoptimizer (* derive-type) ((x y))
1126 (derive-integer-type
1129 (let ((x-low (numeric-type-low x))
1130 (x-high (numeric-type-high x))
1131 (y-low (numeric-type-low y))
1132 (y-high (numeric-type-high y)))
1133 (cond ((not (and x-low y-low))
1135 ((or (minusp x-low) (minusp y-low))
1136 (if (and x-high y-high)
1137 (let ((max (* (max (abs x-low) (abs x-high))
1138 (max (abs y-low) (abs y-high)))))
1139 (values (- max) max))
1142 (values (* x-low y-low)
1143 (if (and x-high y-high)
1147 (defoptimizer (/ derive-type) ((x y))
1148 (numeric-contagion (lvar-type x) (lvar-type y)))
1152 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1154 (defun +-derive-type-aux (x y same-arg)
1155 (if (and (numeric-type-real-p x)
1156 (numeric-type-real-p y))
1159 (let ((x-int (numeric-type->interval x)))
1160 (interval-add x-int x-int))
1161 (interval-add (numeric-type->interval x)
1162 (numeric-type->interval y))))
1163 (result-type (numeric-contagion x y)))
1164 ;; If the result type is a float, we need to be sure to coerce
1165 ;; the bounds into the correct type.
1166 (when (eq (numeric-type-class result-type) 'float)
1167 (setf result (interval-func
1169 (coerce x (or (numeric-type-format result-type)
1173 :class (if (and (eq (numeric-type-class x) 'integer)
1174 (eq (numeric-type-class y) 'integer))
1175 ;; The sum of integers is always an integer.
1177 (numeric-type-class result-type))
1178 :format (numeric-type-format result-type)
1179 :low (interval-low result)
1180 :high (interval-high result)))
1181 ;; general contagion
1182 (numeric-contagion x y)))
1184 (defoptimizer (+ derive-type) ((x y))
1185 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1187 (defun --derive-type-aux (x y same-arg)
1188 (if (and (numeric-type-real-p x)
1189 (numeric-type-real-p y))
1191 ;; (- X X) is always 0.
1193 (make-interval :low 0 :high 0)
1194 (interval-sub (numeric-type->interval x)
1195 (numeric-type->interval y))))
1196 (result-type (numeric-contagion x y)))
1197 ;; If the result type is a float, we need to be sure to coerce
1198 ;; the bounds into the correct type.
1199 (when (eq (numeric-type-class result-type) 'float)
1200 (setf result (interval-func
1202 (coerce x (or (numeric-type-format result-type)
1206 :class (if (and (eq (numeric-type-class x) 'integer)
1207 (eq (numeric-type-class y) 'integer))
1208 ;; The difference of integers is always an integer.
1210 (numeric-type-class result-type))
1211 :format (numeric-type-format result-type)
1212 :low (interval-low result)
1213 :high (interval-high result)))
1214 ;; general contagion
1215 (numeric-contagion x y)))
1217 (defoptimizer (- derive-type) ((x y))
1218 (two-arg-derive-type x y #'--derive-type-aux #'-))
1220 (defun *-derive-type-aux (x y same-arg)
1221 (if (and (numeric-type-real-p x)
1222 (numeric-type-real-p y))
1224 ;; (* X X) is always positive, so take care to do it right.
1226 (interval-sqr (numeric-type->interval x))
1227 (interval-mul (numeric-type->interval x)
1228 (numeric-type->interval y))))
1229 (result-type (numeric-contagion x y)))
1230 ;; If the result type is a float, we need to be sure to coerce
1231 ;; the bounds into the correct type.
1232 (when (eq (numeric-type-class result-type) 'float)
1233 (setf result (interval-func
1235 (coerce x (or (numeric-type-format result-type)
1239 :class (if (and (eq (numeric-type-class x) 'integer)
1240 (eq (numeric-type-class y) 'integer))
1241 ;; The product of integers is always an integer.
1243 (numeric-type-class result-type))
1244 :format (numeric-type-format result-type)
1245 :low (interval-low result)
1246 :high (interval-high result)))
1247 (numeric-contagion x y)))
1249 (defoptimizer (* derive-type) ((x y))
1250 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1252 (defun /-derive-type-aux (x y same-arg)
1253 (if (and (numeric-type-real-p x)
1254 (numeric-type-real-p y))
1256 ;; (/ X X) is always 1, except if X can contain 0. In
1257 ;; that case, we shouldn't optimize the division away
1258 ;; because we want 0/0 to signal an error.
1260 (not (interval-contains-p
1261 0 (interval-closure (numeric-type->interval y)))))
1262 (make-interval :low 1 :high 1)
1263 (interval-div (numeric-type->interval x)
1264 (numeric-type->interval y))))
1265 (result-type (numeric-contagion x y)))
1266 ;; If the result type is a float, we need to be sure to coerce
1267 ;; the bounds into the correct type.
1268 (when (eq (numeric-type-class result-type) 'float)
1269 (setf result (interval-func
1271 (coerce x (or (numeric-type-format result-type)
1274 (make-numeric-type :class (numeric-type-class result-type)
1275 :format (numeric-type-format result-type)
1276 :low (interval-low result)
1277 :high (interval-high result)))
1278 (numeric-contagion x y)))
1280 (defoptimizer (/ derive-type) ((x y))
1281 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1285 (defun ash-derive-type-aux (n-type shift same-arg)
1286 (declare (ignore same-arg))
1287 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1288 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1289 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1290 ;; two bignums yielding zero) and it's hard to avoid that
1291 ;; calculation in here.
1292 #+(and cmu sb-xc-host)
1293 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1294 (typep (numeric-type-high n-type) 'bignum))
1295 (or (typep (numeric-type-low shift) 'bignum)
1296 (typep (numeric-type-high shift) 'bignum)))
1297 (return-from ash-derive-type-aux *universal-type*))
1298 (flet ((ash-outer (n s)
1299 (when (and (fixnump s)
1301 (> s sb!xc:most-negative-fixnum))
1303 ;; KLUDGE: The bare 64's here should be related to
1304 ;; symbolic machine word size values somehow.
1307 (if (and (fixnump s)
1308 (> s sb!xc:most-negative-fixnum))
1310 (if (minusp n) -1 0))))
1311 (or (and (csubtypep n-type (specifier-type 'integer))
1312 (csubtypep shift (specifier-type 'integer))
1313 (let ((n-low (numeric-type-low n-type))
1314 (n-high (numeric-type-high n-type))
1315 (s-low (numeric-type-low shift))
1316 (s-high (numeric-type-high shift)))
1317 (make-numeric-type :class 'integer :complexp :real
1320 (ash-outer n-low s-high)
1321 (ash-inner n-low s-low)))
1324 (ash-inner n-high s-low)
1325 (ash-outer n-high s-high))))))
1328 (defoptimizer (ash derive-type) ((n shift))
1329 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1331 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1332 (macrolet ((frob (fun)
1333 `#'(lambda (type type2)
1334 (declare (ignore type2))
1335 (let ((lo (numeric-type-low type))
1336 (hi (numeric-type-high type)))
1337 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1339 (defoptimizer (%negate derive-type) ((num))
1340 (derive-integer-type num num (frob -))))
1342 (defoptimizer (lognot derive-type) ((int))
1343 (derive-integer-type int int
1344 (lambda (type type2)
1345 (declare (ignore type2))
1346 (let ((lo (numeric-type-low type))
1347 (hi (numeric-type-high type)))
1348 (values (if hi (lognot hi) nil)
1349 (if lo (lognot lo) nil)
1350 (numeric-type-class type)
1351 (numeric-type-format type))))))
1353 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1354 (defoptimizer (%negate derive-type) ((num))
1355 (flet ((negate-bound (b)
1357 (set-bound (- (type-bound-number b))
1359 (one-arg-derive-type num
1361 (modified-numeric-type
1363 :low (negate-bound (numeric-type-high type))
1364 :high (negate-bound (numeric-type-low type))))
1367 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1368 (defoptimizer (abs derive-type) ((num))
1369 (let ((type (lvar-type num)))
1370 (if (and (numeric-type-p type)
1371 (eq (numeric-type-class type) 'integer)
1372 (eq (numeric-type-complexp type) :real))
1373 (let ((lo (numeric-type-low type))
1374 (hi (numeric-type-high type)))
1375 (make-numeric-type :class 'integer :complexp :real
1376 :low (cond ((and hi (minusp hi))
1382 :high (if (and hi lo)
1383 (max (abs hi) (abs lo))
1385 (numeric-contagion type type))))
1387 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1388 (defun abs-derive-type-aux (type)
1389 (cond ((eq (numeric-type-complexp type) :complex)
1390 ;; The absolute value of a complex number is always a
1391 ;; non-negative float.
1392 (let* ((format (case (numeric-type-class type)
1393 ((integer rational) 'single-float)
1394 (t (numeric-type-format type))))
1395 (bound-format (or format 'float)))
1396 (make-numeric-type :class 'float
1399 :low (coerce 0 bound-format)
1402 ;; The absolute value of a real number is a non-negative real
1403 ;; of the same type.
1404 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1405 (class (numeric-type-class type))
1406 (format (numeric-type-format type))
1407 (bound-type (or format class 'real)))
1412 :low (coerce-numeric-bound (interval-low abs-bnd) bound-type)
1413 :high (coerce-numeric-bound
1414 (interval-high abs-bnd) bound-type))))))
1416 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1417 (defoptimizer (abs derive-type) ((num))
1418 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1420 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1421 (defoptimizer (truncate derive-type) ((number divisor))
1422 (let ((number-type (lvar-type number))
1423 (divisor-type (lvar-type divisor))
1424 (integer-type (specifier-type 'integer)))
1425 (if (and (numeric-type-p number-type)
1426 (csubtypep number-type integer-type)
1427 (numeric-type-p divisor-type)
1428 (csubtypep divisor-type integer-type))
1429 (let ((number-low (numeric-type-low number-type))
1430 (number-high (numeric-type-high number-type))
1431 (divisor-low (numeric-type-low divisor-type))
1432 (divisor-high (numeric-type-high divisor-type)))
1433 (values-specifier-type
1434 `(values ,(integer-truncate-derive-type number-low number-high
1435 divisor-low divisor-high)
1436 ,(integer-rem-derive-type number-low number-high
1437 divisor-low divisor-high))))
1440 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1443 (defun rem-result-type (number-type divisor-type)
1444 ;; Figure out what the remainder type is. The remainder is an
1445 ;; integer if both args are integers; a rational if both args are
1446 ;; rational; and a float otherwise.
1447 (cond ((and (csubtypep number-type (specifier-type 'integer))
1448 (csubtypep divisor-type (specifier-type 'integer)))
1450 ((and (csubtypep number-type (specifier-type 'rational))
1451 (csubtypep divisor-type (specifier-type 'rational)))
1453 ((and (csubtypep number-type (specifier-type 'float))
1454 (csubtypep divisor-type (specifier-type 'float)))
1455 ;; Both are floats so the result is also a float, of
1456 ;; the largest type.
1457 (or (float-format-max (numeric-type-format number-type)
1458 (numeric-type-format divisor-type))
1460 ((and (csubtypep number-type (specifier-type 'float))
1461 (csubtypep divisor-type (specifier-type 'rational)))
1462 ;; One of the arguments is a float and the other is a
1463 ;; rational. The remainder is a float of the same
1465 (or (numeric-type-format number-type) 'float))
1466 ((and (csubtypep divisor-type (specifier-type 'float))
1467 (csubtypep number-type (specifier-type 'rational)))
1468 ;; One of the arguments is a float and the other is a
1469 ;; rational. The remainder is a float of the same
1471 (or (numeric-type-format divisor-type) 'float))
1473 ;; Some unhandled combination. This usually means both args
1474 ;; are REAL so the result is a REAL.
1477 (defun truncate-derive-type-quot (number-type divisor-type)
1478 (let* ((rem-type (rem-result-type number-type divisor-type))
1479 (number-interval (numeric-type->interval number-type))
1480 (divisor-interval (numeric-type->interval divisor-type)))
1481 ;;(declare (type (member '(integer rational float)) rem-type))
1482 ;; We have real numbers now.
1483 (cond ((eq rem-type 'integer)
1484 ;; Since the remainder type is INTEGER, both args are
1486 (let* ((res (integer-truncate-derive-type
1487 (interval-low number-interval)
1488 (interval-high number-interval)
1489 (interval-low divisor-interval)
1490 (interval-high divisor-interval))))
1491 (specifier-type (if (listp res) res 'integer))))
1493 (let ((quot (truncate-quotient-bound
1494 (interval-div number-interval
1495 divisor-interval))))
1496 (specifier-type `(integer ,(or (interval-low quot) '*)
1497 ,(or (interval-high quot) '*))))))))
1499 (defun truncate-derive-type-rem (number-type divisor-type)
1500 (let* ((rem-type (rem-result-type number-type divisor-type))
1501 (number-interval (numeric-type->interval number-type))
1502 (divisor-interval (numeric-type->interval divisor-type))
1503 (rem (truncate-rem-bound number-interval divisor-interval)))
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 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1510 ,(or (interval-high rem) '*))))
1512 (multiple-value-bind (class format)
1515 (values 'integer nil))
1517 (values 'rational nil))
1518 ((or single-float double-float #!+long-float long-float)
1519 (values 'float rem-type))
1521 (values 'float nil))
1524 (when (member rem-type '(float single-float double-float
1525 #!+long-float long-float))
1526 (setf rem (interval-func #'(lambda (x)
1527 (coerce x rem-type))
1529 (make-numeric-type :class class
1531 :low (interval-low rem)
1532 :high (interval-high rem)))))))
1534 (defun truncate-derive-type-quot-aux (num div same-arg)
1535 (declare (ignore same-arg))
1536 (if (and (numeric-type-real-p num)
1537 (numeric-type-real-p div))
1538 (truncate-derive-type-quot num div)
1541 (defun truncate-derive-type-rem-aux (num div same-arg)
1542 (declare (ignore same-arg))
1543 (if (and (numeric-type-real-p num)
1544 (numeric-type-real-p div))
1545 (truncate-derive-type-rem num div)
1548 (defoptimizer (truncate derive-type) ((number divisor))
1549 (let ((quot (two-arg-derive-type number divisor
1550 #'truncate-derive-type-quot-aux #'truncate))
1551 (rem (two-arg-derive-type number divisor
1552 #'truncate-derive-type-rem-aux #'rem)))
1553 (when (and quot rem)
1554 (make-values-type :required (list quot rem)))))
1556 (defun ftruncate-derive-type-quot (number-type divisor-type)
1557 ;; The bounds are the same as for truncate. However, the first
1558 ;; result is a float of some type. We need to determine what that
1559 ;; type is. Basically it's the more contagious of the two types.
1560 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1561 (res-type (numeric-contagion number-type divisor-type)))
1562 (make-numeric-type :class 'float
1563 :format (numeric-type-format res-type)
1564 :low (numeric-type-low q-type)
1565 :high (numeric-type-high q-type))))
1567 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1568 (declare (ignore same-arg))
1569 (if (and (numeric-type-real-p n)
1570 (numeric-type-real-p d))
1571 (ftruncate-derive-type-quot n d)
1574 (defoptimizer (ftruncate derive-type) ((number divisor))
1576 (two-arg-derive-type number divisor
1577 #'ftruncate-derive-type-quot-aux #'ftruncate))
1578 (rem (two-arg-derive-type number divisor
1579 #'truncate-derive-type-rem-aux #'rem)))
1580 (when (and quot rem)
1581 (make-values-type :required (list quot rem)))))
1583 (defun %unary-truncate-derive-type-aux (number)
1584 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1586 (defoptimizer (%unary-truncate derive-type) ((number))
1587 (one-arg-derive-type number
1588 #'%unary-truncate-derive-type-aux
1591 ;;; Define optimizers for FLOOR and CEILING.
1593 ((def (name q-name r-name)
1594 (let ((q-aux (symbolicate q-name "-AUX"))
1595 (r-aux (symbolicate r-name "-AUX")))
1597 ;; Compute type of quotient (first) result.
1598 (defun ,q-aux (number-type divisor-type)
1599 (let* ((number-interval
1600 (numeric-type->interval number-type))
1602 (numeric-type->interval divisor-type))
1603 (quot (,q-name (interval-div number-interval
1604 divisor-interval))))
1605 (specifier-type `(integer ,(or (interval-low quot) '*)
1606 ,(or (interval-high quot) '*)))))
1607 ;; Compute type of remainder.
1608 (defun ,r-aux (number-type divisor-type)
1609 (let* ((divisor-interval
1610 (numeric-type->interval divisor-type))
1611 (rem (,r-name divisor-interval))
1612 (result-type (rem-result-type number-type divisor-type)))
1613 (multiple-value-bind (class format)
1616 (values 'integer nil))
1618 (values 'rational nil))
1619 ((or single-float double-float #!+long-float long-float)
1620 (values 'float result-type))
1622 (values 'float nil))
1625 (when (member result-type '(float single-float double-float
1626 #!+long-float long-float))
1627 ;; Make sure that the limits on the interval have
1629 (setf rem (interval-func (lambda (x)
1630 (coerce x result-type))
1632 (make-numeric-type :class class
1634 :low (interval-low rem)
1635 :high (interval-high rem)))))
1636 ;; the optimizer itself
1637 (defoptimizer (,name derive-type) ((number divisor))
1638 (flet ((derive-q (n d same-arg)
1639 (declare (ignore same-arg))
1640 (if (and (numeric-type-real-p n)
1641 (numeric-type-real-p d))
1644 (derive-r (n d same-arg)
1645 (declare (ignore same-arg))
1646 (if (and (numeric-type-real-p n)
1647 (numeric-type-real-p d))
1650 (let ((quot (two-arg-derive-type
1651 number divisor #'derive-q #',name))
1652 (rem (two-arg-derive-type
1653 number divisor #'derive-r #'mod)))
1654 (when (and quot rem)
1655 (make-values-type :required (list quot rem))))))))))
1657 (def floor floor-quotient-bound floor-rem-bound)
1658 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1660 ;;; Define optimizers for FFLOOR and FCEILING
1661 (macrolet ((def (name q-name r-name)
1662 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1663 (r-aux (symbolicate r-name "-AUX")))
1665 ;; Compute type of quotient (first) result.
1666 (defun ,q-aux (number-type divisor-type)
1667 (let* ((number-interval
1668 (numeric-type->interval number-type))
1670 (numeric-type->interval divisor-type))
1671 (quot (,q-name (interval-div number-interval
1673 (res-type (numeric-contagion number-type
1676 :class (numeric-type-class res-type)
1677 :format (numeric-type-format res-type)
1678 :low (interval-low quot)
1679 :high (interval-high quot))))
1681 (defoptimizer (,name derive-type) ((number divisor))
1682 (flet ((derive-q (n d same-arg)
1683 (declare (ignore same-arg))
1684 (if (and (numeric-type-real-p n)
1685 (numeric-type-real-p d))
1688 (derive-r (n d same-arg)
1689 (declare (ignore same-arg))
1690 (if (and (numeric-type-real-p n)
1691 (numeric-type-real-p d))
1694 (let ((quot (two-arg-derive-type
1695 number divisor #'derive-q #',name))
1696 (rem (two-arg-derive-type
1697 number divisor #'derive-r #'mod)))
1698 (when (and quot rem)
1699 (make-values-type :required (list quot rem))))))))))
1701 (def ffloor floor-quotient-bound floor-rem-bound)
1702 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1704 ;;; functions to compute the bounds on the quotient and remainder for
1705 ;;; the FLOOR function
1706 (defun floor-quotient-bound (quot)
1707 ;; Take the floor of the quotient and then massage it into what we
1709 (let ((lo (interval-low quot))
1710 (hi (interval-high quot)))
1711 ;; Take the floor of the lower bound. The result is always a
1712 ;; closed lower bound.
1714 (floor (type-bound-number lo))
1716 ;; For the upper bound, we need to be careful.
1719 ;; An open bound. We need to be careful here because
1720 ;; the floor of '(10.0) is 9, but the floor of
1722 (multiple-value-bind (q r) (floor (first hi))
1727 ;; A closed bound, so the answer is obvious.
1731 (make-interval :low lo :high hi)))
1732 (defun floor-rem-bound (div)
1733 ;; The remainder depends only on the divisor. Try to get the
1734 ;; correct sign for the remainder if we can.
1735 (case (interval-range-info div)
1737 ;; The divisor is always positive.
1738 (let ((rem (interval-abs div)))
1739 (setf (interval-low rem) 0)
1740 (when (and (numberp (interval-high rem))
1741 (not (zerop (interval-high rem))))
1742 ;; The remainder never contains the upper bound. However,
1743 ;; watch out for the case where the high limit is zero!
1744 (setf (interval-high rem) (list (interval-high rem))))
1747 ;; The divisor is always negative.
1748 (let ((rem (interval-neg (interval-abs div))))
1749 (setf (interval-high rem) 0)
1750 (when (numberp (interval-low rem))
1751 ;; The remainder never contains the lower bound.
1752 (setf (interval-low rem) (list (interval-low rem))))
1755 ;; The divisor can be positive or negative. All bets off. The
1756 ;; magnitude of remainder is the maximum value of the divisor.
1757 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1758 ;; The bound never reaches the limit, so make the interval open.
1759 (make-interval :low (if limit
1762 :high (list limit))))))
1764 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
1765 => #S(INTERVAL :LOW 0 :HIGH 10)
1766 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1767 => #S(INTERVAL :LOW 0 :HIGH 10)
1768 (floor-quotient-bound (make-interval :low 0.3 :high 10))
1769 => #S(INTERVAL :LOW 0 :HIGH 10)
1770 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
1771 => #S(INTERVAL :LOW 0 :HIGH 9)
1772 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
1773 => #S(INTERVAL :LOW 0 :HIGH 10)
1774 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
1775 => #S(INTERVAL :LOW 0 :HIGH 10)
1776 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1777 => #S(INTERVAL :LOW -2 :HIGH 10)
1778 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1779 => #S(INTERVAL :LOW -1 :HIGH 10)
1780 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
1781 => #S(INTERVAL :LOW -1 :HIGH 10)
1783 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
1784 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1785 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
1786 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1787 (floor-rem-bound (make-interval :low -10 :high -2.3))
1788 #S(INTERVAL :LOW (-10) :HIGH 0)
1789 (floor-rem-bound (make-interval :low 0.3 :high 10))
1790 => #S(INTERVAL :LOW 0 :HIGH '(10))
1791 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
1792 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
1793 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
1794 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1797 ;;; same functions for CEILING
1798 (defun ceiling-quotient-bound (quot)
1799 ;; Take the ceiling of the quotient and then massage it into what we
1801 (let ((lo (interval-low quot))
1802 (hi (interval-high quot)))
1803 ;; Take the ceiling of the upper bound. The result is always a
1804 ;; closed upper bound.
1806 (ceiling (type-bound-number hi))
1808 ;; For the lower bound, we need to be careful.
1811 ;; An open bound. We need to be careful here because
1812 ;; the ceiling of '(10.0) is 11, but the ceiling of
1814 (multiple-value-bind (q r) (ceiling (first lo))
1819 ;; A closed bound, so the answer is obvious.
1823 (make-interval :low lo :high hi)))
1824 (defun ceiling-rem-bound (div)
1825 ;; The remainder depends only on the divisor. Try to get the
1826 ;; correct sign for the remainder if we can.
1827 (case (interval-range-info div)
1829 ;; Divisor is always positive. The remainder is negative.
1830 (let ((rem (interval-neg (interval-abs div))))
1831 (setf (interval-high rem) 0)
1832 (when (and (numberp (interval-low rem))
1833 (not (zerop (interval-low rem))))
1834 ;; The remainder never contains the upper bound. However,
1835 ;; watch out for the case when the upper bound is zero!
1836 (setf (interval-low rem) (list (interval-low rem))))
1839 ;; Divisor is always negative. The remainder is positive
1840 (let ((rem (interval-abs div)))
1841 (setf (interval-low rem) 0)
1842 (when (numberp (interval-high rem))
1843 ;; The remainder never contains the lower bound.
1844 (setf (interval-high rem) (list (interval-high rem))))
1847 ;; The divisor can be positive or negative. All bets off. The
1848 ;; magnitude of remainder is the maximum value of the divisor.
1849 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1850 ;; The bound never reaches the limit, so make the interval open.
1851 (make-interval :low (if limit
1854 :high (list limit))))))
1857 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
1858 => #S(INTERVAL :LOW 1 :HIGH 11)
1859 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1860 => #S(INTERVAL :LOW 1 :HIGH 11)
1861 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
1862 => #S(INTERVAL :LOW 1 :HIGH 10)
1863 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
1864 => #S(INTERVAL :LOW 1 :HIGH 10)
1865 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
1866 => #S(INTERVAL :LOW 1 :HIGH 11)
1867 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
1868 => #S(INTERVAL :LOW 1 :HIGH 11)
1869 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1870 => #S(INTERVAL :LOW -1 :HIGH 11)
1871 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1872 => #S(INTERVAL :LOW 0 :HIGH 11)
1873 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
1874 => #S(INTERVAL :LOW -1 :HIGH 11)
1876 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
1877 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
1878 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
1879 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1880 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
1881 => #S(INTERVAL :LOW 0 :HIGH (10))
1882 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
1883 => #S(INTERVAL :LOW (-10) :HIGH 0)
1884 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
1885 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
1886 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
1887 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1890 (defun truncate-quotient-bound (quot)
1891 ;; For positive quotients, truncate is exactly like floor. For
1892 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
1893 ;; it's the union of the two pieces.
1894 (case (interval-range-info quot)
1897 (floor-quotient-bound quot))
1899 ;; just like CEILING
1900 (ceiling-quotient-bound quot))
1902 ;; Split the interval into positive and negative pieces, compute
1903 ;; the result for each piece and put them back together.
1904 (destructuring-bind (neg pos) (interval-split 0 quot t t)
1905 (interval-merge-pair (ceiling-quotient-bound neg)
1906 (floor-quotient-bound pos))))))
1908 (defun truncate-rem-bound (num div)
1909 ;; This is significantly more complicated than FLOOR or CEILING. We
1910 ;; need both the number and the divisor to determine the range. The
1911 ;; basic idea is to split the ranges of NUM and DEN into positive
1912 ;; and negative pieces and deal with each of the four possibilities
1914 (case (interval-range-info num)
1916 (case (interval-range-info div)
1918 (floor-rem-bound div))
1920 (ceiling-rem-bound div))
1922 (destructuring-bind (neg pos) (interval-split 0 div t t)
1923 (interval-merge-pair (truncate-rem-bound num neg)
1924 (truncate-rem-bound num pos))))))
1926 (case (interval-range-info div)
1928 (ceiling-rem-bound div))
1930 (floor-rem-bound div))
1932 (destructuring-bind (neg pos) (interval-split 0 div t t)
1933 (interval-merge-pair (truncate-rem-bound num neg)
1934 (truncate-rem-bound num pos))))))
1936 (destructuring-bind (neg pos) (interval-split 0 num t t)
1937 (interval-merge-pair (truncate-rem-bound neg div)
1938 (truncate-rem-bound pos div))))))
1941 ;;; Derive useful information about the range. Returns three values:
1942 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
1943 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
1944 ;;; - The abs of the maximal value if there is one, or nil if it is
1946 (defun numeric-range-info (low high)
1947 (cond ((and low (not (minusp low)))
1948 (values '+ low high))
1949 ((and high (not (plusp high)))
1950 (values '- (- high) (if low (- low) nil)))
1952 (values nil 0 (and low high (max (- low) high))))))
1954 (defun integer-truncate-derive-type
1955 (number-low number-high divisor-low divisor-high)
1956 ;; The result cannot be larger in magnitude than the number, but the
1957 ;; sign might change. If we can determine the sign of either the
1958 ;; number or the divisor, we can eliminate some of the cases.
1959 (multiple-value-bind (number-sign number-min number-max)
1960 (numeric-range-info number-low number-high)
1961 (multiple-value-bind (divisor-sign divisor-min divisor-max)
1962 (numeric-range-info divisor-low divisor-high)
1963 (when (and divisor-max (zerop divisor-max))
1964 ;; We've got a problem: guaranteed division by zero.
1965 (return-from integer-truncate-derive-type t))
1966 (when (zerop divisor-min)
1967 ;; We'll assume that they aren't going to divide by zero.
1969 (cond ((and number-sign divisor-sign)
1970 ;; We know the sign of both.
1971 (if (eq number-sign divisor-sign)
1972 ;; Same sign, so the result will be positive.
1973 `(integer ,(if divisor-max
1974 (truncate number-min divisor-max)
1977 (truncate number-max divisor-min)
1979 ;; Different signs, the result will be negative.
1980 `(integer ,(if number-max
1981 (- (truncate number-max divisor-min))
1984 (- (truncate number-min divisor-max))
1986 ((eq divisor-sign '+)
1987 ;; The divisor is positive. Therefore, the number will just
1988 ;; become closer to zero.
1989 `(integer ,(if number-low
1990 (truncate number-low divisor-min)
1993 (truncate number-high divisor-min)
1995 ((eq divisor-sign '-)
1996 ;; The divisor is negative. Therefore, the absolute value of
1997 ;; the number will become closer to zero, but the sign will also
1999 `(integer ,(if number-high
2000 (- (truncate number-high divisor-min))
2003 (- (truncate number-low divisor-min))
2005 ;; The divisor could be either positive or negative.
2007 ;; The number we are dividing has a bound. Divide that by the
2008 ;; smallest posible divisor.
2009 (let ((bound (truncate number-max divisor-min)))
2010 `(integer ,(- bound) ,bound)))
2012 ;; The number we are dividing is unbounded, so we can't tell
2013 ;; anything about the result.
2016 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2017 (defun integer-rem-derive-type
2018 (number-low number-high divisor-low divisor-high)
2019 (if (and divisor-low divisor-high)
2020 ;; We know the range of the divisor, and the remainder must be
2021 ;; smaller than the divisor. We can tell the sign of the
2022 ;; remainer if we know the sign of the number.
2023 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2024 `(integer ,(if (or (null number-low)
2025 (minusp number-low))
2028 ,(if (or (null number-high)
2029 (plusp number-high))
2032 ;; The divisor is potentially either very positive or very
2033 ;; negative. Therefore, the remainer is unbounded, but we might
2034 ;; be able to tell something about the sign from the number.
2035 `(integer ,(if (and number-low (not (minusp number-low)))
2036 ;; The number we are dividing is positive.
2037 ;; Therefore, the remainder must be positive.
2040 ,(if (and number-high (not (plusp number-high)))
2041 ;; The number we are dividing is negative.
2042 ;; Therefore, the remainder must be negative.
2046 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2047 (defoptimizer (random derive-type) ((bound &optional state))
2048 (let ((type (lvar-type bound)))
2049 (when (numeric-type-p type)
2050 (let ((class (numeric-type-class type))
2051 (high (numeric-type-high type))
2052 (format (numeric-type-format type)))
2056 :low (coerce 0 (or format class 'real))
2057 :high (cond ((not high) nil)
2058 ((eq class 'integer) (max (1- high) 0))
2059 ((or (consp high) (zerop high)) high)
2062 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2063 (defun random-derive-type-aux (type)
2064 (let ((class (numeric-type-class type))
2065 (high (numeric-type-high type))
2066 (format (numeric-type-format type)))
2070 :low (coerce 0 (or format class 'real))
2071 :high (cond ((not high) nil)
2072 ((eq class 'integer) (max (1- high) 0))
2073 ((or (consp high) (zerop high)) high)
2076 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2077 (defoptimizer (random derive-type) ((bound &optional state))
2078 (one-arg-derive-type bound #'random-derive-type-aux nil))
2080 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2082 ;;; Return the maximum number of bits an integer of the supplied type
2083 ;;; can take up, or NIL if it is unbounded. The second (third) value
2084 ;;; is T if the integer can be positive (negative) and NIL if not.
2085 ;;; Zero counts as positive.
2086 (defun integer-type-length (type)
2087 (if (numeric-type-p type)
2088 (let ((min (numeric-type-low type))
2089 (max (numeric-type-high type)))
2090 (values (and min max (max (integer-length min) (integer-length max)))
2091 (or (null max) (not (minusp max)))
2092 (or (null min) (minusp min))))
2095 (defun logand-derive-type-aux (x y &optional same-leaf)
2096 (declare (ignore same-leaf))
2097 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2098 (declare (ignore x-pos))
2099 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2100 (declare (ignore y-pos))
2102 ;; X must be positive.
2104 ;; They must both be positive.
2105 (cond ((or (null x-len) (null y-len))
2106 (specifier-type 'unsigned-byte))
2108 (specifier-type `(unsigned-byte* ,(min x-len y-len)))))
2109 ;; X is positive, but Y might be negative.
2111 (specifier-type 'unsigned-byte))
2113 (specifier-type `(unsigned-byte* ,x-len)))))
2114 ;; X might be negative.
2116 ;; Y must be positive.
2118 (specifier-type 'unsigned-byte))
2119 (t (specifier-type `(unsigned-byte* ,y-len))))
2120 ;; Either might be negative.
2121 (if (and x-len y-len)
2122 ;; The result is bounded.
2123 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2124 ;; We can't tell squat about the result.
2125 (specifier-type 'integer)))))))
2127 (defun logior-derive-type-aux (x y &optional same-leaf)
2128 (declare (ignore same-leaf))
2129 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2130 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2132 ((and (not x-neg) (not y-neg))
2133 ;; Both are positive.
2134 (specifier-type `(unsigned-byte* ,(if (and x-len y-len)
2138 ;; X must be negative.
2140 ;; Both are negative. The result is going to be negative
2141 ;; and be the same length or shorter than the smaller.
2142 (if (and x-len y-len)
2144 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2146 (specifier-type '(integer * -1)))
2147 ;; X is negative, but we don't know about Y. The result
2148 ;; will be negative, but no more negative than X.
2150 `(integer ,(or (numeric-type-low x) '*)
2153 ;; X might be either positive or negative.
2155 ;; But Y is negative. The result will be negative.
2157 `(integer ,(or (numeric-type-low y) '*)
2159 ;; We don't know squat about either. It won't get any bigger.
2160 (if (and x-len y-len)
2162 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2164 (specifier-type 'integer))))))))
2166 (defun logxor-derive-type-aux (x y &optional same-leaf)
2167 (declare (ignore same-leaf))
2168 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2169 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2171 ((or (and (not x-neg) (not y-neg))
2172 (and (not x-pos) (not y-pos)))
2173 ;; Either both are negative or both are positive. The result
2174 ;; will be positive, and as long as the longer.
2175 (specifier-type `(unsigned-byte* ,(if (and x-len y-len)
2178 ((or (and (not x-pos) (not y-neg))
2179 (and (not y-neg) (not y-pos)))
2180 ;; Either X is negative and Y is positive of vice-versa. The
2181 ;; result will be negative.
2182 (specifier-type `(integer ,(if (and x-len y-len)
2183 (ash -1 (max x-len y-len))
2186 ;; We can't tell what the sign of the result is going to be.
2187 ;; All we know is that we don't create new bits.
2189 (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2191 (specifier-type 'integer))))))
2193 (macrolet ((deffrob (logfun)
2194 (let ((fun-aux (symbolicate logfun "-DERIVE-TYPE-AUX")))
2195 `(defoptimizer (,logfun derive-type) ((x y))
2196 (two-arg-derive-type x y #',fun-aux #',logfun)))))
2201 ;;;; miscellaneous derive-type methods
2203 (defoptimizer (integer-length derive-type) ((x))
2204 (let ((x-type (lvar-type x)))
2205 (when (and (numeric-type-p x-type)
2206 (csubtypep x-type (specifier-type 'integer)))
2207 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2208 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2209 ;; careful about LO or HI being NIL, though. Also, if 0 is
2210 ;; contained in X, the lower bound is obviously 0.
2211 (flet ((null-or-min (a b)
2212 (and a b (min (integer-length a)
2213 (integer-length b))))
2215 (and a b (max (integer-length a)
2216 (integer-length b)))))
2217 (let* ((min (numeric-type-low x-type))
2218 (max (numeric-type-high x-type))
2219 (min-len (null-or-min min max))
2220 (max-len (null-or-max min max)))
2221 (when (ctypep 0 x-type)
2223 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2225 (defoptimizer (code-char derive-type) ((code))
2226 (specifier-type 'base-char))
2228 (defoptimizer (values derive-type) ((&rest values))
2229 (make-values-type :required (mapcar #'lvar-type values)))
2231 ;;;; byte operations
2233 ;;;; We try to turn byte operations into simple logical operations.
2234 ;;;; First, we convert byte specifiers into separate size and position
2235 ;;;; arguments passed to internal %FOO functions. We then attempt to
2236 ;;;; transform the %FOO functions into boolean operations when the
2237 ;;;; size and position are constant and the operands are fixnums.
2239 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2240 ;; expressions that evaluate to the SIZE and POSITION of
2241 ;; the byte-specifier form SPEC. We may wrap a let around
2242 ;; the result of the body to bind some variables.
2244 ;; If the spec is a BYTE form, then bind the vars to the
2245 ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2246 ;; and BYTE-POSITION. The goal of this transformation is to
2247 ;; avoid consing up byte specifiers and then immediately
2248 ;; throwing them away.
2249 (with-byte-specifier ((size-var pos-var spec) &body body)
2250 (once-only ((spec `(macroexpand ,spec))
2252 `(if (and (consp ,spec)
2253 (eq (car ,spec) 'byte)
2254 (= (length ,spec) 3))
2255 (let ((,size-var (second ,spec))
2256 (,pos-var (third ,spec)))
2258 (let ((,size-var `(byte-size ,,temp))
2259 (,pos-var `(byte-position ,,temp)))
2260 `(let ((,,temp ,,spec))
2263 (define-source-transform ldb (spec int)
2264 (with-byte-specifier (size pos spec)
2265 `(%ldb ,size ,pos ,int)))
2267 (define-source-transform dpb (newbyte spec int)
2268 (with-byte-specifier (size pos spec)
2269 `(%dpb ,newbyte ,size ,pos ,int)))
2271 (define-source-transform mask-field (spec int)
2272 (with-byte-specifier (size pos spec)
2273 `(%mask-field ,size ,pos ,int)))
2275 (define-source-transform deposit-field (newbyte spec int)
2276 (with-byte-specifier (size pos spec)
2277 `(%deposit-field ,newbyte ,size ,pos ,int))))
2279 (defoptimizer (%ldb derive-type) ((size posn num))
2280 (let ((size (lvar-type size)))
2281 (if (and (numeric-type-p size)
2282 (csubtypep size (specifier-type 'integer)))
2283 (let ((size-high (numeric-type-high size)))
2284 (if (and size-high (<= size-high sb!vm:n-word-bits))
2285 (specifier-type `(unsigned-byte* ,size-high))
2286 (specifier-type 'unsigned-byte)))
2289 (defoptimizer (%mask-field derive-type) ((size posn num))
2290 (let ((size (lvar-type size))
2291 (posn (lvar-type posn)))
2292 (if (and (numeric-type-p size)
2293 (csubtypep size (specifier-type 'integer))
2294 (numeric-type-p posn)
2295 (csubtypep posn (specifier-type 'integer)))
2296 (let ((size-high (numeric-type-high size))
2297 (posn-high (numeric-type-high posn)))
2298 (if (and size-high posn-high
2299 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2300 (specifier-type `(unsigned-byte* ,(+ size-high posn-high)))
2301 (specifier-type 'unsigned-byte)))
2304 (defun %deposit-field-derive-type-aux (size posn int)
2305 (let ((size (lvar-type size))
2306 (posn (lvar-type posn))
2307 (int (lvar-type int)))
2308 (when (and (numeric-type-p size)
2309 (numeric-type-p posn)
2310 (numeric-type-p int))
2311 (let ((size-high (numeric-type-high size))
2312 (posn-high (numeric-type-high posn))
2313 (high (numeric-type-high int))
2314 (low (numeric-type-low int)))
2315 (when (and size-high posn-high high low
2316 ;; KLUDGE: we need this cutoff here, otherwise we
2317 ;; will merrily derive the type of %DPB as
2318 ;; (UNSIGNED-BYTE 1073741822), and then attempt to
2319 ;; canonicalize this type to (INTEGER 0 (1- (ASH 1
2320 ;; 1073741822))), with hilarious consequences. We
2321 ;; cutoff at 4*SB!VM:N-WORD-BITS to allow inference
2322 ;; over a reasonable amount of shifting, even on
2323 ;; the alpha/32 port, where N-WORD-BITS is 32 but
2324 ;; machine integers are 64-bits. -- CSR,
2326 (<= (+ size-high posn-high) (* 4 sb!vm:n-word-bits)))
2327 (let ((raw-bit-count (max (integer-length high)
2328 (integer-length low)
2329 (+ size-high posn-high))))
2332 `(signed-byte ,(1+ raw-bit-count))
2333 `(unsigned-byte* ,raw-bit-count)))))))))
2335 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2336 (%deposit-field-derive-type-aux size posn int))
2338 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2339 (%deposit-field-derive-type-aux size posn int))
2341 (deftransform %ldb ((size posn int)
2342 (fixnum fixnum integer)
2343 (unsigned-byte #.sb!vm:n-word-bits))
2344 "convert to inline logical operations"
2345 `(logand (ash int (- posn))
2346 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2347 (- size ,sb!vm:n-word-bits))))
2349 (deftransform %mask-field ((size posn int)
2350 (fixnum fixnum integer)
2351 (unsigned-byte #.sb!vm:n-word-bits))
2352 "convert to inline logical operations"
2354 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2355 (- size ,sb!vm:n-word-bits))
2358 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2359 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2360 ;;; as the result type, as that would allow result types that cover
2361 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2362 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2364 (deftransform %dpb ((new size posn int)
2366 (unsigned-byte #.sb!vm:n-word-bits))
2367 "convert to inline logical operations"
2368 `(let ((mask (ldb (byte size 0) -1)))
2369 (logior (ash (logand new mask) posn)
2370 (logand int (lognot (ash mask posn))))))
2372 (deftransform %dpb ((new size posn int)
2374 (signed-byte #.sb!vm:n-word-bits))
2375 "convert to inline logical operations"
2376 `(let ((mask (ldb (byte size 0) -1)))
2377 (logior (ash (logand new mask) posn)
2378 (logand int (lognot (ash mask posn))))))
2380 (deftransform %deposit-field ((new size posn int)
2382 (unsigned-byte #.sb!vm:n-word-bits))
2383 "convert to inline logical operations"
2384 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2385 (logior (logand new mask)
2386 (logand int (lognot mask)))))
2388 (deftransform %deposit-field ((new size posn int)
2390 (signed-byte #.sb!vm:n-word-bits))
2391 "convert to inline logical operations"
2392 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2393 (logior (logand new mask)
2394 (logand int (lognot mask)))))
2396 ;;; Modular functions
2398 ;;; (ldb (byte s 0) (foo x y ...)) =
2399 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2401 ;;; and similar for other arguments.
2403 ;;; Try to recursively cut all uses of the continuation CONT to WIDTH
2406 ;;; For good functions, we just recursively cut arguments; their
2407 ;;; "goodness" means that the result will not increase (in the
2408 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
2409 ;;; replaced with the version, cutting its result to WIDTH or more
2410 ;;; bits. If we have changed anything, we need to flush old derived
2411 ;;; types, because they have nothing in common with the new code.
2412 (defun cut-to-width (lvar width)
2413 (declare (type lvar lvar) (type (integer 0) width))
2414 (labels ((reoptimize-node (node name)
2415 (setf (node-derived-type node)
2417 (info :function :type name)))
2418 (setf (lvar-%derived-type (node-lvar node)) nil)
2419 (setf (node-reoptimize node) t)
2420 (setf (block-reoptimize (node-block node)) t)
2421 (setf (component-reoptimize (node-component node)) t))
2422 (cut-node (node &aux did-something)
2423 (when (and (combination-p node)
2424 (fun-info-p (basic-combination-kind node)))
2425 (let* ((fun-ref (lvar-use (combination-fun node)))
2426 (fun-name (leaf-source-name (ref-leaf fun-ref)))
2427 (modular-fun (find-modular-version fun-name width))
2428 (name (and (modular-fun-info-p modular-fun)
2429 (modular-fun-info-name modular-fun))))
2430 (when (and modular-fun
2431 (not (and (eq name 'logand)
2433 (single-value-type (node-derived-type node))
2434 (specifier-type `(unsigned-byte ,width))))))
2435 (unless (eq modular-fun :good)
2436 (setq did-something t)
2439 (find-free-fun name "in a strange place"))
2440 (setf (combination-kind node) :full))
2441 (dolist (arg (basic-combination-args node))
2442 (when (cut-lvar arg)
2443 (setq did-something t)))
2445 (reoptimize-node node fun-name))
2447 (cut-lvar (lvar &aux did-something)
2448 (do-uses (node lvar)
2449 (when (cut-node node)
2450 (setq did-something t)))
2454 (defoptimizer (logand optimizer) ((x y) node)
2455 (let ((result-type (single-value-type (node-derived-type node))))
2456 (when (numeric-type-p result-type)
2457 (let ((low (numeric-type-low result-type))
2458 (high (numeric-type-high result-type)))
2459 (when (and (numberp low)
2462 (let ((width (integer-length high)))
2463 (when (some (lambda (x) (<= width x))
2464 *modular-funs-widths*)
2465 ;; FIXME: This should be (CUT-TO-WIDTH NODE WIDTH).
2466 (cut-to-width x width)
2467 (cut-to-width y width)
2468 nil ; After fixing above, replace with T.
2471 ;;; miscellanous numeric transforms
2473 ;;; If a constant appears as the first arg, swap the args.
2474 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
2475 (if (and (constant-lvar-p x)
2476 (not (constant-lvar-p y)))
2477 `(,(lvar-fun-name (basic-combination-fun node))
2480 (give-up-ir1-transform)))
2482 (dolist (x '(= char= + * logior logand logxor))
2483 (%deftransform x '(function * *) #'commutative-arg-swap
2484 "place constant arg last"))
2486 ;;; Handle the case of a constant BOOLE-CODE.
2487 (deftransform boole ((op x y) * *)
2488 "convert to inline logical operations"
2489 (unless (constant-lvar-p op)
2490 (give-up-ir1-transform "BOOLE code is not a constant."))
2491 (let ((control (lvar-value op)))
2497 (#.boole-c1 '(lognot x))
2498 (#.boole-c2 '(lognot y))
2499 (#.boole-and '(logand x y))
2500 (#.boole-ior '(logior x y))
2501 (#.boole-xor '(logxor x y))
2502 (#.boole-eqv '(logeqv x y))
2503 (#.boole-nand '(lognand x y))
2504 (#.boole-nor '(lognor x y))
2505 (#.boole-andc1 '(logandc1 x y))
2506 (#.boole-andc2 '(logandc2 x y))
2507 (#.boole-orc1 '(logorc1 x y))
2508 (#.boole-orc2 '(logorc2 x y))
2510 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
2513 ;;;; converting special case multiply/divide to shifts
2515 ;;; If arg is a constant power of two, turn * into a shift.
2516 (deftransform * ((x y) (integer integer) *)
2517 "convert x*2^k to shift"
2518 (unless (constant-lvar-p y)
2519 (give-up-ir1-transform))
2520 (let* ((y (lvar-value y))
2522 (len (1- (integer-length y-abs))))
2523 (unless (= y-abs (ash 1 len))
2524 (give-up-ir1-transform))
2529 ;;; If arg is a constant power of two, turn FLOOR into a shift and
2530 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
2532 (flet ((frob (y ceil-p)
2533 (unless (constant-lvar-p y)
2534 (give-up-ir1-transform))
2535 (let* ((y (lvar-value y))
2537 (len (1- (integer-length y-abs))))
2538 (unless (= y-abs (ash 1 len))
2539 (give-up-ir1-transform))
2540 (let ((shift (- len))
2542 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
2543 `(let ((x (+ x ,delta)))
2545 `(values (ash (- x) ,shift)
2546 (- (- (logand (- x) ,mask)) ,delta))
2547 `(values (ash x ,shift)
2548 (- (logand x ,mask) ,delta))))))))
2549 (deftransform floor ((x y) (integer integer) *)
2550 "convert division by 2^k to shift"
2552 (deftransform ceiling ((x y) (integer integer) *)
2553 "convert division by 2^k to shift"
2556 ;;; Do the same for MOD.
2557 (deftransform mod ((x y) (integer integer) *)
2558 "convert remainder mod 2^k to LOGAND"
2559 (unless (constant-lvar-p y)
2560 (give-up-ir1-transform))
2561 (let* ((y (lvar-value y))
2563 (len (1- (integer-length y-abs))))
2564 (unless (= y-abs (ash 1 len))
2565 (give-up-ir1-transform))
2566 (let ((mask (1- y-abs)))
2568 `(- (logand (- x) ,mask))
2569 `(logand x ,mask)))))
2571 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
2572 (deftransform truncate ((x y) (integer integer))
2573 "convert division by 2^k to shift"
2574 (unless (constant-lvar-p y)
2575 (give-up-ir1-transform))
2576 (let* ((y (lvar-value y))
2578 (len (1- (integer-length y-abs))))
2579 (unless (= y-abs (ash 1 len))
2580 (give-up-ir1-transform))
2581 (let* ((shift (- len))
2584 (values ,(if (minusp y)
2586 `(- (ash (- x) ,shift)))
2587 (- (logand (- x) ,mask)))
2588 (values ,(if (minusp y)
2589 `(- (ash (- x) ,shift))
2591 (logand x ,mask))))))
2593 ;;; And the same for REM.
2594 (deftransform rem ((x y) (integer integer) *)
2595 "convert remainder mod 2^k to LOGAND"
2596 (unless (constant-lvar-p y)
2597 (give-up-ir1-transform))
2598 (let* ((y (lvar-value y))
2600 (len (1- (integer-length y-abs))))
2601 (unless (= y-abs (ash 1 len))
2602 (give-up-ir1-transform))
2603 (let ((mask (1- y-abs)))
2605 (- (logand (- x) ,mask))
2606 (logand x ,mask)))))
2608 ;;;; arithmetic and logical identity operation elimination
2610 ;;; Flush calls to various arith functions that convert to the
2611 ;;; identity function or a constant.
2612 (macrolet ((def (name identity result)
2613 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
2614 "fold identity operations"
2621 (def logxor -1 (lognot x))
2624 (deftransform logand ((x y) (* (constant-arg t)) *)
2625 "fold identity operation"
2626 (let ((y (lvar-value y)))
2627 (unless (and (plusp y)
2628 (= y (1- (ash 1 (integer-length y)))))
2629 (give-up-ir1-transform))
2630 (unless (csubtypep (lvar-type x)
2631 (specifier-type `(integer 0 ,y)))
2632 (give-up-ir1-transform))
2635 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
2636 ;;; (* 0 -4.0) is -0.0.
2637 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
2638 "convert (- 0 x) to negate"
2640 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
2641 "convert (* x 0) to 0"
2644 ;;; Return T if in an arithmetic op including continuations X and Y,
2645 ;;; the result type is not affected by the type of X. That is, Y is at
2646 ;;; least as contagious as X.
2648 (defun not-more-contagious (x y)
2649 (declare (type continuation x y))
2650 (let ((x (lvar-type x))
2652 (values (type= (numeric-contagion x y)
2653 (numeric-contagion y y)))))
2654 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
2655 ;;; XXX needs more work as valid transforms are missed; some cases are
2656 ;;; specific to particular transform functions so the use of this
2657 ;;; function may need a re-think.
2658 (defun not-more-contagious (x y)
2659 (declare (type lvar x y))
2660 (flet ((simple-numeric-type (num)
2661 (and (numeric-type-p num)
2662 ;; Return non-NIL if NUM is integer, rational, or a float
2663 ;; of some type (but not FLOAT)
2664 (case (numeric-type-class num)
2668 (numeric-type-format num))
2671 (let ((x (lvar-type x))
2673 (if (and (simple-numeric-type x)
2674 (simple-numeric-type y))
2675 (values (type= (numeric-contagion x y)
2676 (numeric-contagion y y)))))))
2680 ;;; If y is not constant, not zerop, or is contagious, or a positive
2681 ;;; float +0.0 then give up.
2682 (deftransform + ((x y) (t (constant-arg t)) *)
2684 (let ((val (lvar-value y)))
2685 (unless (and (zerop val)
2686 (not (and (floatp val) (plusp (float-sign val))))
2687 (not-more-contagious y x))
2688 (give-up-ir1-transform)))
2693 ;;; If y is not constant, not zerop, or is contagious, or a negative
2694 ;;; float -0.0 then give up.
2695 (deftransform - ((x y) (t (constant-arg t)) *)
2697 (let ((val (lvar-value y)))
2698 (unless (and (zerop val)
2699 (not (and (floatp val) (minusp (float-sign val))))
2700 (not-more-contagious y x))
2701 (give-up-ir1-transform)))
2704 ;;; Fold (OP x +/-1)
2705 (macrolet ((def (name result minus-result)
2706 `(deftransform ,name ((x y) (t (constant-arg real)) *)
2707 "fold identity operations"
2708 (let ((val (lvar-value y)))
2709 (unless (and (= (abs val) 1)
2710 (not-more-contagious y x))
2711 (give-up-ir1-transform))
2712 (if (minusp val) ',minus-result ',result)))))
2713 (def * x (%negate x))
2714 (def / x (%negate x))
2715 (def expt x (/ 1 x)))
2717 ;;; Fold (expt x n) into multiplications for small integral values of
2718 ;;; N; convert (expt x 1/2) to sqrt.
2719 (deftransform expt ((x y) (t (constant-arg real)) *)
2720 "recode as multiplication or sqrt"
2721 (let ((val (lvar-value y)))
2722 ;; If Y would cause the result to be promoted to the same type as
2723 ;; Y, we give up. If not, then the result will be the same type
2724 ;; as X, so we can replace the exponentiation with simple
2725 ;; multiplication and division for small integral powers.
2726 (unless (not-more-contagious y x)
2727 (give-up-ir1-transform))
2729 (let ((x-type (lvar-type x)))
2730 (cond ((csubtypep x-type (specifier-type '(or rational
2731 (complex rational))))
2733 ((csubtypep x-type (specifier-type 'real))
2737 ((csubtypep x-type (specifier-type 'complex))
2738 ;; both parts are float
2740 (t (give-up-ir1-transform)))))
2741 ((= val 2) '(* x x))
2742 ((= val -2) '(/ (* x x)))
2743 ((= val 3) '(* x x x))
2744 ((= val -3) '(/ (* x x x)))
2745 ((= val 1/2) '(sqrt x))
2746 ((= val -1/2) '(/ (sqrt x)))
2747 (t (give-up-ir1-transform)))))
2749 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
2750 ;;; transformations?
2751 ;;; Perhaps we should have to prove that the denominator is nonzero before
2752 ;;; doing them? -- WHN 19990917
2753 (macrolet ((def (name)
2754 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2761 (macrolet ((def (name)
2762 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
2771 ;;;; character operations
2773 (deftransform char-equal ((a b) (base-char base-char))
2775 '(let* ((ac (char-code a))
2777 (sum (logxor ac bc)))
2779 (when (eql sum #x20)
2780 (let ((sum (+ ac bc)))
2781 (and (> sum 161) (< sum 213)))))))
2783 (deftransform char-upcase ((x) (base-char))
2785 '(let ((n-code (char-code x)))
2786 (if (and (> n-code #o140) ; Octal 141 is #\a.
2787 (< n-code #o173)) ; Octal 172 is #\z.
2788 (code-char (logxor #x20 n-code))
2791 (deftransform char-downcase ((x) (base-char))
2793 '(let ((n-code (char-code x)))
2794 (if (and (> n-code 64) ; 65 is #\A.
2795 (< n-code 91)) ; 90 is #\Z.
2796 (code-char (logxor #x20 n-code))
2799 ;;;; equality predicate transforms
2801 ;;; Return true if X and Y are continuations whose only use is a
2802 ;;; reference to the same leaf, and the value of the leaf cannot
2804 (defun same-leaf-ref-p (x y)
2805 (declare (type lvar x y))
2806 (let ((x-use (principal-lvar-use x))
2807 (y-use (principal-lvar-use y)))
2810 (eq (ref-leaf x-use) (ref-leaf y-use))
2811 (constant-reference-p x-use))))
2813 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
2814 ;;; if there is no intersection between the types of the arguments,
2815 ;;; then the result is definitely false.
2816 (deftransform simple-equality-transform ((x y) * *
2818 (cond ((same-leaf-ref-p x y)
2820 ((not (types-equal-or-intersect (lvar-type x)
2824 (give-up-ir1-transform))))
2827 `(%deftransform ',x '(function * *) #'simple-equality-transform)))
2832 ;;; This is similar to SIMPLE-EQUALITY-PREDICATE, except that we also
2833 ;;; try to convert to a type-specific predicate or EQ:
2834 ;;; -- If both args are characters, convert to CHAR=. This is better than
2835 ;;; just converting to EQ, since CHAR= may have special compilation
2836 ;;; strategies for non-standard representations, etc.
2837 ;;; -- If either arg is definitely not a number, then we can compare
2839 ;;; -- Otherwise, we try to put the arg we know more about second. If X
2840 ;;; is constant then we put it second. If X is a subtype of Y, we put
2841 ;;; it second. These rules make it easier for the back end to match
2842 ;;; these interesting cases.
2843 ;;; -- If Y is a fixnum, then we quietly pass because the back end can
2844 ;;; handle that case, otherwise give an efficiency note.
2845 (deftransform eql ((x y) * *)
2846 "convert to simpler equality predicate"
2847 (let ((x-type (lvar-type x))
2848 (y-type (lvar-type y))
2849 (char-type (specifier-type 'character))
2850 (number-type (specifier-type 'number)))
2851 (cond ((same-leaf-ref-p x y)
2853 ((not (types-equal-or-intersect x-type y-type))
2855 ((and (csubtypep x-type char-type)
2856 (csubtypep y-type char-type))
2858 ((or (not (types-equal-or-intersect x-type number-type))
2859 (not (types-equal-or-intersect y-type number-type)))
2861 ((and (not (constant-lvar-p y))
2862 (or (constant-lvar-p x)
2863 (and (csubtypep x-type y-type)
2864 (not (csubtypep y-type x-type)))))
2867 (give-up-ir1-transform)))))
2869 ;;; Convert to EQL if both args are rational and complexp is specified
2870 ;;; and the same for both.
2871 (deftransform = ((x y) * *)
2873 (let ((x-type (lvar-type x))
2874 (y-type (lvar-type y)))
2875 (if (and (csubtypep x-type (specifier-type 'number))
2876 (csubtypep y-type (specifier-type 'number)))
2877 (cond ((or (and (csubtypep x-type (specifier-type 'float))
2878 (csubtypep y-type (specifier-type 'float)))
2879 (and (csubtypep x-type (specifier-type '(complex float)))
2880 (csubtypep y-type (specifier-type '(complex float)))))
2881 ;; They are both floats. Leave as = so that -0.0 is
2882 ;; handled correctly.
2883 (give-up-ir1-transform))
2884 ((or (and (csubtypep x-type (specifier-type 'rational))
2885 (csubtypep y-type (specifier-type 'rational)))
2886 (and (csubtypep x-type
2887 (specifier-type '(complex rational)))
2889 (specifier-type '(complex rational)))))
2890 ;; They are both rationals and complexp is the same.
2894 (give-up-ir1-transform
2895 "The operands might not be the same type.")))
2896 (give-up-ir1-transform
2897 "The operands might not be the same type."))))
2899 ;;; If CONT's type is a numeric type, then return the type, otherwise
2900 ;;; GIVE-UP-IR1-TRANSFORM.
2901 (defun numeric-type-or-lose (lvar)
2902 (declare (type lvar lvar))
2903 (let ((res (lvar-type lvar)))
2904 (unless (numeric-type-p res) (give-up-ir1-transform))
2907 ;;; See whether we can statically determine (< X Y) using type
2908 ;;; information. If X's high bound is < Y's low, then X < Y.
2909 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
2910 ;;; NIL). If not, at least make sure any constant arg is second.
2912 ;;; FIXME: Why should constant argument be second? It would be nice to
2913 ;;; find out and explain.
2914 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2915 (defun ir1-transform-< (x y first second inverse)
2916 (if (same-leaf-ref-p x y)
2918 (let* ((x-type (numeric-type-or-lose x))
2919 (x-lo (numeric-type-low x-type))
2920 (x-hi (numeric-type-high x-type))
2921 (y-type (numeric-type-or-lose y))
2922 (y-lo (numeric-type-low y-type))
2923 (y-hi (numeric-type-high y-type)))
2924 (cond ((and x-hi y-lo (< x-hi y-lo))
2926 ((and y-hi x-lo (>= x-lo y-hi))
2928 ((and (constant-lvar-p first)
2929 (not (constant-lvar-p second)))
2932 (give-up-ir1-transform))))))
2933 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2934 (defun ir1-transform-< (x y first second inverse)
2935 (if (same-leaf-ref-p x y)
2937 (let ((xi (numeric-type->interval (numeric-type-or-lose x)))
2938 (yi (numeric-type->interval (numeric-type-or-lose y))))
2939 (cond ((interval-< xi yi)
2941 ((interval->= xi yi)
2943 ((and (constant-lvar-p first)
2944 (not (constant-lvar-p second)))
2947 (give-up-ir1-transform))))))
2949 (deftransform < ((x y) (integer integer) *)
2950 (ir1-transform-< x y x y '>))
2952 (deftransform > ((x y) (integer integer) *)
2953 (ir1-transform-< y x x y '<))
2955 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2956 (deftransform < ((x y) (float float) *)
2957 (ir1-transform-< x y x y '>))
2959 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2960 (deftransform > ((x y) (float float) *)
2961 (ir1-transform-< y x x y '<))
2963 (defun ir1-transform-char< (x y first second inverse)
2965 ((same-leaf-ref-p x y) nil)
2966 ;; If we had interval representation of character types, as we
2967 ;; might eventually have to to support 2^21 characters, then here
2968 ;; we could do some compile-time computation as in IR1-TRANSFORM-<
2969 ;; above. -- CSR, 2003-07-01
2970 ((and (constant-lvar-p first)
2971 (not (constant-lvar-p second)))
2973 (t (give-up-ir1-transform))))
2975 (deftransform char< ((x y) (character character) *)
2976 (ir1-transform-char< x y x y 'char>))
2978 (deftransform char> ((x y) (character character) *)
2979 (ir1-transform-char< y x x y 'char<))
2981 ;;;; converting N-arg comparisons
2983 ;;;; We convert calls to N-arg comparison functions such as < into
2984 ;;;; two-arg calls. This transformation is enabled for all such
2985 ;;;; comparisons in this file. If any of these predicates are not
2986 ;;;; open-coded, then the transformation should be removed at some
2987 ;;;; point to avoid pessimization.
2989 ;;; This function is used for source transformation of N-arg
2990 ;;; comparison functions other than inequality. We deal both with
2991 ;;; converting to two-arg calls and inverting the sense of the test,
2992 ;;; if necessary. If the call has two args, then we pass or return a
2993 ;;; negated test as appropriate. If it is a degenerate one-arg call,
2994 ;;; then we transform to code that returns true. Otherwise, we bind
2995 ;;; all the arguments and expand into a bunch of IFs.
2996 (declaim (ftype (function (symbol list boolean t) *) multi-compare))
2997 (defun multi-compare (predicate args not-p type)
2998 (let ((nargs (length args)))
2999 (cond ((< nargs 1) (values nil t))
3000 ((= nargs 1) `(progn (the ,type ,@args) t))
3003 `(if (,predicate ,(first args) ,(second args)) nil t)
3006 (do* ((i (1- nargs) (1- i))
3008 (current (gensym) (gensym))
3009 (vars (list current) (cons current vars))
3011 `(if (,predicate ,current ,last)
3013 `(if (,predicate ,current ,last)
3016 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3019 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
3020 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
3021 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
3022 (define-source-transform <= (&rest args) (multi-compare '> args t 'real))
3023 (define-source-transform >= (&rest args) (multi-compare '< args t 'real))
3025 (define-source-transform char= (&rest args) (multi-compare 'char= args nil
3027 (define-source-transform char< (&rest args) (multi-compare 'char< args nil
3029 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
3031 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
3033 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
3036 (define-source-transform char-equal (&rest args)
3037 (multi-compare 'char-equal args nil 'character))
3038 (define-source-transform char-lessp (&rest args)
3039 (multi-compare 'char-lessp args nil 'character))
3040 (define-source-transform char-greaterp (&rest args)
3041 (multi-compare 'char-greaterp args nil 'character))
3042 (define-source-transform char-not-greaterp (&rest args)
3043 (multi-compare 'char-greaterp args t 'character))
3044 (define-source-transform char-not-lessp (&rest args)
3045 (multi-compare 'char-lessp args t 'character))
3047 ;;; This function does source transformation of N-arg inequality
3048 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3049 ;;; arg cases. If there are more than two args, then we expand into
3050 ;;; the appropriate n^2 comparisons only when speed is important.
3051 (declaim (ftype (function (symbol list t) *) multi-not-equal))
3052 (defun multi-not-equal (predicate args type)
3053 (let ((nargs (length args)))
3054 (cond ((< nargs 1) (values nil t))
3055 ((= nargs 1) `(progn (the ,type ,@args) t))
3057 `(if (,predicate ,(first args) ,(second args)) nil t))
3058 ((not (policy *lexenv*
3059 (and (>= speed space)
3060 (>= speed compilation-speed))))
3063 (let ((vars (make-gensym-list nargs)))
3064 (do ((var vars next)
3065 (next (cdr vars) (cdr next))
3068 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3070 (let ((v1 (first var)))
3072 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3074 (define-source-transform /= (&rest args)
3075 (multi-not-equal '= args 'number))
3076 (define-source-transform char/= (&rest args)
3077 (multi-not-equal 'char= args 'character))
3078 (define-source-transform char-not-equal (&rest args)
3079 (multi-not-equal 'char-equal args 'character))
3081 ;;; Expand MAX and MIN into the obvious comparisons.
3082 (define-source-transform max (arg0 &rest rest)
3083 (once-only ((arg0 arg0))
3085 `(values (the real ,arg0))
3086 `(let ((maxrest (max ,@rest)))
3087 (if (> ,arg0 maxrest) ,arg0 maxrest)))))
3088 (define-source-transform min (arg0 &rest rest)
3089 (once-only ((arg0 arg0))
3091 `(values (the real ,arg0))
3092 `(let ((minrest (min ,@rest)))
3093 (if (< ,arg0 minrest) ,arg0 minrest)))))
3095 ;;;; converting N-arg arithmetic functions
3097 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3098 ;;;; versions, and degenerate cases are flushed.
3100 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3101 (declaim (ftype (function (symbol t list) list) associate-args))
3102 (defun associate-args (function first-arg more-args)
3103 (let ((next (rest more-args))
3104 (arg (first more-args)))
3106 `(,function ,first-arg ,arg)
3107 (associate-args function `(,function ,first-arg ,arg) next))))
3109 ;;; Do source transformations for transitive functions such as +.
3110 ;;; One-arg cases are replaced with the arg and zero arg cases with
3111 ;;; the identity. ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3112 ;;; ensure (with THE) that the argument in one-argument calls is.
3113 (defun source-transform-transitive (fun args identity
3114 &optional one-arg-result-type)
3115 (declare (symbol fun) (list args))
3118 (1 (if one-arg-result-type
3119 `(values (the ,one-arg-result-type ,(first args)))
3120 `(values ,(first args))))
3123 (associate-args fun (first args) (rest args)))))
3125 (define-source-transform + (&rest args)
3126 (source-transform-transitive '+ args 0 'number))
3127 (define-source-transform * (&rest args)
3128 (source-transform-transitive '* args 1 'number))
3129 (define-source-transform logior (&rest args)
3130 (source-transform-transitive 'logior args 0 'integer))
3131 (define-source-transform logxor (&rest args)
3132 (source-transform-transitive 'logxor args 0 'integer))
3133 (define-source-transform logand (&rest args)
3134 (source-transform-transitive 'logand args -1 'integer))
3136 (define-source-transform logeqv (&rest args)
3137 (if (evenp (length args))
3138 `(lognot (logxor ,@args))
3141 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3142 ;;; because when they are given one argument, they return its absolute
3145 (define-source-transform gcd (&rest args)
3148 (1 `(abs (the integer ,(first args))))
3150 (t (associate-args 'gcd (first args) (rest args)))))
3152 (define-source-transform lcm (&rest args)
3155 (1 `(abs (the integer ,(first args))))
3157 (t (associate-args 'lcm (first args) (rest args)))))
3159 ;;; Do source transformations for intransitive n-arg functions such as
3160 ;;; /. With one arg, we form the inverse. With two args we pass.
3161 ;;; Otherwise we associate into two-arg calls.
3162 (declaim (ftype (function (symbol list t)
3163 (values list &optional (member nil t)))
3164 source-transform-intransitive))
3165 (defun source-transform-intransitive (function args inverse)
3167 ((0 2) (values nil t))
3168 (1 `(,@inverse ,(first args)))
3169 (t (associate-args function (first args) (rest args)))))
3171 (define-source-transform - (&rest args)
3172 (source-transform-intransitive '- args '(%negate)))
3173 (define-source-transform / (&rest args)
3174 (source-transform-intransitive '/ args '(/ 1)))
3176 ;;;; transforming APPLY
3178 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3179 ;;; only needs to understand one kind of variable-argument call. It is
3180 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3181 (define-source-transform apply (fun arg &rest more-args)
3182 (let ((args (cons arg more-args)))
3183 `(multiple-value-call ,fun
3184 ,@(mapcar (lambda (x)
3187 (values-list ,(car (last args))))))
3189 ;;;; transforming FORMAT
3191 ;;;; If the control string is a compile-time constant, then replace it
3192 ;;;; with a use of the FORMATTER macro so that the control string is
3193 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3194 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3195 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3197 ;;; for compile-time argument count checking.
3199 ;;; FIXME I: this is currently called from DEFTRANSFORMs, the vast
3200 ;;; majority of which are not going to transform the code, but instead
3201 ;;; are going to GIVE-UP-IR1-TRANSFORM unconditionally. It would be
3202 ;;; nice to make this explicit, maybe by implementing a new
3203 ;;; "optimizer" (say, DEFOPTIMIZER CONSISTENCY-CHECK).
3205 ;;; FIXME II: In some cases, type information could be correlated; for
3206 ;;; instance, ~{ ... ~} requires a list argument, so if the
3207 ;;; continuation-type of a corresponding argument is known and does
3208 ;;; not intersect the list type, a warning could be signalled.
3209 (defun check-format-args (string args fun)
3210 (declare (type string string))
3211 (unless (typep string 'simple-string)
3212 (setq string (coerce string 'simple-string)))
3213 (multiple-value-bind (min max)
3214 (handler-case (sb!format:%compiler-walk-format-string string args)
3215 (sb!format:format-error (c)
3216 (compiler-warn "~A" c)))
3218 (let ((nargs (length args)))
3221 (compiler-warn "Too few arguments (~D) to ~S ~S: ~
3222 requires at least ~D."
3223 nargs fun string min))
3225 (;; to get warned about probably bogus code at
3226 ;; cross-compile time.
3227 #+sb-xc-host compiler-warn
3228 ;; ANSI saith that too many arguments doesn't cause a
3230 #-sb-xc-host compiler-style-warn
3231 "Too many arguments (~D) to ~S ~S: uses at most ~D."
3232 nargs fun string max)))))))
3234 (defoptimizer (format optimizer) ((dest control &rest args))
3235 (when (constant-lvar-p control)
3236 (let ((x (lvar-value control)))
3238 (check-format-args x args 'format)))))
3240 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3241 :policy (> speed space))
3242 (unless (constant-lvar-p control)
3243 (give-up-ir1-transform "The control string is not a constant."))
3244 (let ((arg-names (make-gensym-list (length args))))
3245 `(lambda (dest control ,@arg-names)
3246 (declare (ignore control))
3247 (format dest (formatter ,(lvar-value control)) ,@arg-names))))
3249 (deftransform format ((stream control &rest args) (stream function &rest t) *
3250 :policy (> speed space))
3251 (let ((arg-names (make-gensym-list (length args))))
3252 `(lambda (stream control ,@arg-names)
3253 (funcall control stream ,@arg-names)
3256 (deftransform format ((tee control &rest args) ((member t) function &rest t) *
3257 :policy (> speed space))
3258 (let ((arg-names (make-gensym-list (length args))))
3259 `(lambda (tee control ,@arg-names)
3260 (declare (ignore tee))
3261 (funcall control *standard-output* ,@arg-names)
3266 `(defoptimizer (,name optimizer) ((control &rest args))
3267 (when (constant-lvar-p control)
3268 (let ((x (lvar-value control)))
3270 (check-format-args x args ',name)))))))
3273 #+sb-xc-host ; Only we should be using these
3276 (def compiler-abort)
3277 (def compiler-error)
3279 (def compiler-style-warn)
3280 (def compiler-notify)
3281 (def maybe-compiler-notify)
3284 (defoptimizer (cerror optimizer) ((report control &rest args))
3285 (when (and (constant-lvar-p control)
3286 (constant-lvar-p report))
3287 (let ((x (lvar-value control))
3288 (y (lvar-value report)))
3289 (when (and (stringp x) (stringp y))
3290 (multiple-value-bind (min1 max1)
3292 (sb!format:%compiler-walk-format-string x args)
3293 (sb!format:format-error (c)
3294 (compiler-warn "~A" c)))
3296 (multiple-value-bind (min2 max2)
3298 (sb!format:%compiler-walk-format-string y args)
3299 (sb!format:format-error (c)
3300 (compiler-warn "~A" c)))
3302 (let ((nargs (length args)))
3304 ((< nargs (min min1 min2))
3305 (compiler-warn "Too few arguments (~D) to ~S ~S ~S: ~
3306 requires at least ~D."
3307 nargs 'cerror y x (min min1 min2)))
3308 ((> nargs (max max1 max2))
3309 (;; to get warned about probably bogus code at
3310 ;; cross-compile time.
3311 #+sb-xc-host compiler-warn
3312 ;; ANSI saith that too many arguments doesn't cause a
3314 #-sb-xc-host compiler-style-warn
3315 "Too many arguments (~D) to ~S ~S ~S: uses at most ~D."
3316 nargs 'cerror y x (max max1 max2)))))))))))))
3318 (defoptimizer (coerce derive-type) ((value type))
3320 ((constant-lvar-p type)
3321 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3322 ;; but dealing with the niggle that complex canonicalization gets
3323 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3325 (let* ((specifier (lvar-value type))
3326 (result-typeoid (careful-specifier-type specifier)))
3328 ((null result-typeoid) nil)
3329 ((csubtypep result-typeoid (specifier-type 'number))
3330 ;; the difficult case: we have to cope with ANSI 12.1.5.3
3331 ;; Rule of Canonical Representation for Complex Rationals,
3332 ;; which is a truly nasty delivery to field.
3334 ((csubtypep result-typeoid (specifier-type 'real))
3335 ;; cleverness required here: it would be nice to deduce
3336 ;; that something of type (INTEGER 2 3) coerced to type
3337 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3338 ;; FLOAT gets its own clause because it's implemented as
3339 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3342 ((and (numeric-type-p result-typeoid)
3343 (eq (numeric-type-complexp result-typeoid) :real))
3344 ;; FIXME: is this clause (a) necessary or (b) useful?
3346 ((or (csubtypep result-typeoid
3347 (specifier-type '(complex single-float)))
3348 (csubtypep result-typeoid
3349 (specifier-type '(complex double-float)))
3351 (csubtypep result-typeoid
3352 (specifier-type '(complex long-float))))
3353 ;; float complex types are never canonicalized.
3356 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
3357 ;; probably just a COMPLEX or equivalent. So, in that
3358 ;; case, we will return a complex or an object of the
3359 ;; provided type if it's rational:
3360 (type-union result-typeoid
3361 (type-intersection (lvar-type value)
3362 (specifier-type 'rational))))))
3363 (t result-typeoid))))
3365 ;; OK, the result-type argument isn't constant. However, there
3366 ;; are common uses where we can still do better than just
3367 ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
3368 ;; where Y is of a known type. See messages on cmucl-imp
3369 ;; 2001-02-14 and sbcl-devel 2002-12-12. We only worry here
3370 ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
3371 ;; the basis that it's unlikely that other uses are both
3372 ;; time-critical and get to this branch of the COND (non-constant
3373 ;; second argument to COERCE). -- CSR, 2002-12-16
3374 (let ((value-type (lvar-type value))
3375 (type-type (lvar-type type)))
3377 ((good-cons-type-p (cons-type)
3378 ;; Make sure the cons-type we're looking at is something
3379 ;; we're prepared to handle which is basically something
3380 ;; that array-element-type can return.
3381 (or (and (member-type-p cons-type)
3382 (null (rest (member-type-members cons-type)))
3383 (null (first (member-type-members cons-type))))
3384 (let ((car-type (cons-type-car-type cons-type)))
3385 (and (member-type-p car-type)
3386 (null (rest (member-type-members car-type)))
3387 (or (symbolp (first (member-type-members car-type)))
3388 (numberp (first (member-type-members car-type)))
3389 (and (listp (first (member-type-members
3391 (numberp (first (first (member-type-members
3393 (good-cons-type-p (cons-type-cdr-type cons-type))))))
3394 (unconsify-type (good-cons-type)
3395 ;; Convert the "printed" respresentation of a cons
3396 ;; specifier into a type specifier. That is, the
3397 ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
3398 ;; NULL)) is converted to (SIGNED-BYTE 16).
3399 (cond ((or (null good-cons-type)
3400 (eq good-cons-type 'null))
3402 ((and (eq (first good-cons-type) 'cons)
3403 (eq (first (second good-cons-type)) 'member))
3404 `(,(second (second good-cons-type))
3405 ,@(unconsify-type (caddr good-cons-type))))))
3406 (coerceable-p (c-type)
3407 ;; Can the value be coerced to the given type? Coerce is
3408 ;; complicated, so we don't handle every possible case
3409 ;; here---just the most common and easiest cases:
3411 ;; * Any REAL can be coerced to a FLOAT type.
3412 ;; * Any NUMBER can be coerced to a (COMPLEX
3413 ;; SINGLE/DOUBLE-FLOAT).
3415 ;; FIXME I: we should also be able to deal with characters
3418 ;; FIXME II: I'm not sure that anything is necessary
3419 ;; here, at least while COMPLEX is not a specialized
3420 ;; array element type in the system. Reasoning: if
3421 ;; something cannot be coerced to the requested type, an
3422 ;; error will be raised (and so any downstream compiled
3423 ;; code on the assumption of the returned type is
3424 ;; unreachable). If something can, then it will be of
3425 ;; the requested type, because (by assumption) COMPLEX
3426 ;; (and other difficult types like (COMPLEX INTEGER)
3427 ;; aren't specialized types.
3428 (let ((coerced-type c-type))
3429 (or (and (subtypep coerced-type 'float)
3430 (csubtypep value-type (specifier-type 'real)))
3431 (and (subtypep coerced-type
3432 '(or (complex single-float)
3433 (complex double-float)))
3434 (csubtypep value-type (specifier-type 'number))))))
3435 (process-types (type)
3436 ;; FIXME: This needs some work because we should be able
3437 ;; to derive the resulting type better than just the
3438 ;; type arg of coerce. That is, if X is (INTEGER 10
3439 ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
3440 ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
3442 (cond ((member-type-p type)
3443 (let ((members (member-type-members type)))
3444 (if (every #'coerceable-p members)
3445 (specifier-type `(or ,@members))
3447 ((and (cons-type-p type)
3448 (good-cons-type-p type))
3449 (let ((c-type (unconsify-type (type-specifier type))))
3450 (if (coerceable-p c-type)
3451 (specifier-type c-type)
3454 *universal-type*))))
3455 (cond ((union-type-p type-type)
3456 (apply #'type-union (mapcar #'process-types
3457 (union-type-types type-type))))
3458 ((or (member-type-p type-type)
3459 (cons-type-p type-type))
3460 (process-types type-type))
3462 *universal-type*)))))))
3464 (defoptimizer (compile derive-type) ((nameoid function))
3465 (when (csubtypep (lvar-type nameoid)
3466 (specifier-type 'null))
3467 (values-specifier-type '(values function boolean boolean))))
3469 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
3470 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
3471 ;;; optimizer, above).
3472 (defoptimizer (array-element-type derive-type) ((array))
3473 (let ((array-type (lvar-type array)))
3474 (labels ((consify (list)
3477 `(cons (eql ,(car list)) ,(consify (rest list)))))
3478 (get-element-type (a)
3480 (type-specifier (array-type-specialized-element-type a))))
3481 (cond ((eq element-type '*)
3482 (specifier-type 'type-specifier))
3483 ((symbolp element-type)
3484 (make-member-type :members (list element-type)))
3485 ((consp element-type)
3486 (specifier-type (consify element-type)))
3488 (error "can't understand type ~S~%" element-type))))))
3489 (cond ((array-type-p array-type)
3490 (get-element-type array-type))
3491 ((union-type-p array-type)
3493 (mapcar #'get-element-type (union-type-types array-type))))
3495 *universal-type*)))))
3497 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
3498 `(macrolet ((%index (x) `(truly-the index ,x))
3499 (%parent (i) `(ash ,i -1))
3500 (%left (i) `(%index (ash ,i 1)))
3501 (%right (i) `(%index (1+ (ash ,i 1))))
3504 (left (%left i) (%left i)))
3505 ((> left current-heap-size))
3506 (declare (type index i left))
3507 (let* ((i-elt (%elt i))
3508 (i-key (funcall keyfun i-elt))
3509 (left-elt (%elt left))
3510 (left-key (funcall keyfun left-elt)))
3511 (multiple-value-bind (large large-elt large-key)
3512 (if (funcall ,',predicate i-key left-key)
3513 (values left left-elt left-key)
3514 (values i i-elt i-key))
3515 (let ((right (%right i)))
3516 (multiple-value-bind (largest largest-elt)
3517 (if (> right current-heap-size)
3518 (values large large-elt)
3519 (let* ((right-elt (%elt right))
3520 (right-key (funcall keyfun right-elt)))
3521 (if (funcall ,',predicate large-key right-key)
3522 (values right right-elt)
3523 (values large large-elt))))
3524 (cond ((= largest i)
3527 (setf (%elt i) largest-elt
3528 (%elt largest) i-elt
3530 (%sort-vector (keyfun &optional (vtype 'vector))
3531 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had trouble getting
3532 ;; type inference to propagate all the way
3533 ;; through this tangled mess of
3534 ;; inlining. The TRULY-THE here works
3535 ;; around that. -- WHN
3537 `(aref (truly-the ,',vtype ,',',vector)
3538 (%index (+ (%index ,i) start-1)))))
3539 (let ((start-1 (1- ,',start)) ; Heaps prefer 1-based addressing.
3540 (current-heap-size (- ,',end ,',start))
3542 (declare (type (integer -1 #.(1- most-positive-fixnum))
3544 (declare (type index current-heap-size))
3545 (declare (type function keyfun))
3546 (loop for i of-type index
3547 from (ash current-heap-size -1) downto 1 do
3550 (when (< current-heap-size 2)
3552 (rotatef (%elt 1) (%elt current-heap-size))
3553 (decf current-heap-size)
3555 (if (typep ,vector 'simple-vector)
3556 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
3557 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
3559 ;; Special-casing the KEY=NIL case lets us avoid some
3561 (%sort-vector #'identity simple-vector)
3562 (%sort-vector ,key simple-vector))
3563 ;; It's hard to anticipate many speed-critical applications for
3564 ;; sorting vector types other than (VECTOR T), so we just lump
3565 ;; them all together in one slow dynamically typed mess.
3567 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
3568 (%sort-vector (or ,key #'identity))))))
3570 ;;;; debuggers' little helpers
3572 ;;; for debugging when transforms are behaving mysteriously,
3573 ;;; e.g. when debugging a problem with an ASH transform
3574 ;;; (defun foo (&optional s)
3575 ;;; (sb-c::/report-continuation s "S outside WHEN")
3576 ;;; (when (and (integerp s) (> s 3))
3577 ;;; (sb-c::/report-continuation s "S inside WHEN")
3578 ;;; (let ((bound (ash 1 (1- s))))
3579 ;;; (sb-c::/report-continuation bound "BOUND")
3580 ;;; (let ((x (- bound))
3582 ;;; (sb-c::/report-continuation x "X")
3583 ;;; (sb-c::/report-continuation x "Y"))
3584 ;;; `(integer ,(- bound) ,(1- bound)))))
3585 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
3586 ;;; and the function doesn't do anything at all.)
3589 (defknown /report-lvar (t t) null)
3590 (deftransform /report-lvar ((x message) (t t))
3591 (format t "~%/in /REPORT-LVAR~%")
3592 (format t "/(LVAR-TYPE X)=~S~%" (lvar-type x))
3593 (when (constant-lvar-p x)
3594 (format t "/(LVAR-VALUE X)=~S~%" (lvar-value x)))
3595 (format t "/MESSAGE=~S~%" (lvar-value message))
3596 (give-up-ir1-transform "not a real transform"))
3597 (defun /report-lvar (x message)
3598 (declare (ignore x message))))