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 (car form))
72 (leaf (leaf-source-name name))))))
73 (do ((i (- (length string) 2) (1- i))
75 `(,(ecase (char string i)
81 ;;; Make source transforms to turn CxR forms into combinations of CAR
82 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
84 (/show0 "about to set CxR source transforms")
85 (loop for i of-type index from 2 upto 4 do
86 ;; Iterate over BUF = all names CxR where x = an I-element
87 ;; string of #\A or #\D characters.
88 (let ((buf (make-string (+ 2 i))))
89 (setf (aref buf 0) #\C
90 (aref buf (1+ i)) #\R)
91 (dotimes (j (ash 2 i))
92 (declare (type index j))
94 (declare (type index k))
95 (setf (aref buf (1+ k))
96 (if (logbitp k j) #\A #\D)))
97 (setf (info :function :source-transform (intern buf))
98 #'source-transform-cxr))))
99 (/show0 "done setting CxR source transforms")
101 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
102 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
103 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
105 (define-source-transform first (x) `(car ,x))
106 (define-source-transform rest (x) `(cdr ,x))
107 (define-source-transform second (x) `(cadr ,x))
108 (define-source-transform third (x) `(caddr ,x))
109 (define-source-transform fourth (x) `(cadddr ,x))
110 (define-source-transform fifth (x) `(nth 4 ,x))
111 (define-source-transform sixth (x) `(nth 5 ,x))
112 (define-source-transform seventh (x) `(nth 6 ,x))
113 (define-source-transform eighth (x) `(nth 7 ,x))
114 (define-source-transform ninth (x) `(nth 8 ,x))
115 (define-source-transform tenth (x) `(nth 9 ,x))
117 ;;; LIST with one arg is an extremely common operation (at least inside
118 ;;; SBCL itself); translate it to CONS to take advantage of common
119 ;;; allocation routines.
120 (define-source-transform list (&rest args)
122 (1 `(cons ,(first args) nil))
125 ;;; And similarly for LIST*.
126 (define-source-transform list* (&rest args)
128 (2 `(cons ,(first args) ,(second args)))
131 ;;; Translate RPLACx to LET and SETF.
132 (define-source-transform rplaca (x y)
137 (define-source-transform rplacd (x y)
143 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
145 (define-source-transform last (x) `(sb!impl::last1 ,x))
146 (define-source-transform gethash (&rest args)
148 (2 `(sb!impl::gethash2 ,@args))
149 (3 `(sb!impl::gethash3 ,@args))
151 (define-source-transform get (&rest args)
153 (2 `(sb!impl::get2 ,@args))
154 (3 `(sb!impl::get3 ,@args))
157 (defvar *default-nthcdr-open-code-limit* 6)
158 (defvar *extreme-nthcdr-open-code-limit* 20)
160 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
161 "convert NTHCDR to CAxxR"
162 (unless (constant-lvar-p n)
163 (give-up-ir1-transform))
164 (let ((n (lvar-value n)))
166 (if (policy node (and (= speed 3) (= space 0)))
167 *extreme-nthcdr-open-code-limit*
168 *default-nthcdr-open-code-limit*))
169 (give-up-ir1-transform))
174 `(cdr ,(frob (1- n))))))
177 ;;;; arithmetic and numerology
179 (define-source-transform plusp (x) `(> ,x 0))
180 (define-source-transform minusp (x) `(< ,x 0))
181 (define-source-transform zerop (x) `(= ,x 0))
183 (define-source-transform 1+ (x) `(+ ,x 1))
184 (define-source-transform 1- (x) `(- ,x 1))
186 (define-source-transform oddp (x) `(logtest ,x 1))
187 (define-source-transform evenp (x) `(not (logtest ,x 1)))
189 ;;; Note that all the integer division functions are available for
190 ;;; inline expansion.
192 (macrolet ((deffrob (fun)
193 `(define-source-transform ,fun (x &optional (y nil y-p))
200 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
202 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
205 ;;; This used to be a source transform (hence the lack of restrictions
206 ;;; on the argument types), but we make it a regular transform so that
207 ;;; the VM has a chance to see the bare LOGTEST and potentiall choose
208 ;;; to implement it differently. --njf, 06-02-2006
209 (deftransform logtest ((x y) * *)
210 `(not (zerop (logand x y))))
212 (deftransform logbitp
213 ((index integer) (unsigned-byte (or (signed-byte #.sb!vm:n-word-bits)
214 (unsigned-byte #.sb!vm:n-word-bits))))
215 `(if (>= index #.sb!vm:n-word-bits)
217 (not (zerop (logand integer (ash 1 index))))))
219 (define-source-transform byte (size position)
220 `(cons ,size ,position))
221 (define-source-transform byte-size (spec) `(car ,spec))
222 (define-source-transform byte-position (spec) `(cdr ,spec))
223 (define-source-transform ldb-test (bytespec integer)
224 `(not (zerop (mask-field ,bytespec ,integer))))
226 ;;; With the ratio and complex accessors, we pick off the "identity"
227 ;;; case, and use a primitive to handle the cell access case.
228 (define-source-transform numerator (num)
229 (once-only ((n-num `(the rational ,num)))
233 (define-source-transform denominator (num)
234 (once-only ((n-num `(the rational ,num)))
236 (%denominator ,n-num)
239 ;;;; interval arithmetic for computing bounds
241 ;;;; This is a set of routines for operating on intervals. It
242 ;;;; implements a simple interval arithmetic package. Although SBCL
243 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
244 ;;;; for two reasons:
246 ;;;; 1. This package is simpler than NUMERIC-TYPE.
248 ;;;; 2. It makes debugging much easier because you can just strip
249 ;;;; out these routines and test them independently of SBCL. (This is a
252 ;;;; One disadvantage is a probable increase in consing because we
253 ;;;; have to create these new interval structures even though
254 ;;;; numeric-type has everything we want to know. Reason 2 wins for
257 ;;; Support operations that mimic real arithmetic comparison
258 ;;; operators, but imposing a total order on the floating points such
259 ;;; that negative zeros are strictly less than positive zeros.
260 (macrolet ((def (name op)
263 (if (and (floatp x) (floatp y) (zerop x) (zerop y))
264 (,op (float-sign x) (float-sign y))
266 (def signed-zero->= >=)
267 (def signed-zero-> >)
268 (def signed-zero-= =)
269 (def signed-zero-< <)
270 (def signed-zero-<= <=))
272 ;;; The basic interval type. It can handle open and closed intervals.
273 ;;; A bound is open if it is a list containing a number, just like
274 ;;; Lisp says. NIL means unbounded.
275 (defstruct (interval (:constructor %make-interval)
279 (defun make-interval (&key low high)
280 (labels ((normalize-bound (val)
283 (float-infinity-p val))
284 ;; Handle infinities.
288 ;; Handle any closed bounds.
291 ;; We have an open bound. Normalize the numeric
292 ;; bound. If the normalized bound is still a number
293 ;; (not nil), keep the bound open. Otherwise, the
294 ;; bound is really unbounded, so drop the openness.
295 (let ((new-val (normalize-bound (first val))))
297 ;; The bound exists, so keep it open still.
300 (error "unknown bound type in MAKE-INTERVAL")))))
301 (%make-interval :low (normalize-bound low)
302 :high (normalize-bound high))))
304 ;;; Given a number X, create a form suitable as a bound for an
305 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
306 #!-sb-fluid (declaim (inline set-bound))
307 (defun set-bound (x open-p)
308 (if (and x open-p) (list x) x))
310 ;;; Apply the function F to a bound X. If X is an open bound, then
311 ;;; the result will be open. IF X is NIL, the result is NIL.
312 (defun bound-func (f x)
313 (declare (type function f))
315 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
316 ;; With these traps masked, we might get things like infinity
317 ;; or negative infinity returned. Check for this and return
318 ;; NIL to indicate unbounded.
319 (let ((y (funcall f (type-bound-number x))))
321 (float-infinity-p y))
323 (set-bound y (consp x)))))))
325 ;;; Apply a binary operator OP to two bounds X and Y. The result is
326 ;;; NIL if either is NIL. Otherwise bound is computed and the result
327 ;;; is open if either X or Y is open.
329 ;;; FIXME: only used in this file, not needed in target runtime
331 ;;; ANSI contaigon specifies coercion to floating point if one of the
332 ;;; arguments is floating point. Here we should check to be sure that
333 ;;; the other argument is within the bounds of that floating point
336 (defmacro safely-binop (op x y)
338 ((typep ,x 'single-float)
339 (if (or (typep ,y 'single-float)
340 (<= most-negative-single-float ,y most-positive-single-float))
342 ((typep ,x 'double-float)
343 (if (or (typep ,y 'double-float)
344 (<= most-negative-double-float ,y most-positive-double-float))
346 ((typep ,y 'single-float)
347 (if (<= most-negative-single-float ,x most-positive-single-float)
349 ((typep ,y 'double-float)
350 (if (<= most-negative-double-float ,x most-positive-double-float)
354 (defmacro bound-binop (op x y)
356 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
357 (set-bound (safely-binop ,op (type-bound-number ,x)
358 (type-bound-number ,y))
359 (or (consp ,x) (consp ,y))))))
361 (defun coerce-for-bound (val type)
363 (list (coerce-for-bound (car val) type))
365 ((subtypep type 'double-float)
366 (if (<= most-negative-double-float val most-positive-double-float)
368 ((or (subtypep type 'single-float) (subtypep type 'float))
369 ;; coerce to float returns a single-float
370 (if (<= most-negative-single-float val most-positive-single-float)
372 (t (coerce val type)))))
374 (defun coerce-and-truncate-floats (val type)
377 (list (coerce-and-truncate-floats (car val) type))
379 ((subtypep type 'double-float)
380 (if (<= most-negative-double-float val most-positive-double-float)
382 (if (< val most-negative-double-float)
383 most-negative-double-float most-positive-double-float)))
384 ((or (subtypep type 'single-float) (subtypep type 'float))
385 ;; coerce to float returns a single-float
386 (if (<= most-negative-single-float val most-positive-single-float)
388 (if (< val most-negative-single-float)
389 most-negative-single-float most-positive-single-float)))
390 (t (coerce val type))))))
392 ;;; Convert a numeric-type object to an interval object.
393 (defun numeric-type->interval (x)
394 (declare (type numeric-type x))
395 (make-interval :low (numeric-type-low x)
396 :high (numeric-type-high x)))
398 (defun type-approximate-interval (type)
399 (declare (type ctype type))
400 (let ((types (prepare-arg-for-derive-type type))
403 (let ((type (if (member-type-p type)
404 (convert-member-type type)
406 (unless (numeric-type-p type)
407 (return-from type-approximate-interval nil))
408 (let ((interval (numeric-type->interval type)))
411 (interval-approximate-union result interval)
415 (defun copy-interval-limit (limit)
420 (defun copy-interval (x)
421 (declare (type interval x))
422 (make-interval :low (copy-interval-limit (interval-low x))
423 :high (copy-interval-limit (interval-high x))))
425 ;;; Given a point P contained in the interval X, split X into two
426 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
427 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
428 ;;; contains P. You can specify both to be T or NIL.
429 (defun interval-split (p x &optional close-lower close-upper)
430 (declare (type number p)
432 (list (make-interval :low (copy-interval-limit (interval-low x))
433 :high (if close-lower p (list p)))
434 (make-interval :low (if close-upper (list p) p)
435 :high (copy-interval-limit (interval-high x)))))
437 ;;; Return the closure of the interval. That is, convert open bounds
438 ;;; to closed bounds.
439 (defun interval-closure (x)
440 (declare (type interval x))
441 (make-interval :low (type-bound-number (interval-low x))
442 :high (type-bound-number (interval-high x))))
444 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
445 ;;; '-. Otherwise return NIL.
446 (defun interval-range-info (x &optional (point 0))
447 (declare (type interval x))
448 (let ((lo (interval-low x))
449 (hi (interval-high x)))
450 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
452 ((and hi (signed-zero->= point (type-bound-number hi)))
457 ;;; Test to see whether the interval X is bounded. HOW determines the
458 ;;; test, and should be either ABOVE, BELOW, or BOTH.
459 (defun interval-bounded-p (x how)
460 (declare (type interval x))
467 (and (interval-low x) (interval-high x)))))
469 ;;; See whether the interval X contains the number P, taking into
470 ;;; account that the interval might not be closed.
471 (defun interval-contains-p (p x)
472 (declare (type number p)
474 ;; Does the interval X contain the number P? This would be a lot
475 ;; easier if all intervals were closed!
476 (let ((lo (interval-low x))
477 (hi (interval-high x)))
479 ;; The interval is bounded
480 (if (and (signed-zero-<= (type-bound-number lo) p)
481 (signed-zero-<= p (type-bound-number hi)))
482 ;; P is definitely in the closure of the interval.
483 ;; We just need to check the end points now.
484 (cond ((signed-zero-= p (type-bound-number lo))
486 ((signed-zero-= p (type-bound-number hi))
491 ;; Interval with upper bound
492 (if (signed-zero-< p (type-bound-number hi))
494 (and (numberp hi) (signed-zero-= p hi))))
496 ;; Interval with lower bound
497 (if (signed-zero-> p (type-bound-number lo))
499 (and (numberp lo) (signed-zero-= p lo))))
501 ;; Interval with no bounds
504 ;;; Determine whether two intervals X and Y intersect. Return T if so.
505 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
506 ;;; were closed. Otherwise the intervals are treated as they are.
508 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
509 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
510 ;;; is T, then they do intersect because we use the closure of X = [0,
511 ;;; 1] and Y = [1, 2] to determine intersection.
512 (defun interval-intersect-p (x y &optional closed-intervals-p)
513 (declare (type interval x y))
514 (multiple-value-bind (intersect diff)
515 (interval-intersection/difference (if closed-intervals-p
518 (if closed-intervals-p
521 (declare (ignore diff))
524 ;;; Are the two intervals adjacent? That is, is there a number
525 ;;; between the two intervals that is not an element of either
526 ;;; interval? If so, they are not adjacent. For example [0, 1) and
527 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
528 ;;; between both intervals.
529 (defun interval-adjacent-p (x y)
530 (declare (type interval x y))
531 (flet ((adjacent (lo hi)
532 ;; Check to see whether lo and hi are adjacent. If either is
533 ;; nil, they can't be adjacent.
534 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
535 ;; The bounds are equal. They are adjacent if one of
536 ;; them is closed (a number). If both are open (consp),
537 ;; then there is a number that lies between them.
538 (or (numberp lo) (numberp hi)))))
539 (or (adjacent (interval-low y) (interval-high x))
540 (adjacent (interval-low x) (interval-high y)))))
542 ;;; Compute the intersection and difference between two intervals.
543 ;;; Two values are returned: the intersection and the difference.
545 ;;; Let the two intervals be X and Y, and let I and D be the two
546 ;;; values returned by this function. Then I = X intersect Y. If I
547 ;;; is NIL (the empty set), then D is X union Y, represented as the
548 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
549 ;;; - I, which is a list of two intervals.
551 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
552 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
553 (defun interval-intersection/difference (x y)
554 (declare (type interval x y))
555 (let ((x-lo (interval-low x))
556 (x-hi (interval-high x))
557 (y-lo (interval-low y))
558 (y-hi (interval-high y)))
561 ;; If p is an open bound, make it closed. If p is a closed
562 ;; bound, make it open.
567 ;; Test whether P is in the interval.
568 (when (interval-contains-p (type-bound-number p)
569 (interval-closure int))
570 (let ((lo (interval-low int))
571 (hi (interval-high int)))
572 ;; Check for endpoints.
573 (cond ((and lo (= (type-bound-number p) (type-bound-number lo)))
574 (not (and (consp p) (numberp lo))))
575 ((and hi (= (type-bound-number p) (type-bound-number hi)))
576 (not (and (numberp p) (consp hi))))
578 (test-lower-bound (p int)
579 ;; P is a lower bound of an interval.
582 (not (interval-bounded-p int 'below))))
583 (test-upper-bound (p int)
584 ;; P is an upper bound of an interval.
587 (not (interval-bounded-p int 'above)))))
588 (let ((x-lo-in-y (test-lower-bound x-lo y))
589 (x-hi-in-y (test-upper-bound x-hi y))
590 (y-lo-in-x (test-lower-bound y-lo x))
591 (y-hi-in-x (test-upper-bound y-hi x)))
592 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
593 ;; Intervals intersect. Let's compute the intersection
594 ;; and the difference.
595 (multiple-value-bind (lo left-lo left-hi)
596 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
597 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
598 (multiple-value-bind (hi right-lo right-hi)
600 (values x-hi (opposite-bound x-hi) y-hi))
602 (values y-hi (opposite-bound y-hi) x-hi)))
603 (values (make-interval :low lo :high hi)
604 (list (make-interval :low left-lo
606 (make-interval :low right-lo
609 (values nil (list x y))))))))
611 ;;; If intervals X and Y intersect, return a new interval that is the
612 ;;; union of the two. If they do not intersect, return NIL.
613 (defun interval-merge-pair (x y)
614 (declare (type interval x y))
615 ;; If x and y intersect or are adjacent, create the union.
616 ;; Otherwise return nil
617 (when (or (interval-intersect-p x y)
618 (interval-adjacent-p x y))
619 (flet ((select-bound (x1 x2 min-op max-op)
620 (let ((x1-val (type-bound-number x1))
621 (x2-val (type-bound-number x2)))
623 ;; Both bounds are finite. Select the right one.
624 (cond ((funcall min-op x1-val x2-val)
625 ;; x1 is definitely better.
627 ((funcall max-op x1-val x2-val)
628 ;; x2 is definitely better.
631 ;; Bounds are equal. Select either
632 ;; value and make it open only if
634 (set-bound x1-val (and (consp x1) (consp x2))))))
636 ;; At least one bound is not finite. The
637 ;; non-finite bound always wins.
639 (let* ((x-lo (copy-interval-limit (interval-low x)))
640 (x-hi (copy-interval-limit (interval-high x)))
641 (y-lo (copy-interval-limit (interval-low y)))
642 (y-hi (copy-interval-limit (interval-high y))))
643 (make-interval :low (select-bound x-lo y-lo #'< #'>)
644 :high (select-bound x-hi y-hi #'> #'<))))))
646 ;;; return the minimal interval, containing X and Y
647 (defun interval-approximate-union (x y)
648 (cond ((interval-merge-pair x y))
650 (make-interval :low (copy-interval-limit (interval-low x))
651 :high (copy-interval-limit (interval-high y))))
653 (make-interval :low (copy-interval-limit (interval-low y))
654 :high (copy-interval-limit (interval-high x))))))
656 ;;; basic arithmetic operations on intervals. We probably should do
657 ;;; true interval arithmetic here, but it's complicated because we
658 ;;; have float and integer types and bounds can be open or closed.
660 ;;; the negative of an interval
661 (defun interval-neg (x)
662 (declare (type interval x))
663 (make-interval :low (bound-func #'- (interval-high x))
664 :high (bound-func #'- (interval-low x))))
666 ;;; Add two intervals.
667 (defun interval-add (x y)
668 (declare (type interval x y))
669 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
670 :high (bound-binop + (interval-high x) (interval-high y))))
672 ;;; Subtract two intervals.
673 (defun interval-sub (x y)
674 (declare (type interval x y))
675 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
676 :high (bound-binop - (interval-high x) (interval-low y))))
678 ;;; Multiply two intervals.
679 (defun interval-mul (x y)
680 (declare (type interval x y))
681 (flet ((bound-mul (x y)
682 (cond ((or (null x) (null y))
683 ;; Multiply by infinity is infinity
685 ((or (and (numberp x) (zerop x))
686 (and (numberp y) (zerop y)))
687 ;; Multiply by closed zero is special. The result
688 ;; is always a closed bound. But don't replace this
689 ;; with zero; we want the multiplication to produce
690 ;; the correct signed zero, if needed.
691 (* (type-bound-number x) (type-bound-number y)))
692 ((or (and (floatp x) (float-infinity-p x))
693 (and (floatp y) (float-infinity-p y)))
694 ;; Infinity times anything is infinity
697 ;; General multiply. The result is open if either is open.
698 (bound-binop * x y)))))
699 (let ((x-range (interval-range-info x))
700 (y-range (interval-range-info y)))
701 (cond ((null x-range)
702 ;; Split x into two and multiply each separately
703 (destructuring-bind (x- x+) (interval-split 0 x t t)
704 (interval-merge-pair (interval-mul x- y)
705 (interval-mul x+ y))))
707 ;; Split y into two and multiply each separately
708 (destructuring-bind (y- y+) (interval-split 0 y t t)
709 (interval-merge-pair (interval-mul x y-)
710 (interval-mul x y+))))
712 (interval-neg (interval-mul (interval-neg x) y)))
714 (interval-neg (interval-mul x (interval-neg y))))
715 ((and (eq x-range '+) (eq y-range '+))
716 ;; If we are here, X and Y are both positive.
718 :low (bound-mul (interval-low x) (interval-low y))
719 :high (bound-mul (interval-high x) (interval-high y))))
721 (bug "excluded case in INTERVAL-MUL"))))))
723 ;;; Divide two intervals.
724 (defun interval-div (top bot)
725 (declare (type interval top bot))
726 (flet ((bound-div (x y y-low-p)
729 ;; Divide by infinity means result is 0. However,
730 ;; we need to watch out for the sign of the result,
731 ;; to correctly handle signed zeros. We also need
732 ;; to watch out for positive or negative infinity.
733 (if (floatp (type-bound-number x))
735 (- (float-sign (type-bound-number x) 0.0))
736 (float-sign (type-bound-number x) 0.0))
738 ((zerop (type-bound-number y))
739 ;; Divide by zero means result is infinity
741 ((and (numberp x) (zerop x))
742 ;; Zero divided by anything is zero.
745 (bound-binop / x y)))))
746 (let ((top-range (interval-range-info top))
747 (bot-range (interval-range-info bot)))
748 (cond ((null bot-range)
749 ;; The denominator contains zero, so anything goes!
750 (make-interval :low nil :high nil))
752 ;; Denominator is negative so flip the sign, compute the
753 ;; result, and flip it back.
754 (interval-neg (interval-div top (interval-neg bot))))
756 ;; Split top into two positive and negative parts, and
757 ;; divide each separately
758 (destructuring-bind (top- top+) (interval-split 0 top t t)
759 (interval-merge-pair (interval-div top- bot)
760 (interval-div top+ bot))))
762 ;; Top is negative so flip the sign, divide, and flip the
763 ;; sign of the result.
764 (interval-neg (interval-div (interval-neg top) bot)))
765 ((and (eq top-range '+) (eq bot-range '+))
768 :low (bound-div (interval-low top) (interval-high bot) t)
769 :high (bound-div (interval-high top) (interval-low bot) nil)))
771 (bug "excluded case in INTERVAL-DIV"))))))
773 ;;; Apply the function F to the interval X. If X = [a, b], then the
774 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
775 ;;; result makes sense. It will if F is monotonic increasing (or
777 (defun interval-func (f x)
778 (declare (type function f)
780 (let ((lo (bound-func f (interval-low x)))
781 (hi (bound-func f (interval-high x))))
782 (make-interval :low lo :high hi)))
784 ;;; Return T if X < Y. That is every number in the interval X is
785 ;;; always less than any number in the interval Y.
786 (defun interval-< (x y)
787 (declare (type interval x y))
788 ;; X < Y only if X is bounded above, Y is bounded below, and they
790 (when (and (interval-bounded-p x 'above)
791 (interval-bounded-p y 'below))
792 ;; Intervals are bounded in the appropriate way. Make sure they
794 (let ((left (interval-high x))
795 (right (interval-low y)))
796 (cond ((> (type-bound-number left)
797 (type-bound-number right))
798 ;; The intervals definitely overlap, so result is NIL.
800 ((< (type-bound-number left)
801 (type-bound-number right))
802 ;; The intervals definitely don't touch, so result is T.
805 ;; Limits are equal. Check for open or closed bounds.
806 ;; Don't overlap if one or the other are open.
807 (or (consp left) (consp right)))))))
809 ;;; Return T if X >= Y. That is, every number in the interval X is
810 ;;; always greater than any number in the interval Y.
811 (defun interval->= (x y)
812 (declare (type interval x y))
813 ;; X >= Y if lower bound of X >= upper bound of Y
814 (when (and (interval-bounded-p x 'below)
815 (interval-bounded-p y 'above))
816 (>= (type-bound-number (interval-low x))
817 (type-bound-number (interval-high y)))))
819 ;;; Return an interval that is the absolute value of X. Thus, if
820 ;;; X = [-1 10], the result is [0, 10].
821 (defun interval-abs (x)
822 (declare (type interval x))
823 (case (interval-range-info x)
829 (destructuring-bind (x- x+) (interval-split 0 x t t)
830 (interval-merge-pair (interval-neg x-) x+)))))
832 ;;; Compute the square of an interval.
833 (defun interval-sqr (x)
834 (declare (type interval x))
835 (interval-func (lambda (x) (* x x))
838 ;;;; numeric DERIVE-TYPE methods
840 ;;; a utility for defining derive-type methods of integer operations. If
841 ;;; the types of both X and Y are integer types, then we compute a new
842 ;;; integer type with bounds determined Fun when applied to X and Y.
843 ;;; Otherwise, we use NUMERIC-CONTAGION.
844 (defun derive-integer-type-aux (x y fun)
845 (declare (type function fun))
846 (if (and (numeric-type-p x) (numeric-type-p y)
847 (eq (numeric-type-class x) 'integer)
848 (eq (numeric-type-class y) 'integer)
849 (eq (numeric-type-complexp x) :real)
850 (eq (numeric-type-complexp y) :real))
851 (multiple-value-bind (low high) (funcall fun x y)
852 (make-numeric-type :class 'integer
856 (numeric-contagion x y)))
858 (defun derive-integer-type (x y fun)
859 (declare (type lvar x y) (type function fun))
860 (let ((x (lvar-type x))
862 (derive-integer-type-aux x y fun)))
864 ;;; simple utility to flatten a list
865 (defun flatten-list (x)
866 (labels ((flatten-and-append (tree list)
867 (cond ((null tree) list)
868 ((atom tree) (cons tree list))
869 (t (flatten-and-append
870 (car tree) (flatten-and-append (cdr tree) list))))))
871 (flatten-and-append x nil)))
873 ;;; Take some type of lvar and massage it so that we get a list of the
874 ;;; constituent types. If ARG is *EMPTY-TYPE*, return NIL to indicate
876 (defun prepare-arg-for-derive-type (arg)
877 (flet ((listify (arg)
882 (union-type-types arg))
885 (unless (eq arg *empty-type*)
886 ;; Make sure all args are some type of numeric-type. For member
887 ;; types, convert the list of members into a union of equivalent
888 ;; single-element member-type's.
889 (let ((new-args nil))
890 (dolist (arg (listify arg))
891 (if (member-type-p arg)
892 ;; Run down the list of members and convert to a list of
894 (dolist (member (member-type-members arg))
895 (push (if (numberp member)
896 (make-member-type :members (list member))
899 (push arg new-args)))
900 (unless (member *empty-type* new-args)
903 ;;; Convert from the standard type convention for which -0.0 and 0.0
904 ;;; are equal to an intermediate convention for which they are
905 ;;; considered different which is more natural for some of the
907 (defun convert-numeric-type (type)
908 (declare (type numeric-type type))
909 ;;; Only convert real float interval delimiters types.
910 (if (eq (numeric-type-complexp type) :real)
911 (let* ((lo (numeric-type-low type))
912 (lo-val (type-bound-number lo))
913 (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
914 (hi (numeric-type-high type))
915 (hi-val (type-bound-number hi))
916 (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
917 (if (or lo-float-zero-p hi-float-zero-p)
919 :class (numeric-type-class type)
920 :format (numeric-type-format type)
922 :low (if lo-float-zero-p
924 (list (float 0.0 lo-val))
925 (float (load-time-value (make-unportable-float :single-float-negative-zero)) lo-val))
927 :high (if hi-float-zero-p
929 (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val))
936 ;;; Convert back from the intermediate convention for which -0.0 and
937 ;;; 0.0 are considered different to the standard type convention for
939 (defun convert-back-numeric-type (type)
940 (declare (type numeric-type type))
941 ;;; Only convert real float interval delimiters types.
942 (if (eq (numeric-type-complexp type) :real)
943 (let* ((lo (numeric-type-low type))
944 (lo-val (type-bound-number lo))
946 (and lo (floatp lo-val) (= lo-val 0.0)
947 (float-sign lo-val)))
948 (hi (numeric-type-high type))
949 (hi-val (type-bound-number hi))
951 (and hi (floatp hi-val) (= hi-val 0.0)
952 (float-sign hi-val))))
954 ;; (float +0.0 +0.0) => (member 0.0)
955 ;; (float -0.0 -0.0) => (member -0.0)
956 ((and lo-float-zero-p hi-float-zero-p)
957 ;; shouldn't have exclusive bounds here..
958 (aver (and (not (consp lo)) (not (consp hi))))
959 (if (= lo-float-zero-p hi-float-zero-p)
960 ;; (float +0.0 +0.0) => (member 0.0)
961 ;; (float -0.0 -0.0) => (member -0.0)
962 (specifier-type `(member ,lo-val))
963 ;; (float -0.0 +0.0) => (float 0.0 0.0)
964 ;; (float +0.0 -0.0) => (float 0.0 0.0)
965 (make-numeric-type :class (numeric-type-class type)
966 :format (numeric-type-format type)
972 ;; (float -0.0 x) => (float 0.0 x)
973 ((and (not (consp lo)) (minusp lo-float-zero-p))
974 (make-numeric-type :class (numeric-type-class type)
975 :format (numeric-type-format type)
977 :low (float 0.0 lo-val)
979 ;; (float (+0.0) x) => (float (0.0) x)
980 ((and (consp lo) (plusp lo-float-zero-p))
981 (make-numeric-type :class (numeric-type-class type)
982 :format (numeric-type-format type)
984 :low (list (float 0.0 lo-val))
987 ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
988 ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
989 (list (make-member-type :members (list (float 0.0 lo-val)))
990 (make-numeric-type :class (numeric-type-class type)
991 :format (numeric-type-format type)
993 :low (list (float 0.0 lo-val))
997 ;; (float x +0.0) => (float x 0.0)
998 ((and (not (consp hi)) (plusp hi-float-zero-p))
999 (make-numeric-type :class (numeric-type-class type)
1000 :format (numeric-type-format type)
1003 :high (float 0.0 hi-val)))
1004 ;; (float x (-0.0)) => (float x (0.0))
1005 ((and (consp hi) (minusp hi-float-zero-p))
1006 (make-numeric-type :class (numeric-type-class type)
1007 :format (numeric-type-format type)
1010 :high (list (float 0.0 hi-val))))
1012 ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
1013 ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
1014 (list (make-member-type :members (list (float -0.0 hi-val)))
1015 (make-numeric-type :class (numeric-type-class type)
1016 :format (numeric-type-format type)
1019 :high (list (float 0.0 hi-val)))))))
1025 ;;; Convert back a possible list of numeric types.
1026 (defun convert-back-numeric-type-list (type-list)
1029 (let ((results '()))
1030 (dolist (type type-list)
1031 (if (numeric-type-p type)
1032 (let ((result (convert-back-numeric-type type)))
1034 (setf results (append results result))
1035 (push result results)))
1036 (push type results)))
1039 (convert-back-numeric-type type-list))
1041 (convert-back-numeric-type-list (union-type-types type-list)))
1045 ;;; FIXME: MAKE-CANONICAL-UNION-TYPE and CONVERT-MEMBER-TYPE probably
1046 ;;; belong in the kernel's type logic, invoked always, instead of in
1047 ;;; the compiler, invoked only during some type optimizations. (In
1048 ;;; fact, as of 0.pre8.100 or so they probably are, under
1049 ;;; MAKE-MEMBER-TYPE, so probably this code can be deleted)
1051 ;;; Take a list of types and return a canonical type specifier,
1052 ;;; combining any MEMBER types together. If both positive and negative
1053 ;;; MEMBER types are present they are converted to a float type.
1054 ;;; XXX This would be far simpler if the type-union methods could handle
1055 ;;; member/number unions.
1056 (defun make-canonical-union-type (type-list)
1059 (dolist (type type-list)
1060 (if (member-type-p type)
1061 (setf members (union members (member-type-members type)))
1062 (push type misc-types)))
1064 (when (null (set-difference `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0) members))
1065 (push (specifier-type '(long-float 0.0l0 0.0l0)) misc-types)
1066 (setf members (set-difference members `(,(load-time-value (make-unportable-float :long-float-negative-zero)) 0.0l0))))
1067 (when (null (set-difference `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0) members))
1068 (push (specifier-type '(double-float 0.0d0 0.0d0)) misc-types)
1069 (setf members (set-difference members `(,(load-time-value (make-unportable-float :double-float-negative-zero)) 0.0d0))))
1070 (when (null (set-difference `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0) members))
1071 (push (specifier-type '(single-float 0.0f0 0.0f0)) misc-types)
1072 (setf members (set-difference members `(,(load-time-value (make-unportable-float :single-float-negative-zero)) 0.0f0))))
1074 (apply #'type-union (make-member-type :members members) misc-types)
1075 (apply #'type-union misc-types))))
1077 ;;; Convert a member type with a single member to a numeric type.
1078 (defun convert-member-type (arg)
1079 (let* ((members (member-type-members arg))
1080 (member (first members))
1081 (member-type (type-of member)))
1082 (aver (not (rest members)))
1083 (specifier-type (cond ((typep member 'integer)
1084 `(integer ,member ,member))
1085 ((memq member-type '(short-float single-float
1086 double-float long-float))
1087 `(,member-type ,member ,member))
1091 ;;; This is used in defoptimizers for computing the resulting type of
1094 ;;; Given the lvar ARG, derive the resulting type using the
1095 ;;; DERIVE-FUN. DERIVE-FUN takes exactly one argument which is some
1096 ;;; "atomic" lvar type like numeric-type or member-type (containing
1097 ;;; just one element). It should return the resulting type, which can
1098 ;;; be a list of types.
1100 ;;; For the case of member types, if a MEMBER-FUN is given it is
1101 ;;; called to compute the result otherwise the member type is first
1102 ;;; converted to a numeric type and the DERIVE-FUN is called.
1103 (defun one-arg-derive-type (arg derive-fun member-fun
1104 &optional (convert-type t))
1105 (declare (type function derive-fun)
1106 (type (or null function) member-fun))
1107 (let ((arg-list (prepare-arg-for-derive-type (lvar-type arg))))
1113 (with-float-traps-masked
1114 (:underflow :overflow :divide-by-zero)
1116 `(eql ,(funcall member-fun
1117 (first (member-type-members x))))))
1118 ;; Otherwise convert to a numeric type.
1119 (let ((result-type-list
1120 (funcall derive-fun (convert-member-type x))))
1122 (convert-back-numeric-type-list result-type-list)
1123 result-type-list))))
1126 (convert-back-numeric-type-list
1127 (funcall derive-fun (convert-numeric-type x)))
1128 (funcall derive-fun x)))
1130 *universal-type*))))
1131 ;; Run down the list of args and derive the type of each one,
1132 ;; saving all of the results in a list.
1133 (let ((results nil))
1134 (dolist (arg arg-list)
1135 (let ((result (deriver arg)))
1137 (setf results (append results result))
1138 (push result results))))
1140 (make-canonical-union-type results)
1141 (first results)))))))
1143 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1144 ;;; two arguments. DERIVE-FUN takes 3 args in this case: the two
1145 ;;; original args and a third which is T to indicate if the two args
1146 ;;; really represent the same lvar. This is useful for deriving the
1147 ;;; type of things like (* x x), which should always be positive. If
1148 ;;; we didn't do this, we wouldn't be able to tell.
1149 (defun two-arg-derive-type (arg1 arg2 derive-fun fun
1150 &optional (convert-type t))
1151 (declare (type function derive-fun fun))
1152 (flet ((deriver (x y same-arg)
1153 (cond ((and (member-type-p x) (member-type-p y))
1154 (let* ((x (first (member-type-members x)))
1155 (y (first (member-type-members y)))
1156 (result (ignore-errors
1157 (with-float-traps-masked
1158 (:underflow :overflow :divide-by-zero
1160 (funcall fun x y)))))
1161 (cond ((null result) *empty-type*)
1162 ((and (floatp result) (float-nan-p result))
1163 (make-numeric-type :class 'float
1164 :format (type-of result)
1167 (specifier-type `(eql ,result))))))
1168 ((and (member-type-p x) (numeric-type-p y))
1169 (let* ((x (convert-member-type x))
1170 (y (if convert-type (convert-numeric-type y) y))
1171 (result (funcall derive-fun x y same-arg)))
1173 (convert-back-numeric-type-list result)
1175 ((and (numeric-type-p x) (member-type-p y))
1176 (let* ((x (if convert-type (convert-numeric-type x) x))
1177 (y (convert-member-type y))
1178 (result (funcall derive-fun x y same-arg)))
1180 (convert-back-numeric-type-list result)
1182 ((and (numeric-type-p x) (numeric-type-p y))
1183 (let* ((x (if convert-type (convert-numeric-type x) x))
1184 (y (if convert-type (convert-numeric-type y) y))
1185 (result (funcall derive-fun x y same-arg)))
1187 (convert-back-numeric-type-list result)
1190 *universal-type*))))
1191 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1192 (a1 (prepare-arg-for-derive-type (lvar-type arg1)))
1193 (a2 (prepare-arg-for-derive-type (lvar-type arg2))))
1195 (let ((results nil))
1197 ;; Since the args are the same LVARs, just run down the
1200 (let ((result (deriver x x same-arg)))
1202 (setf results (append results result))
1203 (push result results))))
1204 ;; Try all pairwise combinations.
1207 (let ((result (or (deriver x y same-arg)
1208 (numeric-contagion x y))))
1210 (setf results (append results result))
1211 (push result results))))))
1213 (make-canonical-union-type results)
1214 (first results)))))))
1216 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1218 (defoptimizer (+ derive-type) ((x y))
1219 (derive-integer-type
1226 (values (frob (numeric-type-low x) (numeric-type-low y))
1227 (frob (numeric-type-high x) (numeric-type-high y)))))))
1229 (defoptimizer (- derive-type) ((x y))
1230 (derive-integer-type
1237 (values (frob (numeric-type-low x) (numeric-type-high y))
1238 (frob (numeric-type-high x) (numeric-type-low y)))))))
1240 (defoptimizer (* derive-type) ((x y))
1241 (derive-integer-type
1244 (let ((x-low (numeric-type-low x))
1245 (x-high (numeric-type-high x))
1246 (y-low (numeric-type-low y))
1247 (y-high (numeric-type-high y)))
1248 (cond ((not (and x-low y-low))
1250 ((or (minusp x-low) (minusp y-low))
1251 (if (and x-high y-high)
1252 (let ((max (* (max (abs x-low) (abs x-high))
1253 (max (abs y-low) (abs y-high)))))
1254 (values (- max) max))
1257 (values (* x-low y-low)
1258 (if (and x-high y-high)
1262 (defoptimizer (/ derive-type) ((x y))
1263 (numeric-contagion (lvar-type x) (lvar-type y)))
1267 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1269 (defun +-derive-type-aux (x y same-arg)
1270 (if (and (numeric-type-real-p x)
1271 (numeric-type-real-p y))
1274 (let ((x-int (numeric-type->interval x)))
1275 (interval-add x-int x-int))
1276 (interval-add (numeric-type->interval x)
1277 (numeric-type->interval y))))
1278 (result-type (numeric-contagion x y)))
1279 ;; If the result type is a float, we need to be sure to coerce
1280 ;; the bounds into the correct type.
1281 (when (eq (numeric-type-class result-type) 'float)
1282 (setf result (interval-func
1284 (coerce-for-bound x (or (numeric-type-format result-type)
1288 :class (if (and (eq (numeric-type-class x) 'integer)
1289 (eq (numeric-type-class y) 'integer))
1290 ;; The sum of integers is always an integer.
1292 (numeric-type-class result-type))
1293 :format (numeric-type-format result-type)
1294 :low (interval-low result)
1295 :high (interval-high result)))
1296 ;; general contagion
1297 (numeric-contagion x y)))
1299 (defoptimizer (+ derive-type) ((x y))
1300 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1302 (defun --derive-type-aux (x y same-arg)
1303 (if (and (numeric-type-real-p x)
1304 (numeric-type-real-p y))
1306 ;; (- X X) is always 0.
1308 (make-interval :low 0 :high 0)
1309 (interval-sub (numeric-type->interval x)
1310 (numeric-type->interval y))))
1311 (result-type (numeric-contagion x y)))
1312 ;; If the result type is a float, we need to be sure to coerce
1313 ;; the bounds into the correct type.
1314 (when (eq (numeric-type-class result-type) 'float)
1315 (setf result (interval-func
1317 (coerce-for-bound x (or (numeric-type-format result-type)
1321 :class (if (and (eq (numeric-type-class x) 'integer)
1322 (eq (numeric-type-class y) 'integer))
1323 ;; The difference of integers is always an integer.
1325 (numeric-type-class result-type))
1326 :format (numeric-type-format result-type)
1327 :low (interval-low result)
1328 :high (interval-high result)))
1329 ;; general contagion
1330 (numeric-contagion x y)))
1332 (defoptimizer (- derive-type) ((x y))
1333 (two-arg-derive-type x y #'--derive-type-aux #'-))
1335 (defun *-derive-type-aux (x y same-arg)
1336 (if (and (numeric-type-real-p x)
1337 (numeric-type-real-p y))
1339 ;; (* X X) is always positive, so take care to do it right.
1341 (interval-sqr (numeric-type->interval x))
1342 (interval-mul (numeric-type->interval x)
1343 (numeric-type->interval y))))
1344 (result-type (numeric-contagion x y)))
1345 ;; If the result type is a float, we need to be sure to coerce
1346 ;; the bounds into the correct type.
1347 (when (eq (numeric-type-class result-type) 'float)
1348 (setf result (interval-func
1350 (coerce-for-bound x (or (numeric-type-format result-type)
1354 :class (if (and (eq (numeric-type-class x) 'integer)
1355 (eq (numeric-type-class y) 'integer))
1356 ;; The product of integers is always an integer.
1358 (numeric-type-class result-type))
1359 :format (numeric-type-format result-type)
1360 :low (interval-low result)
1361 :high (interval-high result)))
1362 (numeric-contagion x y)))
1364 (defoptimizer (* derive-type) ((x y))
1365 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1367 (defun /-derive-type-aux (x y same-arg)
1368 (if (and (numeric-type-real-p x)
1369 (numeric-type-real-p y))
1371 ;; (/ X X) is always 1, except if X can contain 0. In
1372 ;; that case, we shouldn't optimize the division away
1373 ;; because we want 0/0 to signal an error.
1375 (not (interval-contains-p
1376 0 (interval-closure (numeric-type->interval y)))))
1377 (make-interval :low 1 :high 1)
1378 (interval-div (numeric-type->interval x)
1379 (numeric-type->interval y))))
1380 (result-type (numeric-contagion x y)))
1381 ;; If the result type is a float, we need to be sure to coerce
1382 ;; the bounds into the correct type.
1383 (when (eq (numeric-type-class result-type) 'float)
1384 (setf result (interval-func
1386 (coerce-for-bound x (or (numeric-type-format result-type)
1389 (make-numeric-type :class (numeric-type-class result-type)
1390 :format (numeric-type-format result-type)
1391 :low (interval-low result)
1392 :high (interval-high result)))
1393 (numeric-contagion x y)))
1395 (defoptimizer (/ derive-type) ((x y))
1396 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1400 (defun ash-derive-type-aux (n-type shift same-arg)
1401 (declare (ignore same-arg))
1402 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1403 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1404 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1405 ;; two bignums yielding zero) and it's hard to avoid that
1406 ;; calculation in here.
1407 #+(and cmu sb-xc-host)
1408 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1409 (typep (numeric-type-high n-type) 'bignum))
1410 (or (typep (numeric-type-low shift) 'bignum)
1411 (typep (numeric-type-high shift) 'bignum)))
1412 (return-from ash-derive-type-aux *universal-type*))
1413 (flet ((ash-outer (n s)
1414 (when (and (fixnump s)
1416 (> s sb!xc:most-negative-fixnum))
1418 ;; KLUDGE: The bare 64's here should be related to
1419 ;; symbolic machine word size values somehow.
1422 (if (and (fixnump s)
1423 (> s sb!xc:most-negative-fixnum))
1425 (if (minusp n) -1 0))))
1426 (or (and (csubtypep n-type (specifier-type 'integer))
1427 (csubtypep shift (specifier-type 'integer))
1428 (let ((n-low (numeric-type-low n-type))
1429 (n-high (numeric-type-high n-type))
1430 (s-low (numeric-type-low shift))
1431 (s-high (numeric-type-high shift)))
1432 (make-numeric-type :class 'integer :complexp :real
1435 (ash-outer n-low s-high)
1436 (ash-inner n-low s-low)))
1439 (ash-inner n-high s-low)
1440 (ash-outer n-high s-high))))))
1443 (defoptimizer (ash derive-type) ((n shift))
1444 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1446 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1447 (macrolet ((frob (fun)
1448 `#'(lambda (type type2)
1449 (declare (ignore type2))
1450 (let ((lo (numeric-type-low type))
1451 (hi (numeric-type-high type)))
1452 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1454 (defoptimizer (%negate derive-type) ((num))
1455 (derive-integer-type num num (frob -))))
1457 (defun lognot-derive-type-aux (int)
1458 (derive-integer-type-aux int int
1459 (lambda (type type2)
1460 (declare (ignore type2))
1461 (let ((lo (numeric-type-low type))
1462 (hi (numeric-type-high type)))
1463 (values (if hi (lognot hi) nil)
1464 (if lo (lognot lo) nil)
1465 (numeric-type-class type)
1466 (numeric-type-format type))))))
1468 (defoptimizer (lognot derive-type) ((int))
1469 (lognot-derive-type-aux (lvar-type int)))
1471 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1472 (defoptimizer (%negate derive-type) ((num))
1473 (flet ((negate-bound (b)
1475 (set-bound (- (type-bound-number b))
1477 (one-arg-derive-type num
1479 (modified-numeric-type
1481 :low (negate-bound (numeric-type-high type))
1482 :high (negate-bound (numeric-type-low type))))
1485 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1486 (defoptimizer (abs derive-type) ((num))
1487 (let ((type (lvar-type num)))
1488 (if (and (numeric-type-p type)
1489 (eq (numeric-type-class type) 'integer)
1490 (eq (numeric-type-complexp type) :real))
1491 (let ((lo (numeric-type-low type))
1492 (hi (numeric-type-high type)))
1493 (make-numeric-type :class 'integer :complexp :real
1494 :low (cond ((and hi (minusp hi))
1500 :high (if (and hi lo)
1501 (max (abs hi) (abs lo))
1503 (numeric-contagion type type))))
1505 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1506 (defun abs-derive-type-aux (type)
1507 (cond ((eq (numeric-type-complexp type) :complex)
1508 ;; The absolute value of a complex number is always a
1509 ;; non-negative float.
1510 (let* ((format (case (numeric-type-class type)
1511 ((integer rational) 'single-float)
1512 (t (numeric-type-format type))))
1513 (bound-format (or format 'float)))
1514 (make-numeric-type :class 'float
1517 :low (coerce 0 bound-format)
1520 ;; The absolute value of a real number is a non-negative real
1521 ;; of the same type.
1522 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1523 (class (numeric-type-class type))
1524 (format (numeric-type-format type))
1525 (bound-type (or format class 'real)))
1530 :low (coerce-and-truncate-floats (interval-low abs-bnd) bound-type)
1531 :high (coerce-and-truncate-floats
1532 (interval-high abs-bnd) bound-type))))))
1534 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1535 (defoptimizer (abs derive-type) ((num))
1536 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1538 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1539 (defoptimizer (truncate derive-type) ((number divisor))
1540 (let ((number-type (lvar-type number))
1541 (divisor-type (lvar-type divisor))
1542 (integer-type (specifier-type 'integer)))
1543 (if (and (numeric-type-p number-type)
1544 (csubtypep number-type integer-type)
1545 (numeric-type-p divisor-type)
1546 (csubtypep divisor-type integer-type))
1547 (let ((number-low (numeric-type-low number-type))
1548 (number-high (numeric-type-high number-type))
1549 (divisor-low (numeric-type-low divisor-type))
1550 (divisor-high (numeric-type-high divisor-type)))
1551 (values-specifier-type
1552 `(values ,(integer-truncate-derive-type number-low number-high
1553 divisor-low divisor-high)
1554 ,(integer-rem-derive-type number-low number-high
1555 divisor-low divisor-high))))
1558 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1561 (defun rem-result-type (number-type divisor-type)
1562 ;; Figure out what the remainder type is. The remainder is an
1563 ;; integer if both args are integers; a rational if both args are
1564 ;; rational; and a float otherwise.
1565 (cond ((and (csubtypep number-type (specifier-type 'integer))
1566 (csubtypep divisor-type (specifier-type 'integer)))
1568 ((and (csubtypep number-type (specifier-type 'rational))
1569 (csubtypep divisor-type (specifier-type 'rational)))
1571 ((and (csubtypep number-type (specifier-type 'float))
1572 (csubtypep divisor-type (specifier-type 'float)))
1573 ;; Both are floats so the result is also a float, of
1574 ;; the largest type.
1575 (or (float-format-max (numeric-type-format number-type)
1576 (numeric-type-format divisor-type))
1578 ((and (csubtypep number-type (specifier-type 'float))
1579 (csubtypep divisor-type (specifier-type 'rational)))
1580 ;; One of the arguments is a float and the other is a
1581 ;; rational. The remainder is a float of the same
1583 (or (numeric-type-format number-type) 'float))
1584 ((and (csubtypep divisor-type (specifier-type 'float))
1585 (csubtypep number-type (specifier-type 'rational)))
1586 ;; One of the arguments is a float and the other is a
1587 ;; rational. The remainder is a float of the same
1589 (or (numeric-type-format divisor-type) 'float))
1591 ;; Some unhandled combination. This usually means both args
1592 ;; are REAL so the result is a REAL.
1595 (defun truncate-derive-type-quot (number-type divisor-type)
1596 (let* ((rem-type (rem-result-type number-type divisor-type))
1597 (number-interval (numeric-type->interval number-type))
1598 (divisor-interval (numeric-type->interval divisor-type)))
1599 ;;(declare (type (member '(integer rational float)) rem-type))
1600 ;; We have real numbers now.
1601 (cond ((eq rem-type 'integer)
1602 ;; Since the remainder type is INTEGER, both args are
1604 (let* ((res (integer-truncate-derive-type
1605 (interval-low number-interval)
1606 (interval-high number-interval)
1607 (interval-low divisor-interval)
1608 (interval-high divisor-interval))))
1609 (specifier-type (if (listp res) res 'integer))))
1611 (let ((quot (truncate-quotient-bound
1612 (interval-div number-interval
1613 divisor-interval))))
1614 (specifier-type `(integer ,(or (interval-low quot) '*)
1615 ,(or (interval-high quot) '*))))))))
1617 (defun truncate-derive-type-rem (number-type divisor-type)
1618 (let* ((rem-type (rem-result-type number-type divisor-type))
1619 (number-interval (numeric-type->interval number-type))
1620 (divisor-interval (numeric-type->interval divisor-type))
1621 (rem (truncate-rem-bound number-interval divisor-interval)))
1622 ;;(declare (type (member '(integer rational float)) rem-type))
1623 ;; We have real numbers now.
1624 (cond ((eq rem-type 'integer)
1625 ;; Since the remainder type is INTEGER, both args are
1627 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1628 ,(or (interval-high rem) '*))))
1630 (multiple-value-bind (class format)
1633 (values 'integer nil))
1635 (values 'rational nil))
1636 ((or single-float double-float #!+long-float long-float)
1637 (values 'float rem-type))
1639 (values 'float nil))
1642 (when (member rem-type '(float single-float double-float
1643 #!+long-float long-float))
1644 (setf rem (interval-func #'(lambda (x)
1645 (coerce-for-bound x rem-type))
1647 (make-numeric-type :class class
1649 :low (interval-low rem)
1650 :high (interval-high rem)))))))
1652 (defun truncate-derive-type-quot-aux (num div same-arg)
1653 (declare (ignore same-arg))
1654 (if (and (numeric-type-real-p num)
1655 (numeric-type-real-p div))
1656 (truncate-derive-type-quot num div)
1659 (defun truncate-derive-type-rem-aux (num div same-arg)
1660 (declare (ignore same-arg))
1661 (if (and (numeric-type-real-p num)
1662 (numeric-type-real-p div))
1663 (truncate-derive-type-rem num div)
1666 (defoptimizer (truncate derive-type) ((number divisor))
1667 (let ((quot (two-arg-derive-type number divisor
1668 #'truncate-derive-type-quot-aux #'truncate))
1669 (rem (two-arg-derive-type number divisor
1670 #'truncate-derive-type-rem-aux #'rem)))
1671 (when (and quot rem)
1672 (make-values-type :required (list quot rem)))))
1674 (defun ftruncate-derive-type-quot (number-type divisor-type)
1675 ;; The bounds are the same as for truncate. However, the first
1676 ;; result is a float of some type. We need to determine what that
1677 ;; type is. Basically it's the more contagious of the two types.
1678 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1679 (res-type (numeric-contagion number-type divisor-type)))
1680 (make-numeric-type :class 'float
1681 :format (numeric-type-format res-type)
1682 :low (numeric-type-low q-type)
1683 :high (numeric-type-high q-type))))
1685 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1686 (declare (ignore same-arg))
1687 (if (and (numeric-type-real-p n)
1688 (numeric-type-real-p d))
1689 (ftruncate-derive-type-quot n d)
1692 (defoptimizer (ftruncate derive-type) ((number divisor))
1694 (two-arg-derive-type number divisor
1695 #'ftruncate-derive-type-quot-aux #'ftruncate))
1696 (rem (two-arg-derive-type number divisor
1697 #'truncate-derive-type-rem-aux #'rem)))
1698 (when (and quot rem)
1699 (make-values-type :required (list quot rem)))))
1701 (defun %unary-truncate-derive-type-aux (number)
1702 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1704 (defoptimizer (%unary-truncate derive-type) ((number))
1705 (one-arg-derive-type number
1706 #'%unary-truncate-derive-type-aux
1709 (defoptimizer (%unary-ftruncate derive-type) ((number))
1710 (let ((divisor (specifier-type '(integer 1 1))))
1711 (one-arg-derive-type number
1713 (ftruncate-derive-type-quot-aux n divisor nil))
1714 #'%unary-ftruncate)))
1716 ;;; Define optimizers for FLOOR and CEILING.
1718 ((def (name q-name r-name)
1719 (let ((q-aux (symbolicate q-name "-AUX"))
1720 (r-aux (symbolicate r-name "-AUX")))
1722 ;; Compute type of quotient (first) result.
1723 (defun ,q-aux (number-type divisor-type)
1724 (let* ((number-interval
1725 (numeric-type->interval number-type))
1727 (numeric-type->interval divisor-type))
1728 (quot (,q-name (interval-div number-interval
1729 divisor-interval))))
1730 (specifier-type `(integer ,(or (interval-low quot) '*)
1731 ,(or (interval-high quot) '*)))))
1732 ;; Compute type of remainder.
1733 (defun ,r-aux (number-type divisor-type)
1734 (let* ((divisor-interval
1735 (numeric-type->interval divisor-type))
1736 (rem (,r-name divisor-interval))
1737 (result-type (rem-result-type number-type divisor-type)))
1738 (multiple-value-bind (class format)
1741 (values 'integer nil))
1743 (values 'rational nil))
1744 ((or single-float double-float #!+long-float long-float)
1745 (values 'float result-type))
1747 (values 'float nil))
1750 (when (member result-type '(float single-float double-float
1751 #!+long-float long-float))
1752 ;; Make sure that the limits on the interval have
1754 (setf rem (interval-func (lambda (x)
1755 (coerce-for-bound x result-type))
1757 (make-numeric-type :class class
1759 :low (interval-low rem)
1760 :high (interval-high rem)))))
1761 ;; the optimizer itself
1762 (defoptimizer (,name derive-type) ((number divisor))
1763 (flet ((derive-q (n d same-arg)
1764 (declare (ignore same-arg))
1765 (if (and (numeric-type-real-p n)
1766 (numeric-type-real-p d))
1769 (derive-r (n d same-arg)
1770 (declare (ignore same-arg))
1771 (if (and (numeric-type-real-p n)
1772 (numeric-type-real-p d))
1775 (let ((quot (two-arg-derive-type
1776 number divisor #'derive-q #',name))
1777 (rem (two-arg-derive-type
1778 number divisor #'derive-r #'mod)))
1779 (when (and quot rem)
1780 (make-values-type :required (list quot rem))))))))))
1782 (def floor floor-quotient-bound floor-rem-bound)
1783 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1785 ;;; Define optimizers for FFLOOR and FCEILING
1786 (macrolet ((def (name q-name r-name)
1787 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1788 (r-aux (symbolicate r-name "-AUX")))
1790 ;; Compute type of quotient (first) result.
1791 (defun ,q-aux (number-type divisor-type)
1792 (let* ((number-interval
1793 (numeric-type->interval number-type))
1795 (numeric-type->interval divisor-type))
1796 (quot (,q-name (interval-div number-interval
1798 (res-type (numeric-contagion number-type
1801 :class (numeric-type-class res-type)
1802 :format (numeric-type-format res-type)
1803 :low (interval-low quot)
1804 :high (interval-high quot))))
1806 (defoptimizer (,name derive-type) ((number divisor))
1807 (flet ((derive-q (n d same-arg)
1808 (declare (ignore same-arg))
1809 (if (and (numeric-type-real-p n)
1810 (numeric-type-real-p d))
1813 (derive-r (n d same-arg)
1814 (declare (ignore same-arg))
1815 (if (and (numeric-type-real-p n)
1816 (numeric-type-real-p d))
1819 (let ((quot (two-arg-derive-type
1820 number divisor #'derive-q #',name))
1821 (rem (two-arg-derive-type
1822 number divisor #'derive-r #'mod)))
1823 (when (and quot rem)
1824 (make-values-type :required (list quot rem))))))))))
1826 (def ffloor floor-quotient-bound floor-rem-bound)
1827 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1829 ;;; functions to compute the bounds on the quotient and remainder for
1830 ;;; the FLOOR function
1831 (defun floor-quotient-bound (quot)
1832 ;; Take the floor of the quotient and then massage it into what we
1834 (let ((lo (interval-low quot))
1835 (hi (interval-high quot)))
1836 ;; Take the floor of the lower bound. The result is always a
1837 ;; closed lower bound.
1839 (floor (type-bound-number lo))
1841 ;; For the upper bound, we need to be careful.
1844 ;; An open bound. We need to be careful here because
1845 ;; the floor of '(10.0) is 9, but the floor of
1847 (multiple-value-bind (q r) (floor (first hi))
1852 ;; A closed bound, so the answer is obvious.
1856 (make-interval :low lo :high hi)))
1857 (defun floor-rem-bound (div)
1858 ;; The remainder depends only on the divisor. Try to get the
1859 ;; correct sign for the remainder if we can.
1860 (case (interval-range-info div)
1862 ;; The divisor is always positive.
1863 (let ((rem (interval-abs div)))
1864 (setf (interval-low rem) 0)
1865 (when (and (numberp (interval-high rem))
1866 (not (zerop (interval-high rem))))
1867 ;; The remainder never contains the upper bound. However,
1868 ;; watch out for the case where the high limit is zero!
1869 (setf (interval-high rem) (list (interval-high rem))))
1872 ;; The divisor is always negative.
1873 (let ((rem (interval-neg (interval-abs div))))
1874 (setf (interval-high rem) 0)
1875 (when (numberp (interval-low rem))
1876 ;; The remainder never contains the lower bound.
1877 (setf (interval-low rem) (list (interval-low rem))))
1880 ;; The divisor can be positive or negative. All bets off. The
1881 ;; magnitude of remainder is the maximum value of the divisor.
1882 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1883 ;; The bound never reaches the limit, so make the interval open.
1884 (make-interval :low (if limit
1887 :high (list limit))))))
1889 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
1890 => #S(INTERVAL :LOW 0 :HIGH 10)
1891 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1892 => #S(INTERVAL :LOW 0 :HIGH 10)
1893 (floor-quotient-bound (make-interval :low 0.3 :high 10))
1894 => #S(INTERVAL :LOW 0 :HIGH 10)
1895 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
1896 => #S(INTERVAL :LOW 0 :HIGH 9)
1897 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
1898 => #S(INTERVAL :LOW 0 :HIGH 10)
1899 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
1900 => #S(INTERVAL :LOW 0 :HIGH 10)
1901 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1902 => #S(INTERVAL :LOW -2 :HIGH 10)
1903 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1904 => #S(INTERVAL :LOW -1 :HIGH 10)
1905 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
1906 => #S(INTERVAL :LOW -1 :HIGH 10)
1908 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
1909 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1910 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
1911 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
1912 (floor-rem-bound (make-interval :low -10 :high -2.3))
1913 #S(INTERVAL :LOW (-10) :HIGH 0)
1914 (floor-rem-bound (make-interval :low 0.3 :high 10))
1915 => #S(INTERVAL :LOW 0 :HIGH '(10))
1916 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
1917 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
1918 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
1919 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
1922 ;;; same functions for CEILING
1923 (defun ceiling-quotient-bound (quot)
1924 ;; Take the ceiling of the quotient and then massage it into what we
1926 (let ((lo (interval-low quot))
1927 (hi (interval-high quot)))
1928 ;; Take the ceiling of the upper bound. The result is always a
1929 ;; closed upper bound.
1931 (ceiling (type-bound-number hi))
1933 ;; For the lower bound, we need to be careful.
1936 ;; An open bound. We need to be careful here because
1937 ;; the ceiling of '(10.0) is 11, but the ceiling of
1939 (multiple-value-bind (q r) (ceiling (first lo))
1944 ;; A closed bound, so the answer is obvious.
1948 (make-interval :low lo :high hi)))
1949 (defun ceiling-rem-bound (div)
1950 ;; The remainder depends only on the divisor. Try to get the
1951 ;; correct sign for the remainder if we can.
1952 (case (interval-range-info div)
1954 ;; Divisor is always positive. The remainder is negative.
1955 (let ((rem (interval-neg (interval-abs div))))
1956 (setf (interval-high rem) 0)
1957 (when (and (numberp (interval-low rem))
1958 (not (zerop (interval-low rem))))
1959 ;; The remainder never contains the upper bound. However,
1960 ;; watch out for the case when the upper bound is zero!
1961 (setf (interval-low rem) (list (interval-low rem))))
1964 ;; Divisor is always negative. The remainder is positive
1965 (let ((rem (interval-abs div)))
1966 (setf (interval-low rem) 0)
1967 (when (numberp (interval-high rem))
1968 ;; The remainder never contains the lower bound.
1969 (setf (interval-high rem) (list (interval-high rem))))
1972 ;; The divisor can be positive or negative. All bets off. The
1973 ;; magnitude of remainder is the maximum value of the divisor.
1974 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1975 ;; The bound never reaches the limit, so make the interval open.
1976 (make-interval :low (if limit
1979 :high (list limit))))))
1982 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
1983 => #S(INTERVAL :LOW 1 :HIGH 11)
1984 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
1985 => #S(INTERVAL :LOW 1 :HIGH 11)
1986 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
1987 => #S(INTERVAL :LOW 1 :HIGH 10)
1988 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
1989 => #S(INTERVAL :LOW 1 :HIGH 10)
1990 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
1991 => #S(INTERVAL :LOW 1 :HIGH 11)
1992 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
1993 => #S(INTERVAL :LOW 1 :HIGH 11)
1994 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
1995 => #S(INTERVAL :LOW -1 :HIGH 11)
1996 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
1997 => #S(INTERVAL :LOW 0 :HIGH 11)
1998 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
1999 => #S(INTERVAL :LOW -1 :HIGH 11)
2001 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
2002 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
2003 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
2004 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2005 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
2006 => #S(INTERVAL :LOW 0 :HIGH (10))
2007 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
2008 => #S(INTERVAL :LOW (-10) :HIGH 0)
2009 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
2010 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
2011 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
2012 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
2015 (defun truncate-quotient-bound (quot)
2016 ;; For positive quotients, truncate is exactly like floor. For
2017 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
2018 ;; it's the union of the two pieces.
2019 (case (interval-range-info quot)
2022 (floor-quotient-bound quot))
2024 ;; just like CEILING
2025 (ceiling-quotient-bound quot))
2027 ;; Split the interval into positive and negative pieces, compute
2028 ;; the result for each piece and put them back together.
2029 (destructuring-bind (neg pos) (interval-split 0 quot t t)
2030 (interval-merge-pair (ceiling-quotient-bound neg)
2031 (floor-quotient-bound pos))))))
2033 (defun truncate-rem-bound (num div)
2034 ;; This is significantly more complicated than FLOOR or CEILING. We
2035 ;; need both the number and the divisor to determine the range. The
2036 ;; basic idea is to split the ranges of NUM and DEN into positive
2037 ;; and negative pieces and deal with each of the four possibilities
2039 (case (interval-range-info num)
2041 (case (interval-range-info div)
2043 (floor-rem-bound div))
2045 (ceiling-rem-bound div))
2047 (destructuring-bind (neg pos) (interval-split 0 div t t)
2048 (interval-merge-pair (truncate-rem-bound num neg)
2049 (truncate-rem-bound num pos))))))
2051 (case (interval-range-info div)
2053 (ceiling-rem-bound div))
2055 (floor-rem-bound div))
2057 (destructuring-bind (neg pos) (interval-split 0 div t t)
2058 (interval-merge-pair (truncate-rem-bound num neg)
2059 (truncate-rem-bound num pos))))))
2061 (destructuring-bind (neg pos) (interval-split 0 num t t)
2062 (interval-merge-pair (truncate-rem-bound neg div)
2063 (truncate-rem-bound pos div))))))
2066 ;;; Derive useful information about the range. Returns three values:
2067 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
2068 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
2069 ;;; - The abs of the maximal value if there is one, or nil if it is
2071 (defun numeric-range-info (low high)
2072 (cond ((and low (not (minusp low)))
2073 (values '+ low high))
2074 ((and high (not (plusp high)))
2075 (values '- (- high) (if low (- low) nil)))
2077 (values nil 0 (and low high (max (- low) high))))))
2079 (defun integer-truncate-derive-type
2080 (number-low number-high divisor-low divisor-high)
2081 ;; The result cannot be larger in magnitude than the number, but the
2082 ;; sign might change. If we can determine the sign of either the
2083 ;; number or the divisor, we can eliminate some of the cases.
2084 (multiple-value-bind (number-sign number-min number-max)
2085 (numeric-range-info number-low number-high)
2086 (multiple-value-bind (divisor-sign divisor-min divisor-max)
2087 (numeric-range-info divisor-low divisor-high)
2088 (when (and divisor-max (zerop divisor-max))
2089 ;; We've got a problem: guaranteed division by zero.
2090 (return-from integer-truncate-derive-type t))
2091 (when (zerop divisor-min)
2092 ;; We'll assume that they aren't going to divide by zero.
2094 (cond ((and number-sign divisor-sign)
2095 ;; We know the sign of both.
2096 (if (eq number-sign divisor-sign)
2097 ;; Same sign, so the result will be positive.
2098 `(integer ,(if divisor-max
2099 (truncate number-min divisor-max)
2102 (truncate number-max divisor-min)
2104 ;; Different signs, the result will be negative.
2105 `(integer ,(if number-max
2106 (- (truncate number-max divisor-min))
2109 (- (truncate number-min divisor-max))
2111 ((eq divisor-sign '+)
2112 ;; The divisor is positive. Therefore, the number will just
2113 ;; become closer to zero.
2114 `(integer ,(if number-low
2115 (truncate number-low divisor-min)
2118 (truncate number-high divisor-min)
2120 ((eq divisor-sign '-)
2121 ;; The divisor is negative. Therefore, the absolute value of
2122 ;; the number will become closer to zero, but the sign will also
2124 `(integer ,(if number-high
2125 (- (truncate number-high divisor-min))
2128 (- (truncate number-low divisor-min))
2130 ;; The divisor could be either positive or negative.
2132 ;; The number we are dividing has a bound. Divide that by the
2133 ;; smallest posible divisor.
2134 (let ((bound (truncate number-max divisor-min)))
2135 `(integer ,(- bound) ,bound)))
2137 ;; The number we are dividing is unbounded, so we can't tell
2138 ;; anything about the result.
2141 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2142 (defun integer-rem-derive-type
2143 (number-low number-high divisor-low divisor-high)
2144 (if (and divisor-low divisor-high)
2145 ;; We know the range of the divisor, and the remainder must be
2146 ;; smaller than the divisor. We can tell the sign of the
2147 ;; remainer if we know the sign of the number.
2148 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2149 `(integer ,(if (or (null number-low)
2150 (minusp number-low))
2153 ,(if (or (null number-high)
2154 (plusp number-high))
2157 ;; The divisor is potentially either very positive or very
2158 ;; negative. Therefore, the remainer is unbounded, but we might
2159 ;; be able to tell something about the sign from the number.
2160 `(integer ,(if (and number-low (not (minusp number-low)))
2161 ;; The number we are dividing is positive.
2162 ;; Therefore, the remainder must be positive.
2165 ,(if (and number-high (not (plusp number-high)))
2166 ;; The number we are dividing is negative.
2167 ;; Therefore, the remainder must be negative.
2171 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2172 (defoptimizer (random derive-type) ((bound &optional state))
2173 (let ((type (lvar-type bound)))
2174 (when (numeric-type-p type)
2175 (let ((class (numeric-type-class type))
2176 (high (numeric-type-high type))
2177 (format (numeric-type-format type)))
2181 :low (coerce 0 (or format class 'real))
2182 :high (cond ((not high) nil)
2183 ((eq class 'integer) (max (1- high) 0))
2184 ((or (consp high) (zerop high)) high)
2187 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2188 (defun random-derive-type-aux (type)
2189 (let ((class (numeric-type-class type))
2190 (high (numeric-type-high type))
2191 (format (numeric-type-format type)))
2195 :low (coerce 0 (or format class 'real))
2196 :high (cond ((not high) nil)
2197 ((eq class 'integer) (max (1- high) 0))
2198 ((or (consp high) (zerop high)) high)
2201 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2202 (defoptimizer (random derive-type) ((bound &optional state))
2203 (one-arg-derive-type bound #'random-derive-type-aux nil))
2205 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2207 ;;; Return the maximum number of bits an integer of the supplied type
2208 ;;; can take up, or NIL if it is unbounded. The second (third) value
2209 ;;; is T if the integer can be positive (negative) and NIL if not.
2210 ;;; Zero counts as positive.
2211 (defun integer-type-length (type)
2212 (if (numeric-type-p type)
2213 (let ((min (numeric-type-low type))
2214 (max (numeric-type-high type)))
2215 (values (and min max (max (integer-length min) (integer-length max)))
2216 (or (null max) (not (minusp max)))
2217 (or (null min) (minusp min))))
2220 ;;; See _Hacker's Delight_, Henry S. Warren, Jr. pp 58-63 for an
2221 ;;; explanation of LOG{AND,IOR,XOR}-DERIVE-UNSIGNED-{LOW,HIGH}-BOUND.
2222 ;;; Credit also goes to Raymond Toy for writing (and debugging!) similar
2223 ;;; versions in CMUCL, from which these functions copy liberally.
2225 (defun logand-derive-unsigned-low-bound (x y)
2226 (let ((a (numeric-type-low x))
2227 (b (numeric-type-high x))
2228 (c (numeric-type-low y))
2229 (d (numeric-type-high y)))
2230 (loop for m = (ash 1 (integer-length (lognor a c))) then (ash m -1)
2232 (unless (zerop (logand m (lognot a) (lognot c)))
2233 (let ((temp (logandc2 (logior a m) (1- m))))
2237 (setf temp (logandc2 (logior c m) (1- m)))
2241 finally (return (logand a c)))))
2243 (defun logand-derive-unsigned-high-bound (x y)
2244 (let ((a (numeric-type-low x))
2245 (b (numeric-type-high x))
2246 (c (numeric-type-low y))
2247 (d (numeric-type-high y)))
2248 (loop for m = (ash 1 (integer-length (logxor b d))) then (ash m -1)
2251 ((not (zerop (logand b (lognot d) m)))
2252 (let ((temp (logior (logandc2 b m) (1- m))))
2256 ((not (zerop (logand (lognot b) d m)))
2257 (let ((temp (logior (logandc2 d m) (1- m))))
2261 finally (return (logand b d)))))
2263 (defun logand-derive-type-aux (x y &optional same-leaf)
2265 (return-from logand-derive-type-aux x))
2266 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2267 (declare (ignore x-pos))
2268 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2269 (declare (ignore y-pos))
2271 ;; X must be positive.
2273 ;; They must both be positive.
2274 (cond ((and (null x-len) (null y-len))
2275 (specifier-type 'unsigned-byte))
2277 (specifier-type `(unsigned-byte* ,y-len)))
2279 (specifier-type `(unsigned-byte* ,x-len)))
2281 (let ((low (logand-derive-unsigned-low-bound x y))
2282 (high (logand-derive-unsigned-high-bound x y)))
2283 (specifier-type `(integer ,low ,high)))))
2284 ;; X is positive, but Y might be negative.
2286 (specifier-type 'unsigned-byte))
2288 (specifier-type `(unsigned-byte* ,x-len)))))
2289 ;; X might be negative.
2291 ;; Y must be positive.
2293 (specifier-type 'unsigned-byte))
2294 (t (specifier-type `(unsigned-byte* ,y-len))))
2295 ;; Either might be negative.
2296 (if (and x-len y-len)
2297 ;; The result is bounded.
2298 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2299 ;; We can't tell squat about the result.
2300 (specifier-type 'integer)))))))
2302 (defun logior-derive-unsigned-low-bound (x y)
2303 (let ((a (numeric-type-low x))
2304 (b (numeric-type-high x))
2305 (c (numeric-type-low y))
2306 (d (numeric-type-high y)))
2307 (loop for m = (ash 1 (integer-length (logxor a c))) then (ash m -1)
2310 ((not (zerop (logandc2 (logand c m) a)))
2311 (let ((temp (logand (logior a m) (1+ (lognot m)))))
2315 ((not (zerop (logandc2 (logand a m) c)))
2316 (let ((temp (logand (logior c m) (1+ (lognot m)))))
2320 finally (return (logior a c)))))
2322 (defun logior-derive-unsigned-high-bound (x y)
2323 (let ((a (numeric-type-low x))
2324 (b (numeric-type-high x))
2325 (c (numeric-type-low y))
2326 (d (numeric-type-high y)))
2327 (loop for m = (ash 1 (integer-length (logand b d))) then (ash m -1)
2329 (unless (zerop (logand b d m))
2330 (let ((temp (logior (- b m) (1- m))))
2334 (setf temp (logior (- d m) (1- m)))
2338 finally (return (logior b d)))))
2340 (defun logior-derive-type-aux (x y &optional same-leaf)
2342 (return-from logior-derive-type-aux x))
2343 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2344 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2346 ((and (not x-neg) (not y-neg))
2347 ;; Both are positive.
2348 (if (and x-len y-len)
2349 (let ((low (logior-derive-unsigned-low-bound x y))
2350 (high (logior-derive-unsigned-high-bound x y)))
2351 (specifier-type `(integer ,low ,high)))
2352 (specifier-type `(unsigned-byte* *))))
2354 ;; X must be negative.
2356 ;; Both are negative. The result is going to be negative
2357 ;; and be the same length or shorter than the smaller.
2358 (if (and x-len y-len)
2360 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2362 (specifier-type '(integer * -1)))
2363 ;; X is negative, but we don't know about Y. The result
2364 ;; will be negative, but no more negative than X.
2366 `(integer ,(or (numeric-type-low x) '*)
2369 ;; X might be either positive or negative.
2371 ;; But Y is negative. The result will be negative.
2373 `(integer ,(or (numeric-type-low y) '*)
2375 ;; We don't know squat about either. It won't get any bigger.
2376 (if (and x-len y-len)
2378 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2380 (specifier-type 'integer))))))))
2382 (defun logxor-derive-unsigned-low-bound (x y)
2383 (let ((a (numeric-type-low x))
2384 (b (numeric-type-high x))
2385 (c (numeric-type-low y))
2386 (d (numeric-type-high y)))
2387 (loop for m = (ash 1 (integer-length (logxor a c))) then (ash m -1)
2390 ((not (zerop (logandc2 (logand c m) a)))
2391 (let ((temp (logand (logior a m)
2395 ((not (zerop (logandc2 (logand a m) c)))
2396 (let ((temp (logand (logior c m)
2400 finally (return (logxor a c)))))
2402 (defun logxor-derive-unsigned-high-bound (x y)
2403 (let ((a (numeric-type-low x))
2404 (b (numeric-type-high x))
2405 (c (numeric-type-low y))
2406 (d (numeric-type-high y)))
2407 (loop for m = (ash 1 (integer-length (logand b d))) then (ash m -1)
2409 (unless (zerop (logand b d m))
2410 (let ((temp (logior (- b m) (1- m))))
2412 ((>= temp a) (setf b temp))
2413 (t (let ((temp (logior (- d m) (1- m))))
2416 finally (return (logxor b d)))))
2418 (defun logxor-derive-type-aux (x y &optional same-leaf)
2420 (return-from logxor-derive-type-aux (specifier-type '(eql 0))))
2421 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2422 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2424 ((and (not x-neg) (not y-neg))
2425 ;; Both are positive
2426 (if (and x-len y-len)
2427 (let ((low (logxor-derive-unsigned-low-bound x y))
2428 (high (logxor-derive-unsigned-high-bound x y)))
2429 (specifier-type `(integer ,low ,high)))
2430 (specifier-type '(unsigned-byte* *))))
2431 ((and (not x-pos) (not y-pos))
2432 ;; Both are negative. The result will be positive, and as long
2434 (specifier-type `(unsigned-byte* ,(if (and x-len y-len)
2437 ((or (and (not x-pos) (not y-neg))
2438 (and (not y-pos) (not x-neg)))
2439 ;; Either X is negative and Y is positive or vice-versa. The
2440 ;; result will be negative.
2441 (specifier-type `(integer ,(if (and x-len y-len)
2442 (ash -1 (max x-len y-len))
2445 ;; We can't tell what the sign of the result is going to be.
2446 ;; All we know is that we don't create new bits.
2448 (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2450 (specifier-type 'integer))))))
2452 (macrolet ((deffrob (logfun)
2453 (let ((fun-aux (symbolicate logfun "-DERIVE-TYPE-AUX")))
2454 `(defoptimizer (,logfun derive-type) ((x y))
2455 (two-arg-derive-type x y #',fun-aux #',logfun)))))
2460 (defoptimizer (logeqv derive-type) ((x y))
2461 (two-arg-derive-type x y (lambda (x y same-leaf)
2462 (lognot-derive-type-aux
2463 (logxor-derive-type-aux x y same-leaf)))
2465 (defoptimizer (lognand derive-type) ((x y))
2466 (two-arg-derive-type x y (lambda (x y same-leaf)
2467 (lognot-derive-type-aux
2468 (logand-derive-type-aux x y same-leaf)))
2470 (defoptimizer (lognor derive-type) ((x y))
2471 (two-arg-derive-type x y (lambda (x y same-leaf)
2472 (lognot-derive-type-aux
2473 (logior-derive-type-aux x y same-leaf)))
2475 (defoptimizer (logandc1 derive-type) ((x y))
2476 (two-arg-derive-type x y (lambda (x y same-leaf)
2478 (specifier-type '(eql 0))
2479 (logand-derive-type-aux
2480 (lognot-derive-type-aux x) y nil)))
2482 (defoptimizer (logandc2 derive-type) ((x y))
2483 (two-arg-derive-type x y (lambda (x y same-leaf)
2485 (specifier-type '(eql 0))
2486 (logand-derive-type-aux
2487 x (lognot-derive-type-aux y) nil)))
2489 (defoptimizer (logorc1 derive-type) ((x y))
2490 (two-arg-derive-type x y (lambda (x y same-leaf)
2492 (specifier-type '(eql -1))
2493 (logior-derive-type-aux
2494 (lognot-derive-type-aux x) y nil)))
2496 (defoptimizer (logorc2 derive-type) ((x y))
2497 (two-arg-derive-type x y (lambda (x y same-leaf)
2499 (specifier-type '(eql -1))
2500 (logior-derive-type-aux
2501 x (lognot-derive-type-aux y) nil)))
2504 ;;;; miscellaneous derive-type methods
2506 (defoptimizer (integer-length derive-type) ((x))
2507 (let ((x-type (lvar-type x)))
2508 (when (numeric-type-p x-type)
2509 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2510 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2511 ;; careful about LO or HI being NIL, though. Also, if 0 is
2512 ;; contained in X, the lower bound is obviously 0.
2513 (flet ((null-or-min (a b)
2514 (and a b (min (integer-length a)
2515 (integer-length b))))
2517 (and a b (max (integer-length a)
2518 (integer-length b)))))
2519 (let* ((min (numeric-type-low x-type))
2520 (max (numeric-type-high x-type))
2521 (min-len (null-or-min min max))
2522 (max-len (null-or-max min max)))
2523 (when (ctypep 0 x-type)
2525 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2527 (defoptimizer (isqrt derive-type) ((x))
2528 (let ((x-type (lvar-type x)))
2529 (when (numeric-type-p x-type)
2530 (let* ((lo (numeric-type-low x-type))
2531 (hi (numeric-type-high x-type))
2532 (lo-res (if lo (isqrt lo) '*))
2533 (hi-res (if hi (isqrt hi) '*)))
2534 (specifier-type `(integer ,lo-res ,hi-res))))))
2536 (defoptimizer (code-char derive-type) ((code))
2537 (let ((type (lvar-type code)))
2538 ;; FIXME: unions of integral ranges? It ought to be easier to do
2539 ;; this, given that CHARACTER-SET is basically an integral range
2540 ;; type. -- CSR, 2004-10-04
2541 (when (numeric-type-p type)
2542 (let* ((lo (numeric-type-low type))
2543 (hi (numeric-type-high type))
2544 (type (specifier-type `(character-set ((,lo . ,hi))))))
2546 ;; KLUDGE: when running on the host, we lose a slight amount
2547 ;; of precision so that we don't have to "unparse" types
2548 ;; that formally we can't, such as (CHARACTER-SET ((0
2549 ;; . 0))). -- CSR, 2004-10-06
2551 ((csubtypep type (specifier-type 'standard-char)) type)
2553 ((csubtypep type (specifier-type 'base-char))
2554 (specifier-type 'base-char))
2556 ((csubtypep type (specifier-type 'extended-char))
2557 (specifier-type 'extended-char))
2558 (t #+sb-xc-host (specifier-type 'character)
2559 #-sb-xc-host type))))))
2561 (defoptimizer (values derive-type) ((&rest values))
2562 (make-values-type :required (mapcar #'lvar-type values)))
2564 (defun signum-derive-type-aux (type)
2565 (if (eq (numeric-type-complexp type) :complex)
2566 (let* ((format (case (numeric-type-class type)
2567 ((integer rational) 'single-float)
2568 (t (numeric-type-format type))))
2569 (bound-format (or format 'float)))
2570 (make-numeric-type :class 'float
2573 :low (coerce -1 bound-format)
2574 :high (coerce 1 bound-format)))
2575 (let* ((interval (numeric-type->interval type))
2576 (range-info (interval-range-info interval))
2577 (contains-0-p (interval-contains-p 0 interval))
2578 (class (numeric-type-class type))
2579 (format (numeric-type-format type))
2580 (one (coerce 1 (or format class 'real)))
2581 (zero (coerce 0 (or format class 'real)))
2582 (minus-one (coerce -1 (or format class 'real)))
2583 (plus (make-numeric-type :class class :format format
2584 :low one :high one))
2585 (minus (make-numeric-type :class class :format format
2586 :low minus-one :high minus-one))
2587 ;; KLUDGE: here we have a fairly horrible hack to deal
2588 ;; with the schizophrenia in the type derivation engine.
2589 ;; The problem is that the type derivers reinterpret
2590 ;; numeric types as being exact; so (DOUBLE-FLOAT 0d0
2591 ;; 0d0) within the derivation mechanism doesn't include
2592 ;; -0d0. Ugh. So force it in here, instead.
2593 (zero (make-numeric-type :class class :format format
2594 :low (- zero) :high zero)))
2596 (+ (if contains-0-p (type-union plus zero) plus))
2597 (- (if contains-0-p (type-union minus zero) minus))
2598 (t (type-union minus zero plus))))))
2600 (defoptimizer (signum derive-type) ((num))
2601 (one-arg-derive-type num #'signum-derive-type-aux nil))
2603 ;;;; byte operations
2605 ;;;; We try to turn byte operations into simple logical operations.
2606 ;;;; First, we convert byte specifiers into separate size and position
2607 ;;;; arguments passed to internal %FOO functions. We then attempt to
2608 ;;;; transform the %FOO functions into boolean operations when the
2609 ;;;; size and position are constant and the operands are fixnums.
2611 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2612 ;; expressions that evaluate to the SIZE and POSITION of
2613 ;; the byte-specifier form SPEC. We may wrap a let around
2614 ;; the result of the body to bind some variables.
2616 ;; If the spec is a BYTE form, then bind the vars to the
2617 ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2618 ;; and BYTE-POSITION. The goal of this transformation is to
2619 ;; avoid consing up byte specifiers and then immediately
2620 ;; throwing them away.
2621 (with-byte-specifier ((size-var pos-var spec) &body body)
2622 (once-only ((spec `(macroexpand ,spec))
2624 `(if (and (consp ,spec)
2625 (eq (car ,spec) 'byte)
2626 (= (length ,spec) 3))
2627 (let ((,size-var (second ,spec))
2628 (,pos-var (third ,spec)))
2630 (let ((,size-var `(byte-size ,,temp))
2631 (,pos-var `(byte-position ,,temp)))
2632 `(let ((,,temp ,,spec))
2635 (define-source-transform ldb (spec int)
2636 (with-byte-specifier (size pos spec)
2637 `(%ldb ,size ,pos ,int)))
2639 (define-source-transform dpb (newbyte spec int)
2640 (with-byte-specifier (size pos spec)
2641 `(%dpb ,newbyte ,size ,pos ,int)))
2643 (define-source-transform mask-field (spec int)
2644 (with-byte-specifier (size pos spec)
2645 `(%mask-field ,size ,pos ,int)))
2647 (define-source-transform deposit-field (newbyte spec int)
2648 (with-byte-specifier (size pos spec)
2649 `(%deposit-field ,newbyte ,size ,pos ,int))))
2651 (defoptimizer (%ldb derive-type) ((size posn num))
2652 (let ((size (lvar-type size)))
2653 (if (and (numeric-type-p size)
2654 (csubtypep size (specifier-type 'integer)))
2655 (let ((size-high (numeric-type-high size)))
2656 (if (and size-high (<= size-high sb!vm:n-word-bits))
2657 (specifier-type `(unsigned-byte* ,size-high))
2658 (specifier-type 'unsigned-byte)))
2661 (defoptimizer (%mask-field derive-type) ((size posn num))
2662 (let ((size (lvar-type size))
2663 (posn (lvar-type posn)))
2664 (if (and (numeric-type-p size)
2665 (csubtypep size (specifier-type 'integer))
2666 (numeric-type-p posn)
2667 (csubtypep posn (specifier-type 'integer)))
2668 (let ((size-high (numeric-type-high size))
2669 (posn-high (numeric-type-high posn)))
2670 (if (and size-high posn-high
2671 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2672 (specifier-type `(unsigned-byte* ,(+ size-high posn-high)))
2673 (specifier-type 'unsigned-byte)))
2676 (defun %deposit-field-derive-type-aux (size posn int)
2677 (let ((size (lvar-type size))
2678 (posn (lvar-type posn))
2679 (int (lvar-type int)))
2680 (when (and (numeric-type-p size)
2681 (numeric-type-p posn)
2682 (numeric-type-p int))
2683 (let ((size-high (numeric-type-high size))
2684 (posn-high (numeric-type-high posn))
2685 (high (numeric-type-high int))
2686 (low (numeric-type-low int)))
2687 (when (and size-high posn-high high low
2688 ;; KLUDGE: we need this cutoff here, otherwise we
2689 ;; will merrily derive the type of %DPB as
2690 ;; (UNSIGNED-BYTE 1073741822), and then attempt to
2691 ;; canonicalize this type to (INTEGER 0 (1- (ASH 1
2692 ;; 1073741822))), with hilarious consequences. We
2693 ;; cutoff at 4*SB!VM:N-WORD-BITS to allow inference
2694 ;; over a reasonable amount of shifting, even on
2695 ;; the alpha/32 port, where N-WORD-BITS is 32 but
2696 ;; machine integers are 64-bits. -- CSR,
2698 (<= (+ size-high posn-high) (* 4 sb!vm:n-word-bits)))
2699 (let ((raw-bit-count (max (integer-length high)
2700 (integer-length low)
2701 (+ size-high posn-high))))
2704 `(signed-byte ,(1+ raw-bit-count))
2705 `(unsigned-byte* ,raw-bit-count)))))))))
2707 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2708 (%deposit-field-derive-type-aux size posn int))
2710 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2711 (%deposit-field-derive-type-aux size posn int))
2713 (deftransform %ldb ((size posn int)
2714 (fixnum fixnum integer)
2715 (unsigned-byte #.sb!vm:n-word-bits))
2716 "convert to inline logical operations"
2717 `(logand (ash int (- posn))
2718 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2719 (- size ,sb!vm:n-word-bits))))
2721 (deftransform %mask-field ((size posn int)
2722 (fixnum fixnum integer)
2723 (unsigned-byte #.sb!vm:n-word-bits))
2724 "convert to inline logical operations"
2726 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2727 (- size ,sb!vm:n-word-bits))
2730 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2731 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2732 ;;; as the result type, as that would allow result types that cover
2733 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2734 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2736 (deftransform %dpb ((new size posn int)
2738 (unsigned-byte #.sb!vm:n-word-bits))
2739 "convert to inline logical operations"
2740 `(let ((mask (ldb (byte size 0) -1)))
2741 (logior (ash (logand new mask) posn)
2742 (logand int (lognot (ash mask posn))))))
2744 (deftransform %dpb ((new size posn int)
2746 (signed-byte #.sb!vm:n-word-bits))
2747 "convert to inline logical operations"
2748 `(let ((mask (ldb (byte size 0) -1)))
2749 (logior (ash (logand new mask) posn)
2750 (logand int (lognot (ash mask posn))))))
2752 (deftransform %deposit-field ((new size posn int)
2754 (unsigned-byte #.sb!vm:n-word-bits))
2755 "convert to inline logical operations"
2756 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2757 (logior (logand new mask)
2758 (logand int (lognot mask)))))
2760 (deftransform %deposit-field ((new size posn int)
2762 (signed-byte #.sb!vm:n-word-bits))
2763 "convert to inline logical operations"
2764 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2765 (logior (logand new mask)
2766 (logand int (lognot mask)))))
2768 (defoptimizer (mask-signed-field derive-type) ((size x))
2769 (let ((size (lvar-type size)))
2770 (if (numeric-type-p size)
2771 (let ((size-high (numeric-type-high size)))
2772 (if (and size-high (<= 1 size-high sb!vm:n-word-bits))
2773 (specifier-type `(signed-byte ,size-high))
2778 ;;; Modular functions
2780 ;;; (ldb (byte s 0) (foo x y ...)) =
2781 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2783 ;;; and similar for other arguments.
2785 (defun make-modular-fun-type-deriver (prototype class width)
2787 (binding* ((info (info :function :info prototype) :exit-if-null)
2788 (fun (fun-info-derive-type info) :exit-if-null)
2789 (mask-type (specifier-type
2791 (:unsigned (let ((mask (1- (ash 1 width))))
2792 `(integer ,mask ,mask)))
2793 (:signed `(signed-byte ,width))))))
2795 (let ((res (funcall fun call)))
2797 (if (eq class :unsigned)
2798 (logand-derive-type-aux res mask-type))))))
2801 (binding* ((info (info :function :info prototype) :exit-if-null)
2802 (fun (fun-info-derive-type info) :exit-if-null)
2803 (res (funcall fun call) :exit-if-null)
2804 (mask-type (specifier-type
2806 (:unsigned (let ((mask (1- (ash 1 width))))
2807 `(integer ,mask ,mask)))
2808 (:signed `(signed-byte ,width))))))
2809 (if (eq class :unsigned)
2810 (logand-derive-type-aux res mask-type)))))
2812 ;;; Try to recursively cut all uses of LVAR to WIDTH bits.
2814 ;;; For good functions, we just recursively cut arguments; their
2815 ;;; "goodness" means that the result will not increase (in the
2816 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
2817 ;;; replaced with the version, cutting its result to WIDTH or more
2818 ;;; bits. For most functions (e.g. for +) we cut all arguments; for
2819 ;;; others (e.g. for ASH) we have "optimizers", cutting only necessary
2820 ;;; arguments (maybe to a different width) and returning the name of a
2821 ;;; modular version, if it exists, or NIL. If we have changed
2822 ;;; anything, we need to flush old derived types, because they have
2823 ;;; nothing in common with the new code.
2824 (defun cut-to-width (lvar class width)
2825 (declare (type lvar lvar) (type (integer 0) width))
2826 (let ((type (specifier-type (if (zerop width)
2828 `(,(ecase class (:unsigned 'unsigned-byte)
2829 (:signed 'signed-byte))
2831 (labels ((reoptimize-node (node name)
2832 (setf (node-derived-type node)
2834 (info :function :type name)))
2835 (setf (lvar-%derived-type (node-lvar node)) nil)
2836 (setf (node-reoptimize node) t)
2837 (setf (block-reoptimize (node-block node)) t)
2838 (reoptimize-component (node-component node) :maybe))
2839 (cut-node (node &aux did-something)
2840 (when (and (not (block-delete-p (node-block node)))
2841 (combination-p node)
2842 (eq (basic-combination-kind node) :known))
2843 (let* ((fun-ref (lvar-use (combination-fun node)))
2844 (fun-name (leaf-source-name (ref-leaf fun-ref)))
2845 (modular-fun (find-modular-version fun-name class width)))
2846 (when (and modular-fun
2847 (not (and (eq fun-name 'logand)
2849 (single-value-type (node-derived-type node))
2851 (binding* ((name (etypecase modular-fun
2852 ((eql :good) fun-name)
2854 (modular-fun-info-name modular-fun))
2856 (funcall modular-fun node width)))
2858 (unless (eql modular-fun :good)
2859 (setq did-something t)
2862 (find-free-fun name "in a strange place"))
2863 (setf (combination-kind node) :full))
2864 (unless (functionp modular-fun)
2865 (dolist (arg (basic-combination-args node))
2866 (when (cut-lvar arg)
2867 (setq did-something t))))
2869 (reoptimize-node node name))
2871 (cut-lvar (lvar &aux did-something)
2872 (do-uses (node lvar)
2873 (when (cut-node node)
2874 (setq did-something t)))
2878 (defoptimizer (logand optimizer) ((x y) node)
2879 (let ((result-type (single-value-type (node-derived-type node))))
2880 (when (numeric-type-p result-type)
2881 (let ((low (numeric-type-low result-type))
2882 (high (numeric-type-high result-type)))
2883 (when (and (numberp low)
2886 (let ((width (integer-length high)))
2887 (when (some (lambda (x) (<= width x))
2888 (modular-class-widths *unsigned-modular-class*))
2889 ;; FIXME: This should be (CUT-TO-WIDTH NODE WIDTH).
2890 (cut-to-width x :unsigned width)
2891 (cut-to-width y :unsigned width)
2892 nil ; After fixing above, replace with T.
2895 (defoptimizer (mask-signed-field optimizer) ((width x) node)
2896 (let ((result-type (single-value-type (node-derived-type node))))
2897 (when (numeric-type-p result-type)
2898 (let ((low (numeric-type-low result-type))
2899 (high (numeric-type-high result-type)))
2900 (when (and (numberp low) (numberp high))
2901 (let ((width (max (integer-length high) (integer-length low))))
2902 (when (some (lambda (x) (<= width x))
2903 (modular-class-widths *signed-modular-class*))
2904 ;; FIXME: This should be (CUT-TO-WIDTH NODE WIDTH).
2905 (cut-to-width x :signed width)
2906 nil ; After fixing above, replace with T.
2909 ;;; miscellanous numeric transforms
2911 ;;; If a constant appears as the first arg, swap the args.
2912 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
2913 (if (and (constant-lvar-p x)
2914 (not (constant-lvar-p y)))
2915 `(,(lvar-fun-name (basic-combination-fun node))
2918 (give-up-ir1-transform)))
2920 (dolist (x '(= char= + * logior logand logxor))
2921 (%deftransform x '(function * *) #'commutative-arg-swap
2922 "place constant arg last"))
2924 ;;; Handle the case of a constant BOOLE-CODE.
2925 (deftransform boole ((op x y) * *)
2926 "convert to inline logical operations"
2927 (unless (constant-lvar-p op)
2928 (give-up-ir1-transform "BOOLE code is not a constant."))
2929 (let ((control (lvar-value op)))
2931 (#.sb!xc:boole-clr 0)
2932 (#.sb!xc:boole-set -1)
2933 (#.sb!xc:boole-1 'x)
2934 (#.sb!xc:boole-2 'y)
2935 (#.sb!xc:boole-c1 '(lognot x))
2936 (#.sb!xc:boole-c2 '(lognot y))
2937 (#.sb!xc:boole-and '(logand x y))
2938 (#.sb!xc:boole-ior '(logior x y))
2939 (#.sb!xc:boole-xor '(logxor x y))
2940 (#.sb!xc:boole-eqv '(logeqv x y))
2941 (#.sb!xc:boole-nand '(lognand x y))
2942 (#.sb!xc:boole-nor '(lognor x y))
2943 (#.sb!xc:boole-andc1 '(logandc1 x y))
2944 (#.sb!xc:boole-andc2 '(logandc2 x y))
2945 (#.sb!xc:boole-orc1 '(logorc1 x y))
2946 (#.sb!xc:boole-orc2 '(logorc2 x y))
2948 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
2951 ;;;; converting special case multiply/divide to shifts
2953 ;;; If arg is a constant power of two, turn * into a shift.
2954 (deftransform * ((x y) (integer integer) *)
2955 "convert x*2^k to shift"
2956 (unless (constant-lvar-p y)
2957 (give-up-ir1-transform))
2958 (let* ((y (lvar-value y))
2960 (len (1- (integer-length y-abs))))
2961 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
2962 (give-up-ir1-transform))
2967 ;;; If arg is a constant power of two, turn FLOOR into a shift and
2968 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
2970 (flet ((frob (y ceil-p)
2971 (unless (constant-lvar-p y)
2972 (give-up-ir1-transform))
2973 (let* ((y (lvar-value y))
2975 (len (1- (integer-length y-abs))))
2976 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
2977 (give-up-ir1-transform))
2978 (let ((shift (- len))
2980 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
2981 `(let ((x (+ x ,delta)))
2983 `(values (ash (- x) ,shift)
2984 (- (- (logand (- x) ,mask)) ,delta))
2985 `(values (ash x ,shift)
2986 (- (logand x ,mask) ,delta))))))))
2987 (deftransform floor ((x y) (integer integer) *)
2988 "convert division by 2^k to shift"
2990 (deftransform ceiling ((x y) (integer integer) *)
2991 "convert division by 2^k to shift"
2994 ;;; Do the same for MOD.
2995 (deftransform mod ((x y) (integer integer) *)
2996 "convert remainder mod 2^k to LOGAND"
2997 (unless (constant-lvar-p y)
2998 (give-up-ir1-transform))
2999 (let* ((y (lvar-value y))
3001 (len (1- (integer-length y-abs))))
3002 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3003 (give-up-ir1-transform))
3004 (let ((mask (1- y-abs)))
3006 `(- (logand (- x) ,mask))
3007 `(logand x ,mask)))))
3009 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
3010 (deftransform truncate ((x y) (integer integer))
3011 "convert division by 2^k to shift"
3012 (unless (constant-lvar-p y)
3013 (give-up-ir1-transform))
3014 (let* ((y (lvar-value y))
3016 (len (1- (integer-length y-abs))))
3017 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3018 (give-up-ir1-transform))
3019 (let* ((shift (- len))
3022 (values ,(if (minusp y)
3024 `(- (ash (- x) ,shift)))
3025 (- (logand (- x) ,mask)))
3026 (values ,(if (minusp y)
3027 `(ash (- ,mask x) ,shift)
3029 (logand x ,mask))))))
3031 ;;; And the same for REM.
3032 (deftransform rem ((x y) (integer integer) *)
3033 "convert remainder mod 2^k to LOGAND"
3034 (unless (constant-lvar-p y)
3035 (give-up-ir1-transform))
3036 (let* ((y (lvar-value y))
3038 (len (1- (integer-length y-abs))))
3039 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3040 (give-up-ir1-transform))
3041 (let ((mask (1- y-abs)))
3043 (- (logand (- x) ,mask))
3044 (logand x ,mask)))))
3046 ;;;; arithmetic and logical identity operation elimination
3048 ;;; Flush calls to various arith functions that convert to the
3049 ;;; identity function or a constant.
3050 (macrolet ((def (name identity result)
3051 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
3052 "fold identity operations"
3059 (def logxor -1 (lognot x))
3062 (deftransform logand ((x y) (* (constant-arg t)) *)
3063 "fold identity operation"
3064 (let ((y (lvar-value y)))
3065 (unless (and (plusp y)
3066 (= y (1- (ash 1 (integer-length y)))))
3067 (give-up-ir1-transform))
3068 (unless (csubtypep (lvar-type x)
3069 (specifier-type `(integer 0 ,y)))
3070 (give-up-ir1-transform))
3073 (deftransform mask-signed-field ((size x) ((constant-arg t) *) *)
3074 "fold identity operation"
3075 (let ((size (lvar-value size)))
3076 (unless (csubtypep (lvar-type x) (specifier-type `(signed-byte ,size)))
3077 (give-up-ir1-transform))
3080 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
3081 ;;; (* 0 -4.0) is -0.0.
3082 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
3083 "convert (- 0 x) to negate"
3085 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
3086 "convert (* x 0) to 0"
3089 ;;; Return T if in an arithmetic op including lvars X and Y, the
3090 ;;; result type is not affected by the type of X. That is, Y is at
3091 ;;; least as contagious as X.
3093 (defun not-more-contagious (x y)
3094 (declare (type continuation x y))
3095 (let ((x (lvar-type x))
3097 (values (type= (numeric-contagion x y)
3098 (numeric-contagion y y)))))
3099 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
3100 ;;; XXX needs more work as valid transforms are missed; some cases are
3101 ;;; specific to particular transform functions so the use of this
3102 ;;; function may need a re-think.
3103 (defun not-more-contagious (x y)
3104 (declare (type lvar x y))
3105 (flet ((simple-numeric-type (num)
3106 (and (numeric-type-p num)
3107 ;; Return non-NIL if NUM is integer, rational, or a float
3108 ;; of some type (but not FLOAT)
3109 (case (numeric-type-class num)
3113 (numeric-type-format num))
3116 (let ((x (lvar-type x))
3118 (if (and (simple-numeric-type x)
3119 (simple-numeric-type y))
3120 (values (type= (numeric-contagion x y)
3121 (numeric-contagion y y)))))))
3125 ;;; If y is not constant, not zerop, or is contagious, or a positive
3126 ;;; float +0.0 then give up.
3127 (deftransform + ((x y) (t (constant-arg t)) *)
3129 (let ((val (lvar-value y)))
3130 (unless (and (zerop val)
3131 (not (and (floatp val) (plusp (float-sign val))))
3132 (not-more-contagious y x))
3133 (give-up-ir1-transform)))
3138 ;;; If y is not constant, not zerop, or is contagious, or a negative
3139 ;;; float -0.0 then give up.
3140 (deftransform - ((x y) (t (constant-arg t)) *)
3142 (let ((val (lvar-value y)))
3143 (unless (and (zerop val)
3144 (not (and (floatp val) (minusp (float-sign val))))
3145 (not-more-contagious y x))
3146 (give-up-ir1-transform)))
3149 ;;; Fold (OP x +/-1)
3150 (macrolet ((def (name result minus-result)
3151 `(deftransform ,name ((x y) (t (constant-arg real)) *)
3152 "fold identity operations"
3153 (let ((val (lvar-value y)))
3154 (unless (and (= (abs val) 1)
3155 (not-more-contagious y x))
3156 (give-up-ir1-transform))
3157 (if (minusp val) ',minus-result ',result)))))
3158 (def * x (%negate x))
3159 (def / x (%negate x))
3160 (def expt x (/ 1 x)))
3162 ;;; Fold (expt x n) into multiplications for small integral values of
3163 ;;; N; convert (expt x 1/2) to sqrt.
3164 (deftransform expt ((x y) (t (constant-arg real)) *)
3165 "recode as multiplication or sqrt"
3166 (let ((val (lvar-value y)))
3167 ;; If Y would cause the result to be promoted to the same type as
3168 ;; Y, we give up. If not, then the result will be the same type
3169 ;; as X, so we can replace the exponentiation with simple
3170 ;; multiplication and division for small integral powers.
3171 (unless (not-more-contagious y x)
3172 (give-up-ir1-transform))
3174 (let ((x-type (lvar-type x)))
3175 (cond ((csubtypep x-type (specifier-type '(or rational
3176 (complex rational))))
3178 ((csubtypep x-type (specifier-type 'real))
3182 ((csubtypep x-type (specifier-type 'complex))
3183 ;; both parts are float
3185 (t (give-up-ir1-transform)))))
3186 ((= val 2) '(* x x))
3187 ((= val -2) '(/ (* x x)))
3188 ((= val 3) '(* x x x))
3189 ((= val -3) '(/ (* x x x)))
3190 ((= val 1/2) '(sqrt x))
3191 ((= val -1/2) '(/ (sqrt x)))
3192 (t (give-up-ir1-transform)))))
3194 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
3195 ;;; transformations?
3196 ;;; Perhaps we should have to prove that the denominator is nonzero before
3197 ;;; doing them? -- WHN 19990917
3198 (macrolet ((def (name)
3199 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3206 (macrolet ((def (name)
3207 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3216 ;;;; character operations
3218 (deftransform char-equal ((a b) (base-char base-char))
3220 '(let* ((ac (char-code a))
3222 (sum (logxor ac bc)))
3224 (when (eql sum #x20)
3225 (let ((sum (+ ac bc)))
3226 (or (and (> sum 161) (< sum 213))
3227 (and (> sum 415) (< sum 461))
3228 (and (> sum 463) (< sum 477))))))))
3230 (deftransform char-upcase ((x) (base-char))
3232 '(let ((n-code (char-code x)))
3233 (if (or (and (> n-code #o140) ; Octal 141 is #\a.
3234 (< n-code #o173)) ; Octal 172 is #\z.
3235 (and (> n-code #o337)
3237 (and (> n-code #o367)
3239 (code-char (logxor #x20 n-code))
3242 (deftransform char-downcase ((x) (base-char))
3244 '(let ((n-code (char-code x)))
3245 (if (or (and (> n-code 64) ; 65 is #\A.
3246 (< n-code 91)) ; 90 is #\Z.
3251 (code-char (logxor #x20 n-code))
3254 ;;;; equality predicate transforms
3256 ;;; Return true if X and Y are lvars whose only use is a
3257 ;;; reference to the same leaf, and the value of the leaf cannot
3259 (defun same-leaf-ref-p (x y)
3260 (declare (type lvar x y))
3261 (let ((x-use (principal-lvar-use x))
3262 (y-use (principal-lvar-use y)))
3265 (eq (ref-leaf x-use) (ref-leaf y-use))
3266 (constant-reference-p x-use))))
3268 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
3269 ;;; if there is no intersection between the types of the arguments,
3270 ;;; then the result is definitely false.
3271 (deftransform simple-equality-transform ((x y) * *
3274 ((same-leaf-ref-p x y) t)
3275 ((not (types-equal-or-intersect (lvar-type x) (lvar-type y)))
3277 (t (give-up-ir1-transform))))
3280 `(%deftransform ',x '(function * *) #'simple-equality-transform)))
3284 ;;; This is similar to SIMPLE-EQUALITY-TRANSFORM, except that we also
3285 ;;; try to convert to a type-specific predicate or EQ:
3286 ;;; -- If both args are characters, convert to CHAR=. This is better than
3287 ;;; just converting to EQ, since CHAR= may have special compilation
3288 ;;; strategies for non-standard representations, etc.
3289 ;;; -- If either arg is definitely a fixnum, we check to see if X is
3290 ;;; constant and if so, put X second. Doing this results in better
3291 ;;; code from the backend, since the backend assumes that any constant
3292 ;;; argument comes second.
3293 ;;; -- If either arg is definitely not a number or a fixnum, then we
3294 ;;; can compare with EQ.
3295 ;;; -- Otherwise, we try to put the arg we know more about second. If X
3296 ;;; is constant then we put it second. If X is a subtype of Y, we put
3297 ;;; it second. These rules make it easier for the back end to match
3298 ;;; these interesting cases.
3299 (deftransform eql ((x y) * * :node node)
3300 "convert to simpler equality predicate"
3301 (let ((x-type (lvar-type x))
3302 (y-type (lvar-type y))
3303 (char-type (specifier-type 'character)))
3304 (flet ((simple-type-p (type)
3305 (csubtypep type (specifier-type '(or fixnum (not number)))))
3306 (fixnum-type-p (type)
3307 (csubtypep type (specifier-type 'fixnum))))
3309 ((same-leaf-ref-p x y) t)
3310 ((not (types-equal-or-intersect x-type y-type))
3312 ((and (csubtypep x-type char-type)
3313 (csubtypep y-type char-type))
3315 ((or (fixnum-type-p x-type) (fixnum-type-p y-type))
3316 (commutative-arg-swap node))
3317 ((or (simple-type-p x-type) (simple-type-p y-type))
3319 ((and (not (constant-lvar-p y))
3320 (or (constant-lvar-p x)
3321 (and (csubtypep x-type y-type)
3322 (not (csubtypep y-type x-type)))))
3325 (give-up-ir1-transform))))))
3327 ;;; similarly to the EQL transform above, we attempt to constant-fold
3328 ;;; or convert to a simpler predicate: mostly we have to be careful
3329 ;;; with strings and bit-vectors.
3330 (deftransform equal ((x y) * *)
3331 "convert to simpler equality predicate"
3332 (let ((x-type (lvar-type x))
3333 (y-type (lvar-type y))
3334 (string-type (specifier-type 'string))
3335 (bit-vector-type (specifier-type 'bit-vector)))
3337 ((same-leaf-ref-p x y) t)
3338 ((and (csubtypep x-type string-type)
3339 (csubtypep y-type string-type))
3341 ((and (csubtypep x-type bit-vector-type)
3342 (csubtypep y-type bit-vector-type))
3343 '(bit-vector-= x y))
3344 ;; if at least one is not a string, and at least one is not a
3345 ;; bit-vector, then we can reason from types.
3346 ((and (not (and (types-equal-or-intersect x-type string-type)
3347 (types-equal-or-intersect y-type string-type)))
3348 (not (and (types-equal-or-intersect x-type bit-vector-type)
3349 (types-equal-or-intersect y-type bit-vector-type)))
3350 (not (types-equal-or-intersect x-type y-type)))
3352 (t (give-up-ir1-transform)))))
3354 ;;; Convert to EQL if both args are rational and complexp is specified
3355 ;;; and the same for both.
3356 (deftransform = ((x y) * *)
3358 (let ((x-type (lvar-type x))
3359 (y-type (lvar-type y)))
3360 (if (and (csubtypep x-type (specifier-type 'number))
3361 (csubtypep y-type (specifier-type 'number)))
3362 (cond ((or (and (csubtypep x-type (specifier-type 'float))
3363 (csubtypep y-type (specifier-type 'float)))
3364 (and (csubtypep x-type (specifier-type '(complex float)))
3365 (csubtypep y-type (specifier-type '(complex float)))))
3366 ;; They are both floats. Leave as = so that -0.0 is
3367 ;; handled correctly.
3368 (give-up-ir1-transform))
3369 ((or (and (csubtypep x-type (specifier-type 'rational))
3370 (csubtypep y-type (specifier-type 'rational)))
3371 (and (csubtypep x-type
3372 (specifier-type '(complex rational)))
3374 (specifier-type '(complex rational)))))
3375 ;; They are both rationals and complexp is the same.
3379 (give-up-ir1-transform
3380 "The operands might not be the same type.")))
3381 (give-up-ir1-transform
3382 "The operands might not be the same type."))))
3384 ;;; If LVAR's type is a numeric type, then return the type, otherwise
3385 ;;; GIVE-UP-IR1-TRANSFORM.
3386 (defun numeric-type-or-lose (lvar)
3387 (declare (type lvar lvar))
3388 (let ((res (lvar-type lvar)))
3389 (unless (numeric-type-p res) (give-up-ir1-transform))
3392 ;;; See whether we can statically determine (< X Y) using type
3393 ;;; information. If X's high bound is < Y's low, then X < Y.
3394 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
3395 ;;; NIL). If not, at least make sure any constant arg is second.
3396 (macrolet ((def (name inverse reflexive-p surely-true surely-false)
3397 `(deftransform ,name ((x y))
3398 (if (same-leaf-ref-p x y)
3400 (let ((ix (or (type-approximate-interval (lvar-type x))
3401 (give-up-ir1-transform)))
3402 (iy (or (type-approximate-interval (lvar-type y))
3403 (give-up-ir1-transform))))
3408 ((and (constant-lvar-p x)
3409 (not (constant-lvar-p y)))
3412 (give-up-ir1-transform))))))))
3413 (def < > nil (interval-< ix iy) (interval->= ix iy))
3414 (def > < nil (interval-< iy ix) (interval->= iy ix))
3415 (def <= >= t (interval->= iy ix) (interval-< iy ix))
3416 (def >= <= t (interval->= ix iy) (interval-< ix iy)))
3418 (defun ir1-transform-char< (x y first second inverse)
3420 ((same-leaf-ref-p x y) nil)
3421 ;; If we had interval representation of character types, as we
3422 ;; might eventually have to to support 2^21 characters, then here
3423 ;; we could do some compile-time computation as in transforms for
3424 ;; < above. -- CSR, 2003-07-01
3425 ((and (constant-lvar-p first)
3426 (not (constant-lvar-p second)))
3428 (t (give-up-ir1-transform))))
3430 (deftransform char< ((x y) (character character) *)
3431 (ir1-transform-char< x y x y 'char>))
3433 (deftransform char> ((x y) (character character) *)
3434 (ir1-transform-char< y x x y 'char<))
3436 ;;;; converting N-arg comparisons
3438 ;;;; We convert calls to N-arg comparison functions such as < into
3439 ;;;; two-arg calls. This transformation is enabled for all such
3440 ;;;; comparisons in this file. If any of these predicates are not
3441 ;;;; open-coded, then the transformation should be removed at some
3442 ;;;; point to avoid pessimization.
3444 ;;; This function is used for source transformation of N-arg
3445 ;;; comparison functions other than inequality. We deal both with
3446 ;;; converting to two-arg calls and inverting the sense of the test,
3447 ;;; if necessary. If the call has two args, then we pass or return a
3448 ;;; negated test as appropriate. If it is a degenerate one-arg call,
3449 ;;; then we transform to code that returns true. Otherwise, we bind
3450 ;;; all the arguments and expand into a bunch of IFs.
3451 (declaim (ftype (function (symbol list boolean t) *) multi-compare))
3452 (defun multi-compare (predicate args not-p type)
3453 (let ((nargs (length args)))
3454 (cond ((< nargs 1) (values nil t))
3455 ((= nargs 1) `(progn (the ,type ,@args) t))
3458 `(if (,predicate ,(first args) ,(second args)) nil t)
3461 (do* ((i (1- nargs) (1- i))
3463 (current (gensym) (gensym))
3464 (vars (list current) (cons current vars))
3466 `(if (,predicate ,current ,last)
3468 `(if (,predicate ,current ,last)
3471 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3474 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
3475 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
3476 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
3477 (define-source-transform <= (&rest args) (multi-compare '> args t 'real))
3478 (define-source-transform >= (&rest args) (multi-compare '< args t 'real))
3480 (define-source-transform char= (&rest args) (multi-compare 'char= args nil
3482 (define-source-transform char< (&rest args) (multi-compare 'char< args nil
3484 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
3486 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
3488 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
3491 (define-source-transform char-equal (&rest args)
3492 (multi-compare 'char-equal args nil 'character))
3493 (define-source-transform char-lessp (&rest args)
3494 (multi-compare 'char-lessp args nil 'character))
3495 (define-source-transform char-greaterp (&rest args)
3496 (multi-compare 'char-greaterp args nil 'character))
3497 (define-source-transform char-not-greaterp (&rest args)
3498 (multi-compare 'char-greaterp args t 'character))
3499 (define-source-transform char-not-lessp (&rest args)
3500 (multi-compare 'char-lessp args t 'character))
3502 ;;; This function does source transformation of N-arg inequality
3503 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3504 ;;; arg cases. If there are more than two args, then we expand into
3505 ;;; the appropriate n^2 comparisons only when speed is important.
3506 (declaim (ftype (function (symbol list t) *) multi-not-equal))
3507 (defun multi-not-equal (predicate args type)
3508 (let ((nargs (length args)))
3509 (cond ((< nargs 1) (values nil t))
3510 ((= nargs 1) `(progn (the ,type ,@args) t))
3512 `(if (,predicate ,(first args) ,(second args)) nil t))
3513 ((not (policy *lexenv*
3514 (and (>= speed space)
3515 (>= speed compilation-speed))))
3518 (let ((vars (make-gensym-list nargs)))
3519 (do ((var vars next)
3520 (next (cdr vars) (cdr next))
3523 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3525 (let ((v1 (first var)))
3527 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3529 (define-source-transform /= (&rest args)
3530 (multi-not-equal '= args 'number))
3531 (define-source-transform char/= (&rest args)
3532 (multi-not-equal 'char= args 'character))
3533 (define-source-transform char-not-equal (&rest args)
3534 (multi-not-equal 'char-equal args 'character))
3536 ;;; Expand MAX and MIN into the obvious comparisons.
3537 (define-source-transform max (arg0 &rest rest)
3538 (once-only ((arg0 arg0))
3540 `(values (the real ,arg0))
3541 `(let ((maxrest (max ,@rest)))
3542 (if (>= ,arg0 maxrest) ,arg0 maxrest)))))
3543 (define-source-transform min (arg0 &rest rest)
3544 (once-only ((arg0 arg0))
3546 `(values (the real ,arg0))
3547 `(let ((minrest (min ,@rest)))
3548 (if (<= ,arg0 minrest) ,arg0 minrest)))))
3550 ;;;; converting N-arg arithmetic functions
3552 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3553 ;;;; versions, and degenerate cases are flushed.
3555 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3556 (declaim (ftype (function (symbol t list) list) associate-args))
3557 (defun associate-args (function first-arg more-args)
3558 (let ((next (rest more-args))
3559 (arg (first more-args)))
3561 `(,function ,first-arg ,arg)
3562 (associate-args function `(,function ,first-arg ,arg) next))))
3564 ;;; Do source transformations for transitive functions such as +.
3565 ;;; One-arg cases are replaced with the arg and zero arg cases with
3566 ;;; the identity. ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3567 ;;; ensure (with THE) that the argument in one-argument calls is.
3568 (defun source-transform-transitive (fun args identity
3569 &optional one-arg-result-type)
3570 (declare (symbol fun) (list args))
3573 (1 (if one-arg-result-type
3574 `(values (the ,one-arg-result-type ,(first args)))
3575 `(values ,(first args))))
3578 (associate-args fun (first args) (rest args)))))
3580 (define-source-transform + (&rest args)
3581 (source-transform-transitive '+ args 0 'number))
3582 (define-source-transform * (&rest args)
3583 (source-transform-transitive '* args 1 'number))
3584 (define-source-transform logior (&rest args)
3585 (source-transform-transitive 'logior args 0 'integer))
3586 (define-source-transform logxor (&rest args)
3587 (source-transform-transitive 'logxor args 0 'integer))
3588 (define-source-transform logand (&rest args)
3589 (source-transform-transitive 'logand args -1 'integer))
3590 (define-source-transform logeqv (&rest args)
3591 (source-transform-transitive 'logeqv args -1 'integer))
3593 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3594 ;;; because when they are given one argument, they return its absolute
3597 (define-source-transform gcd (&rest args)
3600 (1 `(abs (the integer ,(first args))))
3602 (t (associate-args 'gcd (first args) (rest args)))))
3604 (define-source-transform lcm (&rest args)
3607 (1 `(abs (the integer ,(first args))))
3609 (t (associate-args 'lcm (first args) (rest args)))))
3611 ;;; Do source transformations for intransitive n-arg functions such as
3612 ;;; /. With one arg, we form the inverse. With two args we pass.
3613 ;;; Otherwise we associate into two-arg calls.
3614 (declaim (ftype (function (symbol list t)
3615 (values list &optional (member nil t)))
3616 source-transform-intransitive))
3617 (defun source-transform-intransitive (function args inverse)
3619 ((0 2) (values nil t))
3620 (1 `(,@inverse ,(first args)))
3621 (t (associate-args function (first args) (rest args)))))
3623 (define-source-transform - (&rest args)
3624 (source-transform-intransitive '- args '(%negate)))
3625 (define-source-transform / (&rest args)
3626 (source-transform-intransitive '/ args '(/ 1)))
3628 ;;;; transforming APPLY
3630 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3631 ;;; only needs to understand one kind of variable-argument call. It is
3632 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3633 (define-source-transform apply (fun arg &rest more-args)
3634 (let ((args (cons arg more-args)))
3635 `(multiple-value-call ,fun
3636 ,@(mapcar (lambda (x)
3639 (values-list ,(car (last args))))))
3641 ;;;; transforming FORMAT
3643 ;;;; If the control string is a compile-time constant, then replace it
3644 ;;;; with a use of the FORMATTER macro so that the control string is
3645 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3646 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3647 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3649 ;;; for compile-time argument count checking.
3651 ;;; FIXME II: In some cases, type information could be correlated; for
3652 ;;; instance, ~{ ... ~} requires a list argument, so if the lvar-type
3653 ;;; of a corresponding argument is known and does not intersect the
3654 ;;; list type, a warning could be signalled.
3655 (defun check-format-args (string args fun)
3656 (declare (type string string))
3657 (unless (typep string 'simple-string)
3658 (setq string (coerce string 'simple-string)))
3659 (multiple-value-bind (min max)
3660 (handler-case (sb!format:%compiler-walk-format-string string args)
3661 (sb!format:format-error (c)
3662 (compiler-warn "~A" c)))
3664 (let ((nargs (length args)))
3667 (warn 'format-too-few-args-warning
3669 "Too few arguments (~D) to ~S ~S: requires at least ~D."
3670 :format-arguments (list nargs fun string min)))
3672 (warn 'format-too-many-args-warning
3674 "Too many arguments (~D) to ~S ~S: uses at most ~D."
3675 :format-arguments (list nargs fun string max))))))))
3677 (defoptimizer (format optimizer) ((dest control &rest args))
3678 (when (constant-lvar-p control)
3679 (let ((x (lvar-value control)))
3681 (check-format-args x args 'format)))))
3683 ;;; We disable this transform in the cross-compiler to save memory in
3684 ;;; the target image; most of the uses of FORMAT in the compiler are for
3685 ;;; error messages, and those don't need to be particularly fast.
3687 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3688 :policy (> speed space))
3689 (unless (constant-lvar-p control)
3690 (give-up-ir1-transform "The control string is not a constant."))
3691 (let ((arg-names (make-gensym-list (length args))))
3692 `(lambda (dest control ,@arg-names)
3693 (declare (ignore control))
3694 (format dest (formatter ,(lvar-value control)) ,@arg-names))))
3696 (deftransform format ((stream control &rest args) (stream function &rest t) *
3697 :policy (> speed space))
3698 (let ((arg-names (make-gensym-list (length args))))
3699 `(lambda (stream control ,@arg-names)
3700 (funcall control stream ,@arg-names)
3703 (deftransform format ((tee control &rest args) ((member t) function &rest t) *
3704 :policy (> speed space))
3705 (let ((arg-names (make-gensym-list (length args))))
3706 `(lambda (tee control ,@arg-names)
3707 (declare (ignore tee))
3708 (funcall control *standard-output* ,@arg-names)
3711 (deftransform pathname ((pathspec) (pathname) *)
3714 (deftransform pathname ((pathspec) (string) *)
3715 '(values (parse-namestring pathspec)))
3719 `(defoptimizer (,name optimizer) ((control &rest args))
3720 (when (constant-lvar-p control)
3721 (let ((x (lvar-value control)))
3723 (check-format-args x args ',name)))))))
3726 #+sb-xc-host ; Only we should be using these
3729 (def compiler-abort)
3730 (def compiler-error)
3732 (def compiler-style-warn)
3733 (def compiler-notify)
3734 (def maybe-compiler-notify)
3737 (defoptimizer (cerror optimizer) ((report control &rest args))
3738 (when (and (constant-lvar-p control)
3739 (constant-lvar-p report))
3740 (let ((x (lvar-value control))
3741 (y (lvar-value report)))
3742 (when (and (stringp x) (stringp y))
3743 (multiple-value-bind (min1 max1)
3745 (sb!format:%compiler-walk-format-string x args)
3746 (sb!format:format-error (c)
3747 (compiler-warn "~A" c)))
3749 (multiple-value-bind (min2 max2)
3751 (sb!format:%compiler-walk-format-string y args)
3752 (sb!format:format-error (c)
3753 (compiler-warn "~A" c)))
3755 (let ((nargs (length args)))
3757 ((< nargs (min min1 min2))
3758 (warn 'format-too-few-args-warning
3760 "Too few arguments (~D) to ~S ~S ~S: ~
3761 requires at least ~D."
3763 (list nargs 'cerror y x (min min1 min2))))
3764 ((> nargs (max max1 max2))
3765 (warn 'format-too-many-args-warning
3767 "Too many arguments (~D) to ~S ~S ~S: ~
3770 (list nargs 'cerror y x (max max1 max2))))))))))))))
3772 (defoptimizer (coerce derive-type) ((value type))
3774 ((constant-lvar-p type)
3775 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3776 ;; but dealing with the niggle that complex canonicalization gets
3777 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3779 (let* ((specifier (lvar-value type))
3780 (result-typeoid (careful-specifier-type specifier)))
3782 ((null result-typeoid) nil)
3783 ((csubtypep result-typeoid (specifier-type 'number))
3784 ;; the difficult case: we have to cope with ANSI 12.1.5.3
3785 ;; Rule of Canonical Representation for Complex Rationals,
3786 ;; which is a truly nasty delivery to field.
3788 ((csubtypep result-typeoid (specifier-type 'real))
3789 ;; cleverness required here: it would be nice to deduce
3790 ;; that something of type (INTEGER 2 3) coerced to type
3791 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3792 ;; FLOAT gets its own clause because it's implemented as
3793 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3796 ((and (numeric-type-p result-typeoid)
3797 (eq (numeric-type-complexp result-typeoid) :real))
3798 ;; FIXME: is this clause (a) necessary or (b) useful?
3800 ((or (csubtypep result-typeoid
3801 (specifier-type '(complex single-float)))
3802 (csubtypep result-typeoid
3803 (specifier-type '(complex double-float)))
3805 (csubtypep result-typeoid
3806 (specifier-type '(complex long-float))))
3807 ;; float complex types are never canonicalized.
3810 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
3811 ;; probably just a COMPLEX or equivalent. So, in that
3812 ;; case, we will return a complex or an object of the
3813 ;; provided type if it's rational:
3814 (type-union result-typeoid
3815 (type-intersection (lvar-type value)
3816 (specifier-type 'rational))))))
3817 (t result-typeoid))))
3819 ;; OK, the result-type argument isn't constant. However, there
3820 ;; are common uses where we can still do better than just
3821 ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
3822 ;; where Y is of a known type. See messages on cmucl-imp
3823 ;; 2001-02-14 and sbcl-devel 2002-12-12. We only worry here
3824 ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
3825 ;; the basis that it's unlikely that other uses are both
3826 ;; time-critical and get to this branch of the COND (non-constant
3827 ;; second argument to COERCE). -- CSR, 2002-12-16
3828 (let ((value-type (lvar-type value))
3829 (type-type (lvar-type type)))
3831 ((good-cons-type-p (cons-type)
3832 ;; Make sure the cons-type we're looking at is something
3833 ;; we're prepared to handle which is basically something
3834 ;; that array-element-type can return.
3835 (or (and (member-type-p cons-type)
3836 (null (rest (member-type-members cons-type)))
3837 (null (first (member-type-members cons-type))))
3838 (let ((car-type (cons-type-car-type cons-type)))
3839 (and (member-type-p car-type)
3840 (null (rest (member-type-members car-type)))
3841 (or (symbolp (first (member-type-members car-type)))
3842 (numberp (first (member-type-members car-type)))
3843 (and (listp (first (member-type-members
3845 (numberp (first (first (member-type-members
3847 (good-cons-type-p (cons-type-cdr-type cons-type))))))
3848 (unconsify-type (good-cons-type)
3849 ;; Convert the "printed" respresentation of a cons
3850 ;; specifier into a type specifier. That is, the
3851 ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
3852 ;; NULL)) is converted to (SIGNED-BYTE 16).
3853 (cond ((or (null good-cons-type)
3854 (eq good-cons-type 'null))
3856 ((and (eq (first good-cons-type) 'cons)
3857 (eq (first (second good-cons-type)) 'member))
3858 `(,(second (second good-cons-type))
3859 ,@(unconsify-type (caddr good-cons-type))))))
3860 (coerceable-p (c-type)
3861 ;; Can the value be coerced to the given type? Coerce is
3862 ;; complicated, so we don't handle every possible case
3863 ;; here---just the most common and easiest cases:
3865 ;; * Any REAL can be coerced to a FLOAT type.
3866 ;; * Any NUMBER can be coerced to a (COMPLEX
3867 ;; SINGLE/DOUBLE-FLOAT).
3869 ;; FIXME I: we should also be able to deal with characters
3872 ;; FIXME II: I'm not sure that anything is necessary
3873 ;; here, at least while COMPLEX is not a specialized
3874 ;; array element type in the system. Reasoning: if
3875 ;; something cannot be coerced to the requested type, an
3876 ;; error will be raised (and so any downstream compiled
3877 ;; code on the assumption of the returned type is
3878 ;; unreachable). If something can, then it will be of
3879 ;; the requested type, because (by assumption) COMPLEX
3880 ;; (and other difficult types like (COMPLEX INTEGER)
3881 ;; aren't specialized types.
3882 (let ((coerced-type c-type))
3883 (or (and (subtypep coerced-type 'float)
3884 (csubtypep value-type (specifier-type 'real)))
3885 (and (subtypep coerced-type
3886 '(or (complex single-float)
3887 (complex double-float)))
3888 (csubtypep value-type (specifier-type 'number))))))
3889 (process-types (type)
3890 ;; FIXME: This needs some work because we should be able
3891 ;; to derive the resulting type better than just the
3892 ;; type arg of coerce. That is, if X is (INTEGER 10
3893 ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
3894 ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
3896 (cond ((member-type-p type)
3897 (let ((members (member-type-members type)))
3898 (if (every #'coerceable-p members)
3899 (specifier-type `(or ,@members))
3901 ((and (cons-type-p type)
3902 (good-cons-type-p type))
3903 (let ((c-type (unconsify-type (type-specifier type))))
3904 (if (coerceable-p c-type)
3905 (specifier-type c-type)
3908 *universal-type*))))
3909 (cond ((union-type-p type-type)
3910 (apply #'type-union (mapcar #'process-types
3911 (union-type-types type-type))))
3912 ((or (member-type-p type-type)
3913 (cons-type-p type-type))
3914 (process-types type-type))
3916 *universal-type*)))))))
3918 (defoptimizer (compile derive-type) ((nameoid function))
3919 (when (csubtypep (lvar-type nameoid)
3920 (specifier-type 'null))
3921 (values-specifier-type '(values function boolean boolean))))
3923 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
3924 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
3925 ;;; optimizer, above).
3926 (defoptimizer (array-element-type derive-type) ((array))
3927 (let ((array-type (lvar-type array)))
3928 (labels ((consify (list)
3931 `(cons (eql ,(car list)) ,(consify (rest list)))))
3932 (get-element-type (a)
3934 (type-specifier (array-type-specialized-element-type a))))
3935 (cond ((eq element-type '*)
3936 (specifier-type 'type-specifier))
3937 ((symbolp element-type)
3938 (make-member-type :members (list element-type)))
3939 ((consp element-type)
3940 (specifier-type (consify element-type)))
3942 (error "can't understand type ~S~%" element-type))))))
3943 (cond ((array-type-p array-type)
3944 (get-element-type array-type))
3945 ((union-type-p array-type)
3947 (mapcar #'get-element-type (union-type-types array-type))))
3949 *universal-type*)))))
3951 ;;; Like CMU CL, we use HEAPSORT. However, other than that, this code
3952 ;;; isn't really related to the CMU CL code, since instead of trying
3953 ;;; to generalize the CMU CL code to allow START and END values, this
3954 ;;; code has been written from scratch following Chapter 7 of
3955 ;;; _Introduction to Algorithms_ by Corman, Rivest, and Shamir.
3956 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
3957 ;; Like CMU CL, we use HEAPSORT. However, other than that, this code
3958 ;; isn't really related to the CMU CL code, since instead of trying
3959 ;; to generalize the CMU CL code to allow START and END values, this
3960 ;; code has been written from scratch following Chapter 7 of
3961 ;; _Introduction to Algorithms_ by Corman, Rivest, and Shamir.
3962 `(macrolet ((%index (x) `(truly-the index ,x))
3963 (%parent (i) `(ash ,i -1))
3964 (%left (i) `(%index (ash ,i 1)))
3965 (%right (i) `(%index (1+ (ash ,i 1))))
3968 (left (%left i) (%left i)))
3969 ((> left current-heap-size))
3970 (declare (type index i left))
3971 (let* ((i-elt (%elt i))
3972 (i-key (funcall keyfun i-elt))
3973 (left-elt (%elt left))
3974 (left-key (funcall keyfun left-elt)))
3975 (multiple-value-bind (large large-elt large-key)
3976 (if (funcall ,',predicate i-key left-key)
3977 (values left left-elt left-key)
3978 (values i i-elt i-key))
3979 (let ((right (%right i)))
3980 (multiple-value-bind (largest largest-elt)
3981 (if (> right current-heap-size)
3982 (values large large-elt)
3983 (let* ((right-elt (%elt right))
3984 (right-key (funcall keyfun right-elt)))
3985 (if (funcall ,',predicate large-key right-key)
3986 (values right right-elt)
3987 (values large large-elt))))
3988 (cond ((= largest i)
3991 (setf (%elt i) largest-elt
3992 (%elt largest) i-elt
3994 (%sort-vector (keyfun &optional (vtype 'vector))
3995 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had
3996 ;; trouble getting type inference to
3997 ;; propagate all the way through this
3998 ;; tangled mess of inlining. The TRULY-THE
3999 ;; here works around that. -- WHN
4001 `(aref (truly-the ,',vtype ,',',vector)
4002 (%index (+ (%index ,i) start-1)))))
4003 (let (;; Heaps prefer 1-based addressing.
4004 (start-1 (1- ,',start))
4005 (current-heap-size (- ,',end ,',start))
4007 (declare (type (integer -1 #.(1- most-positive-fixnum))
4009 (declare (type index current-heap-size))
4010 (declare (type function keyfun))
4011 (loop for i of-type index
4012 from (ash current-heap-size -1) downto 1 do
4015 (when (< current-heap-size 2)
4017 (rotatef (%elt 1) (%elt current-heap-size))
4018 (decf current-heap-size)
4020 (if (typep ,vector 'simple-vector)
4021 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
4022 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
4024 ;; Special-casing the KEY=NIL case lets us avoid some
4026 (%sort-vector #'identity simple-vector)
4027 (%sort-vector ,key simple-vector))
4028 ;; It's hard to anticipate many speed-critical applications for
4029 ;; sorting vector types other than (VECTOR T), so we just lump
4030 ;; them all together in one slow dynamically typed mess.
4032 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
4033 (%sort-vector (or ,key #'identity))))))
4035 ;;;; debuggers' little helpers
4037 ;;; for debugging when transforms are behaving mysteriously,
4038 ;;; e.g. when debugging a problem with an ASH transform
4039 ;;; (defun foo (&optional s)
4040 ;;; (sb-c::/report-lvar s "S outside WHEN")
4041 ;;; (when (and (integerp s) (> s 3))
4042 ;;; (sb-c::/report-lvar s "S inside WHEN")
4043 ;;; (let ((bound (ash 1 (1- s))))
4044 ;;; (sb-c::/report-lvar bound "BOUND")
4045 ;;; (let ((x (- bound))
4047 ;;; (sb-c::/report-lvar x "X")
4048 ;;; (sb-c::/report-lvar x "Y"))
4049 ;;; `(integer ,(- bound) ,(1- bound)))))
4050 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
4051 ;;; and the function doesn't do anything at all.)
4054 (defknown /report-lvar (t t) null)
4055 (deftransform /report-lvar ((x message) (t t))
4056 (format t "~%/in /REPORT-LVAR~%")
4057 (format t "/(LVAR-TYPE X)=~S~%" (lvar-type x))
4058 (when (constant-lvar-p x)
4059 (format t "/(LVAR-VALUE X)=~S~%" (lvar-value x)))
4060 (format t "/MESSAGE=~S~%" (lvar-value message))
4061 (give-up-ir1-transform "not a real transform"))
4062 (defun /report-lvar (x message)
4063 (declare (ignore x message))))
4066 ;;;; Transforms for internal compiler utilities
4068 ;;; If QUALITY-NAME is constant and a valid name, don't bother
4069 ;;; checking that it's still valid at run-time.
4070 (deftransform policy-quality ((policy quality-name)
4072 (unless (and (constant-lvar-p quality-name)
4073 (policy-quality-name-p (lvar-value quality-name)))
4074 (give-up-ir1-transform))
4075 `(let* ((acons (assoc quality-name policy))
4076 (result (or (cdr acons) 1)))