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))
33 ;;; CONSTANTLY is pretty much never worth transforming, but it's good to get the type.
34 (defoptimizer (constantly derive-type) ((value))
36 `(function (&rest t) (values ,(type-specifier (lvar-type value)) &optional))))
38 ;;; If the function has a known number of arguments, then return a
39 ;;; lambda with the appropriate fixed number of args. If the
40 ;;; destination is a FUNCALL, then do the &REST APPLY thing, and let
41 ;;; MV optimization figure things out.
42 (deftransform complement ((fun) * * :node node)
44 (multiple-value-bind (min max)
45 (fun-type-nargs (lvar-type fun))
47 ((and min (eql min max))
48 (let ((dums (make-gensym-list min)))
49 `#'(lambda ,dums (not (funcall fun ,@dums)))))
50 ((awhen (node-lvar node)
51 (let ((dest (lvar-dest it)))
52 (and (combination-p dest)
53 (eq (combination-fun dest) it))))
54 '#'(lambda (&rest args)
55 (not (apply fun args))))
57 (give-up-ir1-transform
58 "The function doesn't have a fixed argument count.")))))
61 (defun derive-symbol-value-type (lvar node)
62 (if (constant-lvar-p lvar)
63 (let* ((sym (lvar-value lvar))
64 (var (maybe-find-free-var sym))
66 (let ((*lexenv* (node-lexenv node)))
67 (lexenv-find var type-restrictions))))
68 (global-type (info :variable :type sym)))
70 (type-intersection local-type global-type)
74 (defoptimizer (symbol-value derive-type) ((symbol) node)
75 (derive-symbol-value-type symbol node))
77 (defoptimizer (symbol-global-value derive-type) ((symbol) node)
78 (derive-symbol-value-type symbol node))
82 ;;; Translate CxR into CAR/CDR combos.
83 (defun source-transform-cxr (form)
84 (if (/= (length form) 2)
86 (let* ((name (car form))
90 (leaf (leaf-source-name name))))))
91 (do ((i (- (length string) 2) (1- i))
93 `(,(ecase (char string i)
99 ;;; Make source transforms to turn CxR forms into combinations of CAR
100 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
102 (/show0 "about to set CxR source transforms")
103 (loop for i of-type index from 2 upto 4 do
104 ;; Iterate over BUF = all names CxR where x = an I-element
105 ;; string of #\A or #\D characters.
106 (let ((buf (make-string (+ 2 i))))
107 (setf (aref buf 0) #\C
108 (aref buf (1+ i)) #\R)
109 (dotimes (j (ash 2 i))
110 (declare (type index j))
112 (declare (type index k))
113 (setf (aref buf (1+ k))
114 (if (logbitp k j) #\A #\D)))
115 (setf (info :function :source-transform (intern buf))
116 #'source-transform-cxr))))
117 (/show0 "done setting CxR source transforms")
119 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
120 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
121 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
123 (define-source-transform first (x) `(car ,x))
124 (define-source-transform rest (x) `(cdr ,x))
125 (define-source-transform second (x) `(cadr ,x))
126 (define-source-transform third (x) `(caddr ,x))
127 (define-source-transform fourth (x) `(cadddr ,x))
128 (define-source-transform fifth (x) `(nth 4 ,x))
129 (define-source-transform sixth (x) `(nth 5 ,x))
130 (define-source-transform seventh (x) `(nth 6 ,x))
131 (define-source-transform eighth (x) `(nth 7 ,x))
132 (define-source-transform ninth (x) `(nth 8 ,x))
133 (define-source-transform tenth (x) `(nth 9 ,x))
135 ;;; LIST with one arg is an extremely common operation (at least inside
136 ;;; SBCL itself); translate it to CONS to take advantage of common
137 ;;; allocation routines.
138 (define-source-transform list (&rest args)
140 (1 `(cons ,(first args) nil))
143 ;;; And similarly for LIST*.
144 (define-source-transform list* (arg &rest others)
145 (cond ((not others) arg)
146 ((not (cdr others)) `(cons ,arg ,(car others)))
149 (defoptimizer (list* derive-type) ((arg &rest args))
151 (specifier-type 'cons)
154 ;;; Translate RPLACx to LET and SETF.
155 (define-source-transform rplaca (x y)
160 (define-source-transform rplacd (x y)
166 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
168 (deftransform last ((list &optional n) (t &optional t))
169 (let ((c (constant-lvar-p n)))
171 (and c (eql 1 (lvar-value n))))
173 ((and c (eql 0 (lvar-value n)))
176 (let ((type (lvar-type n)))
177 (cond ((csubtypep type (specifier-type 'fixnum))
178 '(%lastn/fixnum list n))
179 ((csubtypep type (specifier-type 'bignum))
180 '(%lastn/bignum list n))
182 (give-up-ir1-transform "second argument type too vague"))))))))
184 (define-source-transform gethash (&rest args)
186 (2 `(sb!impl::gethash3 ,@args nil))
187 (3 `(sb!impl::gethash3 ,@args))
189 (define-source-transform get (&rest args)
191 (2 `(sb!impl::get2 ,@args))
192 (3 `(sb!impl::get3 ,@args))
195 (defvar *default-nthcdr-open-code-limit* 6)
196 (defvar *extreme-nthcdr-open-code-limit* 20)
198 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
199 "convert NTHCDR to CAxxR"
200 (unless (constant-lvar-p n)
201 (give-up-ir1-transform))
202 (let ((n (lvar-value n)))
204 (if (policy node (and (= speed 3) (= space 0)))
205 *extreme-nthcdr-open-code-limit*
206 *default-nthcdr-open-code-limit*))
207 (give-up-ir1-transform))
212 `(cdr ,(frob (1- n))))))
215 ;;;; arithmetic and numerology
217 (define-source-transform plusp (x) `(> ,x 0))
218 (define-source-transform minusp (x) `(< ,x 0))
219 (define-source-transform zerop (x) `(= ,x 0))
221 (define-source-transform 1+ (x) `(+ ,x 1))
222 (define-source-transform 1- (x) `(- ,x 1))
224 (define-source-transform oddp (x) `(logtest ,x 1))
225 (define-source-transform evenp (x) `(not (logtest ,x 1)))
227 ;;; Note that all the integer division functions are available for
228 ;;; inline expansion.
230 (macrolet ((deffrob (fun)
231 `(define-source-transform ,fun (x &optional (y nil y-p))
238 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
240 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
243 ;;; This used to be a source transform (hence the lack of restrictions
244 ;;; on the argument types), but we make it a regular transform so that
245 ;;; the VM has a chance to see the bare LOGTEST and potentiall choose
246 ;;; to implement it differently. --njf, 06-02-2006
247 (deftransform logtest ((x y) * *)
248 `(not (zerop (logand x y))))
250 (deftransform logbitp
251 ((index integer) (unsigned-byte (or (signed-byte #.sb!vm:n-word-bits)
252 (unsigned-byte #.sb!vm:n-word-bits))))
253 `(if (>= index #.sb!vm:n-word-bits)
255 (not (zerop (logand integer (ash 1 index))))))
257 (define-source-transform byte (size position)
258 `(cons ,size ,position))
259 (define-source-transform byte-size (spec) `(car ,spec))
260 (define-source-transform byte-position (spec) `(cdr ,spec))
261 (define-source-transform ldb-test (bytespec integer)
262 `(not (zerop (mask-field ,bytespec ,integer))))
264 ;;; With the ratio and complex accessors, we pick off the "identity"
265 ;;; case, and use a primitive to handle the cell access case.
266 (define-source-transform numerator (num)
267 (once-only ((n-num `(the rational ,num)))
271 (define-source-transform denominator (num)
272 (once-only ((n-num `(the rational ,num)))
274 (%denominator ,n-num)
277 ;;;; interval arithmetic for computing bounds
279 ;;;; This is a set of routines for operating on intervals. It
280 ;;;; implements a simple interval arithmetic package. Although SBCL
281 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
282 ;;;; for two reasons:
284 ;;;; 1. This package is simpler than NUMERIC-TYPE.
286 ;;;; 2. It makes debugging much easier because you can just strip
287 ;;;; out these routines and test them independently of SBCL. (This is a
290 ;;;; One disadvantage is a probable increase in consing because we
291 ;;;; have to create these new interval structures even though
292 ;;;; numeric-type has everything we want to know. Reason 2 wins for
295 ;;; Support operations that mimic real arithmetic comparison
296 ;;; operators, but imposing a total order on the floating points such
297 ;;; that negative zeros are strictly less than positive zeros.
298 (macrolet ((def (name op)
301 (if (and (floatp x) (floatp y) (zerop x) (zerop y))
302 (,op (float-sign x) (float-sign y))
304 (def signed-zero->= >=)
305 (def signed-zero-> >)
306 (def signed-zero-= =)
307 (def signed-zero-< <)
308 (def signed-zero-<= <=))
310 ;;; The basic interval type. It can handle open and closed intervals.
311 ;;; A bound is open if it is a list containing a number, just like
312 ;;; Lisp says. NIL means unbounded.
313 (defstruct (interval (:constructor %make-interval)
317 (defun make-interval (&key low high)
318 (labels ((normalize-bound (val)
321 (float-infinity-p val))
322 ;; Handle infinities.
326 ;; Handle any closed bounds.
329 ;; We have an open bound. Normalize the numeric
330 ;; bound. If the normalized bound is still a number
331 ;; (not nil), keep the bound open. Otherwise, the
332 ;; bound is really unbounded, so drop the openness.
333 (let ((new-val (normalize-bound (first val))))
335 ;; The bound exists, so keep it open still.
338 (error "unknown bound type in MAKE-INTERVAL")))))
339 (%make-interval :low (normalize-bound low)
340 :high (normalize-bound high))))
342 ;;; Given a number X, create a form suitable as a bound for an
343 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
344 #!-sb-fluid (declaim (inline set-bound))
345 (defun set-bound (x open-p)
346 (if (and x open-p) (list x) x))
348 ;;; Apply the function F to a bound X. If X is an open bound, then
349 ;;; the result will be open. IF X is NIL, the result is NIL.
350 (defun bound-func (f x)
351 (declare (type function f))
354 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
355 ;; With these traps masked, we might get things like infinity
356 ;; or negative infinity returned. Check for this and return
357 ;; NIL to indicate unbounded.
358 (let ((y (funcall f (type-bound-number x))))
360 (float-infinity-p y))
362 (set-bound y (consp x)))))
363 ;; Some numerical operations will signal SIMPLE-TYPE-ERROR, e.g.
364 ;; in the course of converting a bignum to a float. Default to
366 (simple-type-error ()))))
368 (defun safe-double-coercion-p (x)
369 (or (typep x 'double-float)
370 (<= most-negative-double-float x most-positive-double-float)))
372 (defun safe-single-coercion-p (x)
373 (or (typep x 'single-float)
375 ;; Fix for bug 420, and related issues: during type derivation we often
376 ;; end up deriving types for both
378 ;; (some-op <int> <single>)
380 ;; (some-op (coerce <int> 'single-float) <single>)
382 ;; or other equivalent transformed forms. The problem with this
383 ;; is that on x86 (+ <int> <single>) is on the machine level
386 ;; (coerce (+ (coerce <int> 'double-float)
387 ;; (coerce <single> 'double-float))
390 ;; so if the result of (coerce <int> 'single-float) is not exact, the
391 ;; derived types for the transformed forms will have an empty
392 ;; intersection -- which in turn means that the compiler will conclude
393 ;; that the call never returns, and all hell breaks lose when it *does*
394 ;; return at runtime. (This affects not just +, but other operators are
397 ;; See also: SAFE-CTYPE-FOR-SINGLE-COERCION-P
399 ;; FIXME: If we ever add SSE-support for x86, this conditional needs to
402 (not (typep x `(or (integer * (,most-negative-exactly-single-float-fixnum))
403 (integer (,most-positive-exactly-single-float-fixnum) *))))
404 (<= most-negative-single-float x most-positive-single-float))))
406 ;;; Apply a binary operator OP to two bounds X and Y. The result is
407 ;;; NIL if either is NIL. Otherwise bound is computed and the result
408 ;;; is open if either X or Y is open.
410 ;;; FIXME: only used in this file, not needed in target runtime
412 ;;; ANSI contaigon specifies coercion to floating point if one of the
413 ;;; arguments is floating point. Here we should check to be sure that
414 ;;; the other argument is within the bounds of that floating point
417 (defmacro safely-binop (op x y)
419 ((typep ,x 'double-float)
420 (when (safe-double-coercion-p ,y)
422 ((typep ,y 'double-float)
423 (when (safe-double-coercion-p ,x)
425 ((typep ,x 'single-float)
426 (when (safe-single-coercion-p ,y)
428 ((typep ,y 'single-float)
429 (when (safe-single-coercion-p ,x)
433 (defmacro bound-binop (op x y)
434 (with-unique-names (xb yb res)
436 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
437 (let* ((,xb (type-bound-number ,x))
438 (,yb (type-bound-number ,y))
439 (,res (safely-binop ,op ,xb ,yb)))
441 (and (or (consp ,x) (consp ,y))
442 ;; Open bounds can very easily be messed up
443 ;; by FP rounding, so take care here.
446 ;; Multiplying a greater-than-zero with
447 ;; less than one can round to zero.
448 `(or (not (fp-zero-p ,res))
449 (cond ((and (consp ,x) (fp-zero-p ,xb))
451 ((and (consp ,y) (fp-zero-p ,yb))
454 ;; Dividing a greater-than-zero with
455 ;; greater than one can round to zero.
456 `(or (not (fp-zero-p ,res))
457 (cond ((and (consp ,x) (fp-zero-p ,xb))
459 ((and (consp ,y) (fp-zero-p ,yb))
462 ;; Adding or subtracting greater-than-zero
463 ;; can end up with identity.
464 `(and (not (fp-zero-p ,xb))
465 (not (fp-zero-p ,yb))))))))))))
467 (defun coerce-for-bound (val type)
469 (list (coerce-for-bound (car val) type))
471 ((subtypep type 'double-float)
472 (if (<= most-negative-double-float val most-positive-double-float)
474 ((or (subtypep type 'single-float) (subtypep type 'float))
475 ;; coerce to float returns a single-float
476 (if (<= most-negative-single-float val most-positive-single-float)
478 (t (coerce val type)))))
480 (defun coerce-and-truncate-floats (val type)
483 (list (coerce-and-truncate-floats (car val) type))
485 ((subtypep type 'double-float)
486 (if (<= most-negative-double-float val most-positive-double-float)
488 (if (< val most-negative-double-float)
489 most-negative-double-float most-positive-double-float)))
490 ((or (subtypep type 'single-float) (subtypep type 'float))
491 ;; coerce to float returns a single-float
492 (if (<= most-negative-single-float val most-positive-single-float)
494 (if (< val most-negative-single-float)
495 most-negative-single-float most-positive-single-float)))
496 (t (coerce val type))))))
498 ;;; Convert a numeric-type object to an interval object.
499 (defun numeric-type->interval (x)
500 (declare (type numeric-type x))
501 (make-interval :low (numeric-type-low x)
502 :high (numeric-type-high x)))
504 (defun type-approximate-interval (type)
505 (declare (type ctype type))
506 (let ((types (prepare-arg-for-derive-type type))
509 (let ((type (if (member-type-p type)
510 (convert-member-type type)
512 (unless (numeric-type-p type)
513 (return-from type-approximate-interval nil))
514 (let ((interval (numeric-type->interval type)))
517 (interval-approximate-union result interval)
521 (defun copy-interval-limit (limit)
526 (defun copy-interval (x)
527 (declare (type interval x))
528 (make-interval :low (copy-interval-limit (interval-low x))
529 :high (copy-interval-limit (interval-high x))))
531 ;;; Given a point P contained in the interval X, split X into two
532 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
533 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
534 ;;; contains P. You can specify both to be T or NIL.
535 (defun interval-split (p x &optional close-lower close-upper)
536 (declare (type number p)
538 (list (make-interval :low (copy-interval-limit (interval-low x))
539 :high (if close-lower p (list p)))
540 (make-interval :low (if close-upper (list p) p)
541 :high (copy-interval-limit (interval-high x)))))
543 ;;; Return the closure of the interval. That is, convert open bounds
544 ;;; to closed bounds.
545 (defun interval-closure (x)
546 (declare (type interval x))
547 (make-interval :low (type-bound-number (interval-low x))
548 :high (type-bound-number (interval-high x))))
550 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
551 ;;; '-. Otherwise return NIL.
552 (defun interval-range-info (x &optional (point 0))
553 (declare (type interval x))
554 (let ((lo (interval-low x))
555 (hi (interval-high x)))
556 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
558 ((and hi (signed-zero->= point (type-bound-number hi)))
563 ;;; Test to see whether the interval X is bounded. HOW determines the
564 ;;; test, and should be either ABOVE, BELOW, or BOTH.
565 (defun interval-bounded-p (x how)
566 (declare (type interval x))
573 (and (interval-low x) (interval-high x)))))
575 ;;; See whether the interval X contains the number P, taking into
576 ;;; account that the interval might not be closed.
577 (defun interval-contains-p (p x)
578 (declare (type number p)
580 ;; Does the interval X contain the number P? This would be a lot
581 ;; easier if all intervals were closed!
582 (let ((lo (interval-low x))
583 (hi (interval-high x)))
585 ;; The interval is bounded
586 (if (and (signed-zero-<= (type-bound-number lo) p)
587 (signed-zero-<= p (type-bound-number hi)))
588 ;; P is definitely in the closure of the interval.
589 ;; We just need to check the end points now.
590 (cond ((signed-zero-= p (type-bound-number lo))
592 ((signed-zero-= p (type-bound-number hi))
597 ;; Interval with upper bound
598 (if (signed-zero-< p (type-bound-number hi))
600 (and (numberp hi) (signed-zero-= p hi))))
602 ;; Interval with lower bound
603 (if (signed-zero-> p (type-bound-number lo))
605 (and (numberp lo) (signed-zero-= p lo))))
607 ;; Interval with no bounds
610 ;;; Determine whether two intervals X and Y intersect. Return T if so.
611 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
612 ;;; were closed. Otherwise the intervals are treated as they are.
614 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
615 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
616 ;;; is T, then they do intersect because we use the closure of X = [0,
617 ;;; 1] and Y = [1, 2] to determine intersection.
618 (defun interval-intersect-p (x y &optional closed-intervals-p)
619 (declare (type interval x y))
620 (and (interval-intersection/difference (if closed-intervals-p
623 (if closed-intervals-p
628 ;;; Are the two intervals adjacent? That is, is there a number
629 ;;; between the two intervals that is not an element of either
630 ;;; interval? If so, they are not adjacent. For example [0, 1) and
631 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
632 ;;; between both intervals.
633 (defun interval-adjacent-p (x y)
634 (declare (type interval x y))
635 (flet ((adjacent (lo hi)
636 ;; Check to see whether lo and hi are adjacent. If either is
637 ;; nil, they can't be adjacent.
638 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
639 ;; The bounds are equal. They are adjacent if one of
640 ;; them is closed (a number). If both are open (consp),
641 ;; then there is a number that lies between them.
642 (or (numberp lo) (numberp hi)))))
643 (or (adjacent (interval-low y) (interval-high x))
644 (adjacent (interval-low x) (interval-high y)))))
646 ;;; Compute the intersection and difference between two intervals.
647 ;;; Two values are returned: the intersection and the difference.
649 ;;; Let the two intervals be X and Y, and let I and D be the two
650 ;;; values returned by this function. Then I = X intersect Y. If I
651 ;;; is NIL (the empty set), then D is X union Y, represented as the
652 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
653 ;;; - I, which is a list of two intervals.
655 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
656 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
657 (defun interval-intersection/difference (x y)
658 (declare (type interval x y))
659 (let ((x-lo (interval-low x))
660 (x-hi (interval-high x))
661 (y-lo (interval-low y))
662 (y-hi (interval-high y)))
665 ;; If p is an open bound, make it closed. If p is a closed
666 ;; bound, make it open.
670 (test-number (p int bound)
671 ;; Test whether P is in the interval.
672 (let ((pn (type-bound-number p)))
673 (when (interval-contains-p pn (interval-closure int))
674 ;; Check for endpoints.
675 (let* ((lo (interval-low int))
676 (hi (interval-high int))
677 (lon (type-bound-number lo))
678 (hin (type-bound-number hi)))
680 ;; Interval may be a point.
681 ((and lon hin (= lon hin pn))
682 (and (numberp p) (numberp lo) (numberp hi)))
683 ;; Point matches the low end.
684 ;; [P] [P,?} => TRUE [P] (P,?} => FALSE
685 ;; (P [P,?} => TRUE P) [P,?} => FALSE
686 ;; (P (P,?} => TRUE P) (P,?} => FALSE
687 ((and lon (= pn lon))
688 (or (and (numberp p) (numberp lo))
689 (and (consp p) (eq :low bound))))
690 ;; [P] {?,P] => TRUE [P] {?,P) => FALSE
691 ;; P) {?,P] => TRUE (P {?,P] => FALSE
692 ;; P) {?,P) => TRUE (P {?,P) => FALSE
693 ((and hin (= pn hin))
694 (or (and (numberp p) (numberp hi))
695 (and (consp p) (eq :high bound))))
696 ;; Not an endpoint, all is well.
699 (test-lower-bound (p int)
700 ;; P is a lower bound of an interval.
702 (test-number p int :low)
703 (not (interval-bounded-p int 'below))))
704 (test-upper-bound (p int)
705 ;; P is an upper bound of an interval.
707 (test-number p int :high)
708 (not (interval-bounded-p int 'above)))))
709 (let ((x-lo-in-y (test-lower-bound x-lo y))
710 (x-hi-in-y (test-upper-bound x-hi y))
711 (y-lo-in-x (test-lower-bound y-lo x))
712 (y-hi-in-x (test-upper-bound y-hi x)))
713 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
714 ;; Intervals intersect. Let's compute the intersection
715 ;; and the difference.
716 (multiple-value-bind (lo left-lo left-hi)
717 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
718 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
719 (multiple-value-bind (hi right-lo right-hi)
721 (values x-hi (opposite-bound x-hi) y-hi))
723 (values y-hi (opposite-bound y-hi) x-hi)))
724 (values (make-interval :low lo :high hi)
725 (list (make-interval :low left-lo
727 (make-interval :low right-lo
730 (values nil (list x y))))))))
732 ;;; If intervals X and Y intersect, return a new interval that is the
733 ;;; union of the two. If they do not intersect, return NIL.
734 (defun interval-merge-pair (x y)
735 (declare (type interval x y))
736 ;; If x and y intersect or are adjacent, create the union.
737 ;; Otherwise return nil
738 (when (or (interval-intersect-p x y)
739 (interval-adjacent-p x y))
740 (flet ((select-bound (x1 x2 min-op max-op)
741 (let ((x1-val (type-bound-number x1))
742 (x2-val (type-bound-number x2)))
744 ;; Both bounds are finite. Select the right one.
745 (cond ((funcall min-op x1-val x2-val)
746 ;; x1 is definitely better.
748 ((funcall max-op x1-val x2-val)
749 ;; x2 is definitely better.
752 ;; Bounds are equal. Select either
753 ;; value and make it open only if
755 (set-bound x1-val (and (consp x1) (consp x2))))))
757 ;; At least one bound is not finite. The
758 ;; non-finite bound always wins.
760 (let* ((x-lo (copy-interval-limit (interval-low x)))
761 (x-hi (copy-interval-limit (interval-high x)))
762 (y-lo (copy-interval-limit (interval-low y)))
763 (y-hi (copy-interval-limit (interval-high y))))
764 (make-interval :low (select-bound x-lo y-lo #'< #'>)
765 :high (select-bound x-hi y-hi #'> #'<))))))
767 ;;; return the minimal interval, containing X and Y
768 (defun interval-approximate-union (x y)
769 (cond ((interval-merge-pair x y))
771 (make-interval :low (copy-interval-limit (interval-low x))
772 :high (copy-interval-limit (interval-high y))))
774 (make-interval :low (copy-interval-limit (interval-low y))
775 :high (copy-interval-limit (interval-high x))))))
777 ;;; basic arithmetic operations on intervals. We probably should do
778 ;;; true interval arithmetic here, but it's complicated because we
779 ;;; have float and integer types and bounds can be open or closed.
781 ;;; the negative of an interval
782 (defun interval-neg (x)
783 (declare (type interval x))
784 (make-interval :low (bound-func #'- (interval-high x))
785 :high (bound-func #'- (interval-low x))))
787 ;;; Add two intervals.
788 (defun interval-add (x y)
789 (declare (type interval x y))
790 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
791 :high (bound-binop + (interval-high x) (interval-high y))))
793 ;;; Subtract two intervals.
794 (defun interval-sub (x y)
795 (declare (type interval x y))
796 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
797 :high (bound-binop - (interval-high x) (interval-low y))))
799 ;;; Multiply two intervals.
800 (defun interval-mul (x y)
801 (declare (type interval x y))
802 (flet ((bound-mul (x y)
803 (cond ((or (null x) (null y))
804 ;; Multiply by infinity is infinity
806 ((or (and (numberp x) (zerop x))
807 (and (numberp y) (zerop y)))
808 ;; Multiply by closed zero is special. The result
809 ;; is always a closed bound. But don't replace this
810 ;; with zero; we want the multiplication to produce
811 ;; the correct signed zero, if needed. Use SIGNUM
812 ;; to avoid trying to multiply huge bignums with 0.0.
813 (* (signum (type-bound-number x)) (signum (type-bound-number y))))
814 ((or (and (floatp x) (float-infinity-p x))
815 (and (floatp y) (float-infinity-p y)))
816 ;; Infinity times anything is infinity
819 ;; General multiply. The result is open if either is open.
820 (bound-binop * x y)))))
821 (let ((x-range (interval-range-info x))
822 (y-range (interval-range-info y)))
823 (cond ((null x-range)
824 ;; Split x into two and multiply each separately
825 (destructuring-bind (x- x+) (interval-split 0 x t t)
826 (interval-merge-pair (interval-mul x- y)
827 (interval-mul x+ y))))
829 ;; Split y into two and multiply each separately
830 (destructuring-bind (y- y+) (interval-split 0 y t t)
831 (interval-merge-pair (interval-mul x y-)
832 (interval-mul x y+))))
834 (interval-neg (interval-mul (interval-neg x) y)))
836 (interval-neg (interval-mul x (interval-neg y))))
837 ((and (eq x-range '+) (eq y-range '+))
838 ;; If we are here, X and Y are both positive.
840 :low (bound-mul (interval-low x) (interval-low y))
841 :high (bound-mul (interval-high x) (interval-high y))))
843 (bug "excluded case in INTERVAL-MUL"))))))
845 ;;; Divide two intervals.
846 (defun interval-div (top bot)
847 (declare (type interval top bot))
848 (flet ((bound-div (x y y-low-p)
851 ;; Divide by infinity means result is 0. However,
852 ;; we need to watch out for the sign of the result,
853 ;; to correctly handle signed zeros. We also need
854 ;; to watch out for positive or negative infinity.
855 (if (floatp (type-bound-number x))
857 (- (float-sign (type-bound-number x) 0.0))
858 (float-sign (type-bound-number x) 0.0))
860 ((zerop (type-bound-number y))
861 ;; Divide by zero means result is infinity
864 (bound-binop / x y)))))
865 (let ((top-range (interval-range-info top))
866 (bot-range (interval-range-info bot)))
867 (cond ((null bot-range)
868 ;; The denominator contains zero, so anything goes!
869 (make-interval :low nil :high nil))
871 ;; Denominator is negative so flip the sign, compute the
872 ;; result, and flip it back.
873 (interval-neg (interval-div top (interval-neg bot))))
875 ;; Split top into two positive and negative parts, and
876 ;; divide each separately
877 (destructuring-bind (top- top+) (interval-split 0 top t t)
878 (interval-merge-pair (interval-div top- bot)
879 (interval-div top+ bot))))
881 ;; Top is negative so flip the sign, divide, and flip the
882 ;; sign of the result.
883 (interval-neg (interval-div (interval-neg top) bot)))
884 ((and (eq top-range '+) (eq bot-range '+))
887 :low (bound-div (interval-low top) (interval-high bot) t)
888 :high (bound-div (interval-high top) (interval-low bot) nil)))
890 (bug "excluded case in INTERVAL-DIV"))))))
892 ;;; Apply the function F to the interval X. If X = [a, b], then the
893 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
894 ;;; result makes sense. It will if F is monotonic increasing (or
896 (defun interval-func (f x)
897 (declare (type function f)
899 (let ((lo (bound-func f (interval-low x)))
900 (hi (bound-func f (interval-high x))))
901 (make-interval :low lo :high hi)))
903 ;;; Return T if X < Y. That is every number in the interval X is
904 ;;; always less than any number in the interval Y.
905 (defun interval-< (x y)
906 (declare (type interval x y))
907 ;; X < Y only if X is bounded above, Y is bounded below, and they
909 (when (and (interval-bounded-p x 'above)
910 (interval-bounded-p y 'below))
911 ;; Intervals are bounded in the appropriate way. Make sure they
913 (let ((left (interval-high x))
914 (right (interval-low y)))
915 (cond ((> (type-bound-number left)
916 (type-bound-number right))
917 ;; The intervals definitely overlap, so result is NIL.
919 ((< (type-bound-number left)
920 (type-bound-number right))
921 ;; The intervals definitely don't touch, so result is T.
924 ;; Limits are equal. Check for open or closed bounds.
925 ;; Don't overlap if one or the other are open.
926 (or (consp left) (consp right)))))))
928 ;;; Return T if X >= Y. That is, every number in the interval X is
929 ;;; always greater than any number in the interval Y.
930 (defun interval->= (x y)
931 (declare (type interval x y))
932 ;; X >= Y if lower bound of X >= upper bound of Y
933 (when (and (interval-bounded-p x 'below)
934 (interval-bounded-p y 'above))
935 (>= (type-bound-number (interval-low x))
936 (type-bound-number (interval-high y)))))
938 ;;; Return T if X = Y.
939 (defun interval-= (x y)
940 (declare (type interval x y))
941 (and (interval-bounded-p x 'both)
942 (interval-bounded-p y 'both)
946 ;; Open intervals cannot be =
947 (return-from interval-= nil))))
948 ;; Both intervals refer to the same point
949 (= (bound (interval-high x)) (bound (interval-low x))
950 (bound (interval-high y)) (bound (interval-low y))))))
952 ;;; Return T if X /= Y
953 (defun interval-/= (x y)
954 (not (interval-intersect-p x y)))
956 ;;; Return an interval that is the absolute value of X. Thus, if
957 ;;; X = [-1 10], the result is [0, 10].
958 (defun interval-abs (x)
959 (declare (type interval x))
960 (case (interval-range-info x)
966 (destructuring-bind (x- x+) (interval-split 0 x t t)
967 (interval-merge-pair (interval-neg x-) x+)))))
969 ;;; Compute the square of an interval.
970 (defun interval-sqr (x)
971 (declare (type interval x))
972 (interval-func (lambda (x) (* x x))
975 ;;;; numeric DERIVE-TYPE methods
977 ;;; a utility for defining derive-type methods of integer operations. If
978 ;;; the types of both X and Y are integer types, then we compute a new
979 ;;; integer type with bounds determined Fun when applied to X and Y.
980 ;;; Otherwise, we use NUMERIC-CONTAGION.
981 (defun derive-integer-type-aux (x y fun)
982 (declare (type function fun))
983 (if (and (numeric-type-p x) (numeric-type-p y)
984 (eq (numeric-type-class x) 'integer)
985 (eq (numeric-type-class y) 'integer)
986 (eq (numeric-type-complexp x) :real)
987 (eq (numeric-type-complexp y) :real))
988 (multiple-value-bind (low high) (funcall fun x y)
989 (make-numeric-type :class 'integer
993 (numeric-contagion x y)))
995 (defun derive-integer-type (x y fun)
996 (declare (type lvar x y) (type function fun))
997 (let ((x (lvar-type x))
999 (derive-integer-type-aux x y fun)))
1001 ;;; simple utility to flatten a list
1002 (defun flatten-list (x)
1003 (labels ((flatten-and-append (tree list)
1004 (cond ((null tree) list)
1005 ((atom tree) (cons tree list))
1006 (t (flatten-and-append
1007 (car tree) (flatten-and-append (cdr tree) list))))))
1008 (flatten-and-append x nil)))
1010 ;;; Take some type of lvar and massage it so that we get a list of the
1011 ;;; constituent types. If ARG is *EMPTY-TYPE*, return NIL to indicate
1013 (defun prepare-arg-for-derive-type (arg)
1014 (flet ((listify (arg)
1019 (union-type-types arg))
1022 (unless (eq arg *empty-type*)
1023 ;; Make sure all args are some type of numeric-type. For member
1024 ;; types, convert the list of members into a union of equivalent
1025 ;; single-element member-type's.
1026 (let ((new-args nil))
1027 (dolist (arg (listify arg))
1028 (if (member-type-p arg)
1029 ;; Run down the list of members and convert to a list of
1031 (mapc-member-type-members
1033 (push (if (numberp member)
1034 (make-member-type :members (list member))
1038 (push arg new-args)))
1039 (unless (member *empty-type* new-args)
1042 ;;; Convert from the standard type convention for which -0.0 and 0.0
1043 ;;; are equal to an intermediate convention for which they are
1044 ;;; considered different which is more natural for some of the
1046 (defun convert-numeric-type (type)
1047 (declare (type numeric-type type))
1048 ;;; Only convert real float interval delimiters types.
1049 (if (eq (numeric-type-complexp type) :real)
1050 (let* ((lo (numeric-type-low type))
1051 (lo-val (type-bound-number lo))
1052 (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
1053 (hi (numeric-type-high type))
1054 (hi-val (type-bound-number hi))
1055 (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
1056 (if (or lo-float-zero-p hi-float-zero-p)
1058 :class (numeric-type-class type)
1059 :format (numeric-type-format type)
1061 :low (if lo-float-zero-p
1063 (list (float 0.0 lo-val))
1064 (float (load-time-value (make-unportable-float :single-float-negative-zero)) lo-val))
1066 :high (if hi-float-zero-p
1068 (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val))
1075 ;;; Convert back from the intermediate convention for which -0.0 and
1076 ;;; 0.0 are considered different to the standard type convention for
1077 ;;; which and equal.
1078 (defun convert-back-numeric-type (type)
1079 (declare (type numeric-type type))
1080 ;;; Only convert real float interval delimiters types.
1081 (if (eq (numeric-type-complexp type) :real)
1082 (let* ((lo (numeric-type-low type))
1083 (lo-val (type-bound-number lo))
1085 (and lo (floatp lo-val) (= lo-val 0.0)
1086 (float-sign lo-val)))
1087 (hi (numeric-type-high type))
1088 (hi-val (type-bound-number hi))
1090 (and hi (floatp hi-val) (= hi-val 0.0)
1091 (float-sign hi-val))))
1093 ;; (float +0.0 +0.0) => (member 0.0)
1094 ;; (float -0.0 -0.0) => (member -0.0)
1095 ((and lo-float-zero-p hi-float-zero-p)
1096 ;; shouldn't have exclusive bounds here..
1097 (aver (and (not (consp lo)) (not (consp hi))))
1098 (if (= lo-float-zero-p hi-float-zero-p)
1099 ;; (float +0.0 +0.0) => (member 0.0)
1100 ;; (float -0.0 -0.0) => (member -0.0)
1101 (specifier-type `(member ,lo-val))
1102 ;; (float -0.0 +0.0) => (float 0.0 0.0)
1103 ;; (float +0.0 -0.0) => (float 0.0 0.0)
1104 (make-numeric-type :class (numeric-type-class type)
1105 :format (numeric-type-format type)
1111 ;; (float -0.0 x) => (float 0.0 x)
1112 ((and (not (consp lo)) (minusp lo-float-zero-p))
1113 (make-numeric-type :class (numeric-type-class type)
1114 :format (numeric-type-format type)
1116 :low (float 0.0 lo-val)
1118 ;; (float (+0.0) x) => (float (0.0) x)
1119 ((and (consp lo) (plusp lo-float-zero-p))
1120 (make-numeric-type :class (numeric-type-class type)
1121 :format (numeric-type-format type)
1123 :low (list (float 0.0 lo-val))
1126 ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
1127 ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
1128 (list (make-member-type :members (list (float 0.0 lo-val)))
1129 (make-numeric-type :class (numeric-type-class type)
1130 :format (numeric-type-format type)
1132 :low (list (float 0.0 lo-val))
1136 ;; (float x +0.0) => (float x 0.0)
1137 ((and (not (consp hi)) (plusp hi-float-zero-p))
1138 (make-numeric-type :class (numeric-type-class type)
1139 :format (numeric-type-format type)
1142 :high (float 0.0 hi-val)))
1143 ;; (float x (-0.0)) => (float x (0.0))
1144 ((and (consp hi) (minusp hi-float-zero-p))
1145 (make-numeric-type :class (numeric-type-class type)
1146 :format (numeric-type-format type)
1149 :high (list (float 0.0 hi-val))))
1151 ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
1152 ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
1153 (list (make-member-type :members (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val)))
1154 (make-numeric-type :class (numeric-type-class type)
1155 :format (numeric-type-format type)
1158 :high (list (float 0.0 hi-val)))))))
1164 ;;; Convert back a possible list of numeric types.
1165 (defun convert-back-numeric-type-list (type-list)
1168 (let ((results '()))
1169 (dolist (type type-list)
1170 (if (numeric-type-p type)
1171 (let ((result (convert-back-numeric-type type)))
1173 (setf results (append results result))
1174 (push result results)))
1175 (push type results)))
1178 (convert-back-numeric-type type-list))
1180 (convert-back-numeric-type-list (union-type-types type-list)))
1184 ;;; Take a list of types and return a canonical type specifier,
1185 ;;; combining any MEMBER types together. If both positive and negative
1186 ;;; MEMBER types are present they are converted to a float type.
1187 ;;; XXX This would be far simpler if the type-union methods could handle
1188 ;;; member/number unions.
1190 ;;; If we're about to generate an overly complex union of numeric types, start
1191 ;;; collapse the ranges together.
1193 ;;; FIXME: The MEMBER canonicalization parts of MAKE-DERIVED-UNION-TYPE and
1194 ;;; entire CONVERT-MEMBER-TYPE probably belong in the kernel's type logic,
1195 ;;; invoked always, instead of in the compiler, invoked only during some type
1197 (defvar *derived-numeric-union-complexity-limit* 6)
1199 (defun make-derived-union-type (type-list)
1200 (let ((xset (alloc-xset))
1203 (numeric-type *empty-type*))
1204 (dolist (type type-list)
1205 (cond ((member-type-p type)
1206 (mapc-member-type-members
1208 (if (fp-zero-p member)
1209 (unless (member member fp-zeroes)
1210 (pushnew member fp-zeroes))
1211 (add-to-xset member xset)))
1213 ((numeric-type-p type)
1214 (let ((*approximate-numeric-unions*
1215 (when (and (union-type-p numeric-type)
1216 (nthcdr *derived-numeric-union-complexity-limit*
1217 (union-type-types numeric-type)))
1219 (setf numeric-type (type-union type numeric-type))))
1221 (push type misc-types))))
1222 (if (and (xset-empty-p xset) (not fp-zeroes))
1223 (apply #'type-union numeric-type misc-types)
1224 (apply #'type-union (make-member-type :xset xset :fp-zeroes fp-zeroes)
1225 numeric-type misc-types))))
1227 ;;; Convert a member type with a single member to a numeric type.
1228 (defun convert-member-type (arg)
1229 (let* ((members (member-type-members arg))
1230 (member (first members))
1231 (member-type (type-of member)))
1232 (aver (not (rest members)))
1233 (specifier-type (cond ((typep member 'integer)
1234 `(integer ,member ,member))
1235 ((memq member-type '(short-float single-float
1236 double-float long-float))
1237 `(,member-type ,member ,member))
1241 ;;; This is used in defoptimizers for computing the resulting type of
1244 ;;; Given the lvar ARG, derive the resulting type using the
1245 ;;; DERIVE-FUN. DERIVE-FUN takes exactly one argument which is some
1246 ;;; "atomic" lvar type like numeric-type or member-type (containing
1247 ;;; just one element). It should return the resulting type, which can
1248 ;;; be a list of types.
1250 ;;; For the case of member types, if a MEMBER-FUN is given it is
1251 ;;; called to compute the result otherwise the member type is first
1252 ;;; converted to a numeric type and the DERIVE-FUN is called.
1253 (defun one-arg-derive-type (arg derive-fun member-fun
1254 &optional (convert-type t))
1255 (declare (type function derive-fun)
1256 (type (or null function) member-fun))
1257 (let ((arg-list (prepare-arg-for-derive-type (lvar-type arg))))
1263 (with-float-traps-masked
1264 (:underflow :overflow :divide-by-zero)
1266 `(eql ,(funcall member-fun
1267 (first (member-type-members x))))))
1268 ;; Otherwise convert to a numeric type.
1269 (let ((result-type-list
1270 (funcall derive-fun (convert-member-type x))))
1272 (convert-back-numeric-type-list result-type-list)
1273 result-type-list))))
1276 (convert-back-numeric-type-list
1277 (funcall derive-fun (convert-numeric-type x)))
1278 (funcall derive-fun x)))
1280 *universal-type*))))
1281 ;; Run down the list of args and derive the type of each one,
1282 ;; saving all of the results in a list.
1283 (let ((results nil))
1284 (dolist (arg arg-list)
1285 (let ((result (deriver arg)))
1287 (setf results (append results result))
1288 (push result results))))
1290 (make-derived-union-type results)
1291 (first results)))))))
1293 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1294 ;;; two arguments. DERIVE-FUN takes 3 args in this case: the two
1295 ;;; original args and a third which is T to indicate if the two args
1296 ;;; really represent the same lvar. This is useful for deriving the
1297 ;;; type of things like (* x x), which should always be positive. If
1298 ;;; we didn't do this, we wouldn't be able to tell.
1299 (defun two-arg-derive-type (arg1 arg2 derive-fun fun
1300 &optional (convert-type t))
1301 (declare (type function derive-fun fun))
1302 (flet ((deriver (x y same-arg)
1303 (cond ((and (member-type-p x) (member-type-p y))
1304 (let* ((x (first (member-type-members x)))
1305 (y (first (member-type-members y)))
1306 (result (ignore-errors
1307 (with-float-traps-masked
1308 (:underflow :overflow :divide-by-zero
1310 (funcall fun x y)))))
1311 (cond ((null result) *empty-type*)
1312 ((and (floatp result) (float-nan-p result))
1313 (make-numeric-type :class 'float
1314 :format (type-of result)
1317 (specifier-type `(eql ,result))))))
1318 ((and (member-type-p x) (numeric-type-p y))
1319 (let* ((x (convert-member-type x))
1320 (y (if convert-type (convert-numeric-type y) y))
1321 (result (funcall derive-fun x y same-arg)))
1323 (convert-back-numeric-type-list result)
1325 ((and (numeric-type-p x) (member-type-p y))
1326 (let* ((x (if convert-type (convert-numeric-type x) x))
1327 (y (convert-member-type y))
1328 (result (funcall derive-fun x y same-arg)))
1330 (convert-back-numeric-type-list result)
1332 ((and (numeric-type-p x) (numeric-type-p y))
1333 (let* ((x (if convert-type (convert-numeric-type x) x))
1334 (y (if convert-type (convert-numeric-type y) y))
1335 (result (funcall derive-fun x y same-arg)))
1337 (convert-back-numeric-type-list result)
1340 *universal-type*))))
1341 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1342 (a1 (prepare-arg-for-derive-type (lvar-type arg1)))
1343 (a2 (prepare-arg-for-derive-type (lvar-type arg2))))
1345 (let ((results nil))
1347 ;; Since the args are the same LVARs, just run down the
1350 (let ((result (deriver x x same-arg)))
1352 (setf results (append results result))
1353 (push result results))))
1354 ;; Try all pairwise combinations.
1357 (let ((result (or (deriver x y same-arg)
1358 (numeric-contagion x y))))
1360 (setf results (append results result))
1361 (push result results))))))
1363 (make-derived-union-type results)
1364 (first results)))))))
1366 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1368 (defoptimizer (+ derive-type) ((x y))
1369 (derive-integer-type
1376 (values (frob (numeric-type-low x) (numeric-type-low y))
1377 (frob (numeric-type-high x) (numeric-type-high y)))))))
1379 (defoptimizer (- derive-type) ((x y))
1380 (derive-integer-type
1387 (values (frob (numeric-type-low x) (numeric-type-high y))
1388 (frob (numeric-type-high x) (numeric-type-low y)))))))
1390 (defoptimizer (* derive-type) ((x y))
1391 (derive-integer-type
1394 (let ((x-low (numeric-type-low x))
1395 (x-high (numeric-type-high x))
1396 (y-low (numeric-type-low y))
1397 (y-high (numeric-type-high y)))
1398 (cond ((not (and x-low y-low))
1400 ((or (minusp x-low) (minusp y-low))
1401 (if (and x-high y-high)
1402 (let ((max (* (max (abs x-low) (abs x-high))
1403 (max (abs y-low) (abs y-high)))))
1404 (values (- max) max))
1407 (values (* x-low y-low)
1408 (if (and x-high y-high)
1412 (defoptimizer (/ derive-type) ((x y))
1413 (numeric-contagion (lvar-type x) (lvar-type y)))
1417 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1419 (defun +-derive-type-aux (x y same-arg)
1420 (if (and (numeric-type-real-p x)
1421 (numeric-type-real-p y))
1424 (let ((x-int (numeric-type->interval x)))
1425 (interval-add x-int x-int))
1426 (interval-add (numeric-type->interval x)
1427 (numeric-type->interval y))))
1428 (result-type (numeric-contagion x y)))
1429 ;; If the result type is a float, we need to be sure to coerce
1430 ;; the bounds into the correct type.
1431 (when (eq (numeric-type-class result-type) 'float)
1432 (setf result (interval-func
1434 (coerce-for-bound x (or (numeric-type-format result-type)
1438 :class (if (and (eq (numeric-type-class x) 'integer)
1439 (eq (numeric-type-class y) 'integer))
1440 ;; The sum of integers is always an integer.
1442 (numeric-type-class result-type))
1443 :format (numeric-type-format result-type)
1444 :low (interval-low result)
1445 :high (interval-high result)))
1446 ;; general contagion
1447 (numeric-contagion x y)))
1449 (defoptimizer (+ derive-type) ((x y))
1450 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1452 (defun --derive-type-aux (x y same-arg)
1453 (if (and (numeric-type-real-p x)
1454 (numeric-type-real-p y))
1456 ;; (- X X) is always 0.
1458 (make-interval :low 0 :high 0)
1459 (interval-sub (numeric-type->interval x)
1460 (numeric-type->interval y))))
1461 (result-type (numeric-contagion x y)))
1462 ;; If the result type is a float, we need to be sure to coerce
1463 ;; the bounds into the correct type.
1464 (when (eq (numeric-type-class result-type) 'float)
1465 (setf result (interval-func
1467 (coerce-for-bound x (or (numeric-type-format result-type)
1471 :class (if (and (eq (numeric-type-class x) 'integer)
1472 (eq (numeric-type-class y) 'integer))
1473 ;; The difference of integers is always an integer.
1475 (numeric-type-class result-type))
1476 :format (numeric-type-format result-type)
1477 :low (interval-low result)
1478 :high (interval-high result)))
1479 ;; general contagion
1480 (numeric-contagion x y)))
1482 (defoptimizer (- derive-type) ((x y))
1483 (two-arg-derive-type x y #'--derive-type-aux #'-))
1485 (defun *-derive-type-aux (x y same-arg)
1486 (if (and (numeric-type-real-p x)
1487 (numeric-type-real-p y))
1489 ;; (* X X) is always positive, so take care to do it right.
1491 (interval-sqr (numeric-type->interval x))
1492 (interval-mul (numeric-type->interval x)
1493 (numeric-type->interval y))))
1494 (result-type (numeric-contagion x y)))
1495 ;; If the result type is a float, we need to be sure to coerce
1496 ;; the bounds into the correct type.
1497 (when (eq (numeric-type-class result-type) 'float)
1498 (setf result (interval-func
1500 (coerce-for-bound x (or (numeric-type-format result-type)
1504 :class (if (and (eq (numeric-type-class x) 'integer)
1505 (eq (numeric-type-class y) 'integer))
1506 ;; The product of integers is always an integer.
1508 (numeric-type-class result-type))
1509 :format (numeric-type-format result-type)
1510 :low (interval-low result)
1511 :high (interval-high result)))
1512 (numeric-contagion x y)))
1514 (defoptimizer (* derive-type) ((x y))
1515 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1517 (defun /-derive-type-aux (x y same-arg)
1518 (if (and (numeric-type-real-p x)
1519 (numeric-type-real-p y))
1521 ;; (/ X X) is always 1, except if X can contain 0. In
1522 ;; that case, we shouldn't optimize the division away
1523 ;; because we want 0/0 to signal an error.
1525 (not (interval-contains-p
1526 0 (interval-closure (numeric-type->interval y)))))
1527 (make-interval :low 1 :high 1)
1528 (interval-div (numeric-type->interval x)
1529 (numeric-type->interval y))))
1530 (result-type (numeric-contagion x y)))
1531 ;; If the result type is a float, we need to be sure to coerce
1532 ;; the bounds into the correct type.
1533 (when (eq (numeric-type-class result-type) 'float)
1534 (setf result (interval-func
1536 (coerce-for-bound x (or (numeric-type-format result-type)
1539 (make-numeric-type :class (numeric-type-class result-type)
1540 :format (numeric-type-format result-type)
1541 :low (interval-low result)
1542 :high (interval-high result)))
1543 (numeric-contagion x y)))
1545 (defoptimizer (/ derive-type) ((x y))
1546 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1550 (defun ash-derive-type-aux (n-type shift same-arg)
1551 (declare (ignore same-arg))
1552 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1553 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1554 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1555 ;; two bignums yielding zero) and it's hard to avoid that
1556 ;; calculation in here.
1557 #+(and cmu sb-xc-host)
1558 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1559 (typep (numeric-type-high n-type) 'bignum))
1560 (or (typep (numeric-type-low shift) 'bignum)
1561 (typep (numeric-type-high shift) 'bignum)))
1562 (return-from ash-derive-type-aux *universal-type*))
1563 (flet ((ash-outer (n s)
1564 (when (and (fixnump s)
1566 (> s sb!xc:most-negative-fixnum))
1568 ;; KLUDGE: The bare 64's here should be related to
1569 ;; symbolic machine word size values somehow.
1572 (if (and (fixnump s)
1573 (> s sb!xc:most-negative-fixnum))
1575 (if (minusp n) -1 0))))
1576 (or (and (csubtypep n-type (specifier-type 'integer))
1577 (csubtypep shift (specifier-type 'integer))
1578 (let ((n-low (numeric-type-low n-type))
1579 (n-high (numeric-type-high n-type))
1580 (s-low (numeric-type-low shift))
1581 (s-high (numeric-type-high shift)))
1582 (make-numeric-type :class 'integer :complexp :real
1585 (ash-outer n-low s-high)
1586 (ash-inner n-low s-low)))
1589 (ash-inner n-high s-low)
1590 (ash-outer n-high s-high))))))
1593 (defoptimizer (ash derive-type) ((n shift))
1594 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1596 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1597 (macrolet ((frob (fun)
1598 `#'(lambda (type type2)
1599 (declare (ignore type2))
1600 (let ((lo (numeric-type-low type))
1601 (hi (numeric-type-high type)))
1602 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1604 (defoptimizer (%negate derive-type) ((num))
1605 (derive-integer-type num num (frob -))))
1607 (defun lognot-derive-type-aux (int)
1608 (derive-integer-type-aux int int
1609 (lambda (type type2)
1610 (declare (ignore type2))
1611 (let ((lo (numeric-type-low type))
1612 (hi (numeric-type-high type)))
1613 (values (if hi (lognot hi) nil)
1614 (if lo (lognot lo) nil)
1615 (numeric-type-class type)
1616 (numeric-type-format type))))))
1618 (defoptimizer (lognot derive-type) ((int))
1619 (lognot-derive-type-aux (lvar-type int)))
1621 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1622 (defoptimizer (%negate derive-type) ((num))
1623 (flet ((negate-bound (b)
1625 (set-bound (- (type-bound-number b))
1627 (one-arg-derive-type num
1629 (modified-numeric-type
1631 :low (negate-bound (numeric-type-high type))
1632 :high (negate-bound (numeric-type-low type))))
1635 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1636 (defoptimizer (abs derive-type) ((num))
1637 (let ((type (lvar-type num)))
1638 (if (and (numeric-type-p type)
1639 (eq (numeric-type-class type) 'integer)
1640 (eq (numeric-type-complexp type) :real))
1641 (let ((lo (numeric-type-low type))
1642 (hi (numeric-type-high type)))
1643 (make-numeric-type :class 'integer :complexp :real
1644 :low (cond ((and hi (minusp hi))
1650 :high (if (and hi lo)
1651 (max (abs hi) (abs lo))
1653 (numeric-contagion type type))))
1655 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1656 (defun abs-derive-type-aux (type)
1657 (cond ((eq (numeric-type-complexp type) :complex)
1658 ;; The absolute value of a complex number is always a
1659 ;; non-negative float.
1660 (let* ((format (case (numeric-type-class type)
1661 ((integer rational) 'single-float)
1662 (t (numeric-type-format type))))
1663 (bound-format (or format 'float)))
1664 (make-numeric-type :class 'float
1667 :low (coerce 0 bound-format)
1670 ;; The absolute value of a real number is a non-negative real
1671 ;; of the same type.
1672 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1673 (class (numeric-type-class type))
1674 (format (numeric-type-format type))
1675 (bound-type (or format class 'real)))
1680 :low (coerce-and-truncate-floats (interval-low abs-bnd) bound-type)
1681 :high (coerce-and-truncate-floats
1682 (interval-high abs-bnd) bound-type))))))
1684 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1685 (defoptimizer (abs derive-type) ((num))
1686 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1688 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1689 (defoptimizer (truncate derive-type) ((number divisor))
1690 (let ((number-type (lvar-type number))
1691 (divisor-type (lvar-type divisor))
1692 (integer-type (specifier-type 'integer)))
1693 (if (and (numeric-type-p number-type)
1694 (csubtypep number-type integer-type)
1695 (numeric-type-p divisor-type)
1696 (csubtypep divisor-type integer-type))
1697 (let ((number-low (numeric-type-low number-type))
1698 (number-high (numeric-type-high number-type))
1699 (divisor-low (numeric-type-low divisor-type))
1700 (divisor-high (numeric-type-high divisor-type)))
1701 (values-specifier-type
1702 `(values ,(integer-truncate-derive-type number-low number-high
1703 divisor-low divisor-high)
1704 ,(integer-rem-derive-type number-low number-high
1705 divisor-low divisor-high))))
1708 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1711 (defun rem-result-type (number-type divisor-type)
1712 ;; Figure out what the remainder type is. The remainder is an
1713 ;; integer if both args are integers; a rational if both args are
1714 ;; rational; and a float otherwise.
1715 (cond ((and (csubtypep number-type (specifier-type 'integer))
1716 (csubtypep divisor-type (specifier-type 'integer)))
1718 ((and (csubtypep number-type (specifier-type 'rational))
1719 (csubtypep divisor-type (specifier-type 'rational)))
1721 ((and (csubtypep number-type (specifier-type 'float))
1722 (csubtypep divisor-type (specifier-type 'float)))
1723 ;; Both are floats so the result is also a float, of
1724 ;; the largest type.
1725 (or (float-format-max (numeric-type-format number-type)
1726 (numeric-type-format divisor-type))
1728 ((and (csubtypep number-type (specifier-type 'float))
1729 (csubtypep divisor-type (specifier-type 'rational)))
1730 ;; One of the arguments is a float and the other is a
1731 ;; rational. The remainder is a float of the same
1733 (or (numeric-type-format number-type) 'float))
1734 ((and (csubtypep divisor-type (specifier-type 'float))
1735 (csubtypep number-type (specifier-type 'rational)))
1736 ;; One of the arguments is a float and the other is a
1737 ;; rational. The remainder is a float of the same
1739 (or (numeric-type-format divisor-type) 'float))
1741 ;; Some unhandled combination. This usually means both args
1742 ;; are REAL so the result is a REAL.
1745 (defun truncate-derive-type-quot (number-type divisor-type)
1746 (let* ((rem-type (rem-result-type number-type divisor-type))
1747 (number-interval (numeric-type->interval number-type))
1748 (divisor-interval (numeric-type->interval divisor-type)))
1749 ;;(declare (type (member '(integer rational float)) rem-type))
1750 ;; We have real numbers now.
1751 (cond ((eq rem-type 'integer)
1752 ;; Since the remainder type is INTEGER, both args are
1754 (let* ((res (integer-truncate-derive-type
1755 (interval-low number-interval)
1756 (interval-high number-interval)
1757 (interval-low divisor-interval)
1758 (interval-high divisor-interval))))
1759 (specifier-type (if (listp res) res 'integer))))
1761 (let ((quot (truncate-quotient-bound
1762 (interval-div number-interval
1763 divisor-interval))))
1764 (specifier-type `(integer ,(or (interval-low quot) '*)
1765 ,(or (interval-high quot) '*))))))))
1767 (defun truncate-derive-type-rem (number-type divisor-type)
1768 (let* ((rem-type (rem-result-type number-type divisor-type))
1769 (number-interval (numeric-type->interval number-type))
1770 (divisor-interval (numeric-type->interval divisor-type))
1771 (rem (truncate-rem-bound number-interval divisor-interval)))
1772 ;;(declare (type (member '(integer rational float)) rem-type))
1773 ;; We have real numbers now.
1774 (cond ((eq rem-type 'integer)
1775 ;; Since the remainder type is INTEGER, both args are
1777 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1778 ,(or (interval-high rem) '*))))
1780 (multiple-value-bind (class format)
1783 (values 'integer nil))
1785 (values 'rational nil))
1786 ((or single-float double-float #!+long-float long-float)
1787 (values 'float rem-type))
1789 (values 'float nil))
1792 (when (member rem-type '(float single-float double-float
1793 #!+long-float long-float))
1794 (setf rem (interval-func #'(lambda (x)
1795 (coerce-for-bound x rem-type))
1797 (make-numeric-type :class class
1799 :low (interval-low rem)
1800 :high (interval-high rem)))))))
1802 (defun truncate-derive-type-quot-aux (num div same-arg)
1803 (declare (ignore same-arg))
1804 (if (and (numeric-type-real-p num)
1805 (numeric-type-real-p div))
1806 (truncate-derive-type-quot num div)
1809 (defun truncate-derive-type-rem-aux (num div same-arg)
1810 (declare (ignore same-arg))
1811 (if (and (numeric-type-real-p num)
1812 (numeric-type-real-p div))
1813 (truncate-derive-type-rem num div)
1816 (defoptimizer (truncate derive-type) ((number divisor))
1817 (let ((quot (two-arg-derive-type number divisor
1818 #'truncate-derive-type-quot-aux #'truncate))
1819 (rem (two-arg-derive-type number divisor
1820 #'truncate-derive-type-rem-aux #'rem)))
1821 (when (and quot rem)
1822 (make-values-type :required (list quot rem)))))
1824 (defun ftruncate-derive-type-quot (number-type divisor-type)
1825 ;; The bounds are the same as for truncate. However, the first
1826 ;; result is a float of some type. We need to determine what that
1827 ;; type is. Basically it's the more contagious of the two types.
1828 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1829 (res-type (numeric-contagion number-type divisor-type)))
1830 (make-numeric-type :class 'float
1831 :format (numeric-type-format res-type)
1832 :low (numeric-type-low q-type)
1833 :high (numeric-type-high q-type))))
1835 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1836 (declare (ignore same-arg))
1837 (if (and (numeric-type-real-p n)
1838 (numeric-type-real-p d))
1839 (ftruncate-derive-type-quot n d)
1842 (defoptimizer (ftruncate derive-type) ((number divisor))
1844 (two-arg-derive-type number divisor
1845 #'ftruncate-derive-type-quot-aux #'ftruncate))
1846 (rem (two-arg-derive-type number divisor
1847 #'truncate-derive-type-rem-aux #'rem)))
1848 (when (and quot rem)
1849 (make-values-type :required (list quot rem)))))
1851 (defun %unary-truncate-derive-type-aux (number)
1852 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1854 (defoptimizer (%unary-truncate derive-type) ((number))
1855 (one-arg-derive-type number
1856 #'%unary-truncate-derive-type-aux
1859 (defoptimizer (%unary-truncate/single-float derive-type) ((number))
1860 (one-arg-derive-type number
1861 #'%unary-truncate-derive-type-aux
1864 (defoptimizer (%unary-truncate/double-float derive-type) ((number))
1865 (one-arg-derive-type number
1866 #'%unary-truncate-derive-type-aux
1869 (defoptimizer (%unary-ftruncate derive-type) ((number))
1870 (let ((divisor (specifier-type '(integer 1 1))))
1871 (one-arg-derive-type number
1873 (ftruncate-derive-type-quot-aux n divisor nil))
1874 #'%unary-ftruncate)))
1876 (defoptimizer (%unary-round derive-type) ((number))
1877 (one-arg-derive-type number
1880 (unless (numeric-type-real-p n)
1881 (return *empty-type*))
1882 (let* ((interval (numeric-type->interval n))
1883 (low (interval-low interval))
1884 (high (interval-high interval)))
1886 (setf low (car low)))
1888 (setf high (car high)))
1898 ;;; Define optimizers for FLOOR and CEILING.
1900 ((def (name q-name r-name)
1901 (let ((q-aux (symbolicate q-name "-AUX"))
1902 (r-aux (symbolicate r-name "-AUX")))
1904 ;; Compute type of quotient (first) result.
1905 (defun ,q-aux (number-type divisor-type)
1906 (let* ((number-interval
1907 (numeric-type->interval number-type))
1909 (numeric-type->interval divisor-type))
1910 (quot (,q-name (interval-div number-interval
1911 divisor-interval))))
1912 (specifier-type `(integer ,(or (interval-low quot) '*)
1913 ,(or (interval-high quot) '*)))))
1914 ;; Compute type of remainder.
1915 (defun ,r-aux (number-type divisor-type)
1916 (let* ((divisor-interval
1917 (numeric-type->interval divisor-type))
1918 (rem (,r-name divisor-interval))
1919 (result-type (rem-result-type number-type divisor-type)))
1920 (multiple-value-bind (class format)
1923 (values 'integer nil))
1925 (values 'rational nil))
1926 ((or single-float double-float #!+long-float long-float)
1927 (values 'float result-type))
1929 (values 'float nil))
1932 (when (member result-type '(float single-float double-float
1933 #!+long-float long-float))
1934 ;; Make sure that the limits on the interval have
1936 (setf rem (interval-func (lambda (x)
1937 (coerce-for-bound x result-type))
1939 (make-numeric-type :class class
1941 :low (interval-low rem)
1942 :high (interval-high rem)))))
1943 ;; the optimizer itself
1944 (defoptimizer (,name derive-type) ((number divisor))
1945 (flet ((derive-q (n d same-arg)
1946 (declare (ignore same-arg))
1947 (if (and (numeric-type-real-p n)
1948 (numeric-type-real-p d))
1951 (derive-r (n d same-arg)
1952 (declare (ignore same-arg))
1953 (if (and (numeric-type-real-p n)
1954 (numeric-type-real-p d))
1957 (let ((quot (two-arg-derive-type
1958 number divisor #'derive-q #',name))
1959 (rem (two-arg-derive-type
1960 number divisor #'derive-r #'mod)))
1961 (when (and quot rem)
1962 (make-values-type :required (list quot rem))))))))))
1964 (def floor floor-quotient-bound floor-rem-bound)
1965 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1967 ;;; Define optimizers for FFLOOR and FCEILING
1968 (macrolet ((def (name q-name r-name)
1969 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1970 (r-aux (symbolicate r-name "-AUX")))
1972 ;; Compute type of quotient (first) result.
1973 (defun ,q-aux (number-type divisor-type)
1974 (let* ((number-interval
1975 (numeric-type->interval number-type))
1977 (numeric-type->interval divisor-type))
1978 (quot (,q-name (interval-div number-interval
1980 (res-type (numeric-contagion number-type
1983 :class (numeric-type-class res-type)
1984 :format (numeric-type-format res-type)
1985 :low (interval-low quot)
1986 :high (interval-high quot))))
1988 (defoptimizer (,name derive-type) ((number divisor))
1989 (flet ((derive-q (n d same-arg)
1990 (declare (ignore same-arg))
1991 (if (and (numeric-type-real-p n)
1992 (numeric-type-real-p d))
1995 (derive-r (n d same-arg)
1996 (declare (ignore same-arg))
1997 (if (and (numeric-type-real-p n)
1998 (numeric-type-real-p d))
2001 (let ((quot (two-arg-derive-type
2002 number divisor #'derive-q #',name))
2003 (rem (two-arg-derive-type
2004 number divisor #'derive-r #'mod)))
2005 (when (and quot rem)
2006 (make-values-type :required (list quot rem))))))))))
2008 (def ffloor floor-quotient-bound floor-rem-bound)
2009 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
2011 ;;; functions to compute the bounds on the quotient and remainder for
2012 ;;; the FLOOR function
2013 (defun floor-quotient-bound (quot)
2014 ;; Take the floor of the quotient and then massage it into what we
2016 (let ((lo (interval-low quot))
2017 (hi (interval-high quot)))
2018 ;; Take the floor of the lower bound. The result is always a
2019 ;; closed lower bound.
2021 (floor (type-bound-number lo))
2023 ;; For the upper bound, we need to be careful.
2026 ;; An open bound. We need to be careful here because
2027 ;; the floor of '(10.0) is 9, but the floor of
2029 (multiple-value-bind (q r) (floor (first hi))
2034 ;; A closed bound, so the answer is obvious.
2038 (make-interval :low lo :high hi)))
2039 (defun floor-rem-bound (div)
2040 ;; The remainder depends only on the divisor. Try to get the
2041 ;; correct sign for the remainder if we can.
2042 (case (interval-range-info div)
2044 ;; The divisor is always positive.
2045 (let ((rem (interval-abs div)))
2046 (setf (interval-low rem) 0)
2047 (when (and (numberp (interval-high rem))
2048 (not (zerop (interval-high rem))))
2049 ;; The remainder never contains the upper bound. However,
2050 ;; watch out for the case where the high limit is zero!
2051 (setf (interval-high rem) (list (interval-high rem))))
2054 ;; The divisor is always negative.
2055 (let ((rem (interval-neg (interval-abs div))))
2056 (setf (interval-high rem) 0)
2057 (when (numberp (interval-low rem))
2058 ;; The remainder never contains the lower bound.
2059 (setf (interval-low rem) (list (interval-low rem))))
2062 ;; The divisor can be positive or negative. All bets off. The
2063 ;; magnitude of remainder is the maximum value of the divisor.
2064 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
2065 ;; The bound never reaches the limit, so make the interval open.
2066 (make-interval :low (if limit
2069 :high (list limit))))))
2071 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
2072 => #S(INTERVAL :LOW 0 :HIGH 10)
2073 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
2074 => #S(INTERVAL :LOW 0 :HIGH 10)
2075 (floor-quotient-bound (make-interval :low 0.3 :high 10))
2076 => #S(INTERVAL :LOW 0 :HIGH 10)
2077 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
2078 => #S(INTERVAL :LOW 0 :HIGH 9)
2079 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
2080 => #S(INTERVAL :LOW 0 :HIGH 10)
2081 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
2082 => #S(INTERVAL :LOW 0 :HIGH 10)
2083 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
2084 => #S(INTERVAL :LOW -2 :HIGH 10)
2085 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
2086 => #S(INTERVAL :LOW -1 :HIGH 10)
2087 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
2088 => #S(INTERVAL :LOW -1 :HIGH 10)
2090 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
2091 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2092 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
2093 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2094 (floor-rem-bound (make-interval :low -10 :high -2.3))
2095 #S(INTERVAL :LOW (-10) :HIGH 0)
2096 (floor-rem-bound (make-interval :low 0.3 :high 10))
2097 => #S(INTERVAL :LOW 0 :HIGH '(10))
2098 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
2099 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
2100 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
2101 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
2104 ;;; same functions for CEILING
2105 (defun ceiling-quotient-bound (quot)
2106 ;; Take the ceiling of the quotient and then massage it into what we
2108 (let ((lo (interval-low quot))
2109 (hi (interval-high quot)))
2110 ;; Take the ceiling of the upper bound. The result is always a
2111 ;; closed upper bound.
2113 (ceiling (type-bound-number hi))
2115 ;; For the lower bound, we need to be careful.
2118 ;; An open bound. We need to be careful here because
2119 ;; the ceiling of '(10.0) is 11, but the ceiling of
2121 (multiple-value-bind (q r) (ceiling (first lo))
2126 ;; A closed bound, so the answer is obvious.
2130 (make-interval :low lo :high hi)))
2131 (defun ceiling-rem-bound (div)
2132 ;; The remainder depends only on the divisor. Try to get the
2133 ;; correct sign for the remainder if we can.
2134 (case (interval-range-info div)
2136 ;; Divisor is always positive. The remainder is negative.
2137 (let ((rem (interval-neg (interval-abs div))))
2138 (setf (interval-high rem) 0)
2139 (when (and (numberp (interval-low rem))
2140 (not (zerop (interval-low rem))))
2141 ;; The remainder never contains the upper bound. However,
2142 ;; watch out for the case when the upper bound is zero!
2143 (setf (interval-low rem) (list (interval-low rem))))
2146 ;; Divisor is always negative. The remainder is positive
2147 (let ((rem (interval-abs div)))
2148 (setf (interval-low rem) 0)
2149 (when (numberp (interval-high rem))
2150 ;; The remainder never contains the lower bound.
2151 (setf (interval-high rem) (list (interval-high rem))))
2154 ;; The divisor can be positive or negative. All bets off. The
2155 ;; magnitude of remainder is the maximum value of the divisor.
2156 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
2157 ;; The bound never reaches the limit, so make the interval open.
2158 (make-interval :low (if limit
2161 :high (list limit))))))
2164 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
2165 => #S(INTERVAL :LOW 1 :HIGH 11)
2166 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
2167 => #S(INTERVAL :LOW 1 :HIGH 11)
2168 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
2169 => #S(INTERVAL :LOW 1 :HIGH 10)
2170 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
2171 => #S(INTERVAL :LOW 1 :HIGH 10)
2172 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
2173 => #S(INTERVAL :LOW 1 :HIGH 11)
2174 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
2175 => #S(INTERVAL :LOW 1 :HIGH 11)
2176 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
2177 => #S(INTERVAL :LOW -1 :HIGH 11)
2178 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
2179 => #S(INTERVAL :LOW 0 :HIGH 11)
2180 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
2181 => #S(INTERVAL :LOW -1 :HIGH 11)
2183 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
2184 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
2185 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
2186 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2187 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
2188 => #S(INTERVAL :LOW 0 :HIGH (10))
2189 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
2190 => #S(INTERVAL :LOW (-10) :HIGH 0)
2191 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
2192 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
2193 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
2194 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
2197 (defun truncate-quotient-bound (quot)
2198 ;; For positive quotients, truncate is exactly like floor. For
2199 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
2200 ;; it's the union of the two pieces.
2201 (case (interval-range-info quot)
2204 (floor-quotient-bound quot))
2206 ;; just like CEILING
2207 (ceiling-quotient-bound quot))
2209 ;; Split the interval into positive and negative pieces, compute
2210 ;; the result for each piece and put them back together.
2211 (destructuring-bind (neg pos) (interval-split 0 quot t t)
2212 (interval-merge-pair (ceiling-quotient-bound neg)
2213 (floor-quotient-bound pos))))))
2215 (defun truncate-rem-bound (num div)
2216 ;; This is significantly more complicated than FLOOR or CEILING. We
2217 ;; need both the number and the divisor to determine the range. The
2218 ;; basic idea is to split the ranges of NUM and DEN into positive
2219 ;; and negative pieces and deal with each of the four possibilities
2221 (case (interval-range-info num)
2223 (case (interval-range-info div)
2225 (floor-rem-bound div))
2227 (ceiling-rem-bound div))
2229 (destructuring-bind (neg pos) (interval-split 0 div t t)
2230 (interval-merge-pair (truncate-rem-bound num neg)
2231 (truncate-rem-bound num pos))))))
2233 (case (interval-range-info div)
2235 (ceiling-rem-bound div))
2237 (floor-rem-bound div))
2239 (destructuring-bind (neg pos) (interval-split 0 div t t)
2240 (interval-merge-pair (truncate-rem-bound num neg)
2241 (truncate-rem-bound num pos))))))
2243 (destructuring-bind (neg pos) (interval-split 0 num t t)
2244 (interval-merge-pair (truncate-rem-bound neg div)
2245 (truncate-rem-bound pos div))))))
2248 ;;; Derive useful information about the range. Returns three values:
2249 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
2250 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
2251 ;;; - The abs of the maximal value if there is one, or nil if it is
2253 (defun numeric-range-info (low high)
2254 (cond ((and low (not (minusp low)))
2255 (values '+ low high))
2256 ((and high (not (plusp high)))
2257 (values '- (- high) (if low (- low) nil)))
2259 (values nil 0 (and low high (max (- low) high))))))
2261 (defun integer-truncate-derive-type
2262 (number-low number-high divisor-low divisor-high)
2263 ;; The result cannot be larger in magnitude than the number, but the
2264 ;; sign might change. If we can determine the sign of either the
2265 ;; number or the divisor, we can eliminate some of the cases.
2266 (multiple-value-bind (number-sign number-min number-max)
2267 (numeric-range-info number-low number-high)
2268 (multiple-value-bind (divisor-sign divisor-min divisor-max)
2269 (numeric-range-info divisor-low divisor-high)
2270 (when (and divisor-max (zerop divisor-max))
2271 ;; We've got a problem: guaranteed division by zero.
2272 (return-from integer-truncate-derive-type t))
2273 (when (zerop divisor-min)
2274 ;; We'll assume that they aren't going to divide by zero.
2276 (cond ((and number-sign divisor-sign)
2277 ;; We know the sign of both.
2278 (if (eq number-sign divisor-sign)
2279 ;; Same sign, so the result will be positive.
2280 `(integer ,(if divisor-max
2281 (truncate number-min divisor-max)
2284 (truncate number-max divisor-min)
2286 ;; Different signs, the result will be negative.
2287 `(integer ,(if number-max
2288 (- (truncate number-max divisor-min))
2291 (- (truncate number-min divisor-max))
2293 ((eq divisor-sign '+)
2294 ;; The divisor is positive. Therefore, the number will just
2295 ;; become closer to zero.
2296 `(integer ,(if number-low
2297 (truncate number-low divisor-min)
2300 (truncate number-high divisor-min)
2302 ((eq divisor-sign '-)
2303 ;; The divisor is negative. Therefore, the absolute value of
2304 ;; the number will become closer to zero, but the sign will also
2306 `(integer ,(if number-high
2307 (- (truncate number-high divisor-min))
2310 (- (truncate number-low divisor-min))
2312 ;; The divisor could be either positive or negative.
2314 ;; The number we are dividing has a bound. Divide that by the
2315 ;; smallest posible divisor.
2316 (let ((bound (truncate number-max divisor-min)))
2317 `(integer ,(- bound) ,bound)))
2319 ;; The number we are dividing is unbounded, so we can't tell
2320 ;; anything about the result.
2323 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2324 (defun integer-rem-derive-type
2325 (number-low number-high divisor-low divisor-high)
2326 (if (and divisor-low divisor-high)
2327 ;; We know the range of the divisor, and the remainder must be
2328 ;; smaller than the divisor. We can tell the sign of the
2329 ;; remainer if we know the sign of the number.
2330 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2331 `(integer ,(if (or (null number-low)
2332 (minusp number-low))
2335 ,(if (or (null number-high)
2336 (plusp number-high))
2339 ;; The divisor is potentially either very positive or very
2340 ;; negative. Therefore, the remainer is unbounded, but we might
2341 ;; be able to tell something about the sign from the number.
2342 `(integer ,(if (and number-low (not (minusp number-low)))
2343 ;; The number we are dividing is positive.
2344 ;; Therefore, the remainder must be positive.
2347 ,(if (and number-high (not (plusp number-high)))
2348 ;; The number we are dividing is negative.
2349 ;; Therefore, the remainder must be negative.
2353 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2354 (defoptimizer (random derive-type) ((bound &optional state))
2355 (let ((type (lvar-type bound)))
2356 (when (numeric-type-p type)
2357 (let ((class (numeric-type-class type))
2358 (high (numeric-type-high type))
2359 (format (numeric-type-format type)))
2363 :low (coerce 0 (or format class 'real))
2364 :high (cond ((not high) nil)
2365 ((eq class 'integer) (max (1- high) 0))
2366 ((or (consp high) (zerop high)) high)
2369 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2370 (defun random-derive-type-aux (type)
2371 (let ((class (numeric-type-class type))
2372 (high (numeric-type-high type))
2373 (format (numeric-type-format type)))
2377 :low (coerce 0 (or format class 'real))
2378 :high (cond ((not high) nil)
2379 ((eq class 'integer) (max (1- high) 0))
2380 ((or (consp high) (zerop high)) high)
2383 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2384 (defoptimizer (random derive-type) ((bound &optional state))
2385 (one-arg-derive-type bound #'random-derive-type-aux nil))
2387 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2389 ;;; Return the maximum number of bits an integer of the supplied type
2390 ;;; can take up, or NIL if it is unbounded. The second (third) value
2391 ;;; is T if the integer can be positive (negative) and NIL if not.
2392 ;;; Zero counts as positive.
2393 (defun integer-type-length (type)
2394 (if (numeric-type-p type)
2395 (let ((min (numeric-type-low type))
2396 (max (numeric-type-high type)))
2397 (values (and min max (max (integer-length min) (integer-length max)))
2398 (or (null max) (not (minusp max)))
2399 (or (null min) (minusp min))))
2402 ;;; See _Hacker's Delight_, Henry S. Warren, Jr. pp 58-63 for an
2403 ;;; explanation of LOG{AND,IOR,XOR}-DERIVE-UNSIGNED-{LOW,HIGH}-BOUND.
2404 ;;; Credit also goes to Raymond Toy for writing (and debugging!) similar
2405 ;;; versions in CMUCL, from which these functions copy liberally.
2407 (defun logand-derive-unsigned-low-bound (x y)
2408 (let ((a (numeric-type-low x))
2409 (b (numeric-type-high x))
2410 (c (numeric-type-low y))
2411 (d (numeric-type-high y)))
2412 (loop for m = (ash 1 (integer-length (lognor a c))) then (ash m -1)
2414 (unless (zerop (logand m (lognot a) (lognot c)))
2415 (let ((temp (logandc2 (logior a m) (1- m))))
2419 (setf temp (logandc2 (logior c m) (1- m)))
2423 finally (return (logand a c)))))
2425 (defun logand-derive-unsigned-high-bound (x y)
2426 (let ((a (numeric-type-low x))
2427 (b (numeric-type-high x))
2428 (c (numeric-type-low y))
2429 (d (numeric-type-high y)))
2430 (loop for m = (ash 1 (integer-length (logxor b d))) then (ash m -1)
2433 ((not (zerop (logand b (lognot d) m)))
2434 (let ((temp (logior (logandc2 b m) (1- m))))
2438 ((not (zerop (logand (lognot b) d m)))
2439 (let ((temp (logior (logandc2 d m) (1- m))))
2443 finally (return (logand b d)))))
2445 (defun logand-derive-type-aux (x y &optional same-leaf)
2447 (return-from logand-derive-type-aux x))
2448 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2449 (declare (ignore x-pos))
2450 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2451 (declare (ignore y-pos))
2453 ;; X must be positive.
2455 ;; They must both be positive.
2456 (cond ((and (null x-len) (null y-len))
2457 (specifier-type 'unsigned-byte))
2459 (specifier-type `(unsigned-byte* ,y-len)))
2461 (specifier-type `(unsigned-byte* ,x-len)))
2463 (let ((low (logand-derive-unsigned-low-bound x y))
2464 (high (logand-derive-unsigned-high-bound x y)))
2465 (specifier-type `(integer ,low ,high)))))
2466 ;; X is positive, but Y might be negative.
2468 (specifier-type 'unsigned-byte))
2470 (specifier-type `(unsigned-byte* ,x-len)))))
2471 ;; X might be negative.
2473 ;; Y must be positive.
2475 (specifier-type 'unsigned-byte))
2476 (t (specifier-type `(unsigned-byte* ,y-len))))
2477 ;; Either might be negative.
2478 (if (and x-len y-len)
2479 ;; The result is bounded.
2480 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2481 ;; We can't tell squat about the result.
2482 (specifier-type 'integer)))))))
2484 (defun logior-derive-unsigned-low-bound (x y)
2485 (let ((a (numeric-type-low x))
2486 (b (numeric-type-high x))
2487 (c (numeric-type-low y))
2488 (d (numeric-type-high y)))
2489 (loop for m = (ash 1 (integer-length (logxor a c))) then (ash m -1)
2492 ((not (zerop (logandc2 (logand c m) a)))
2493 (let ((temp (logand (logior a m) (1+ (lognot m)))))
2497 ((not (zerop (logandc2 (logand a m) c)))
2498 (let ((temp (logand (logior c m) (1+ (lognot m)))))
2502 finally (return (logior a c)))))
2504 (defun logior-derive-unsigned-high-bound (x y)
2505 (let ((a (numeric-type-low x))
2506 (b (numeric-type-high x))
2507 (c (numeric-type-low y))
2508 (d (numeric-type-high y)))
2509 (loop for m = (ash 1 (integer-length (logand b d))) then (ash m -1)
2511 (unless (zerop (logand b d m))
2512 (let ((temp (logior (- b m) (1- m))))
2516 (setf temp (logior (- d m) (1- m)))
2520 finally (return (logior b d)))))
2522 (defun logior-derive-type-aux (x y &optional same-leaf)
2524 (return-from logior-derive-type-aux x))
2525 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2526 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2528 ((and (not x-neg) (not y-neg))
2529 ;; Both are positive.
2530 (if (and x-len y-len)
2531 (let ((low (logior-derive-unsigned-low-bound x y))
2532 (high (logior-derive-unsigned-high-bound x y)))
2533 (specifier-type `(integer ,low ,high)))
2534 (specifier-type `(unsigned-byte* *))))
2536 ;; X must be negative.
2538 ;; Both are negative. The result is going to be negative
2539 ;; and be the same length or shorter than the smaller.
2540 (if (and x-len y-len)
2542 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2544 (specifier-type '(integer * -1)))
2545 ;; X is negative, but we don't know about Y. The result
2546 ;; will be negative, but no more negative than X.
2548 `(integer ,(or (numeric-type-low x) '*)
2551 ;; X might be either positive or negative.
2553 ;; But Y is negative. The result will be negative.
2555 `(integer ,(or (numeric-type-low y) '*)
2557 ;; We don't know squat about either. It won't get any bigger.
2558 (if (and x-len y-len)
2560 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2562 (specifier-type 'integer))))))))
2564 (defun logxor-derive-unsigned-low-bound (x y)
2565 (let ((a (numeric-type-low x))
2566 (b (numeric-type-high x))
2567 (c (numeric-type-low y))
2568 (d (numeric-type-high y)))
2569 (loop for m = (ash 1 (integer-length (logxor a c))) then (ash m -1)
2572 ((not (zerop (logandc2 (logand c m) a)))
2573 (let ((temp (logand (logior a m)
2577 ((not (zerop (logandc2 (logand a m) c)))
2578 (let ((temp (logand (logior c m)
2582 finally (return (logxor a c)))))
2584 (defun logxor-derive-unsigned-high-bound (x y)
2585 (let ((a (numeric-type-low x))
2586 (b (numeric-type-high x))
2587 (c (numeric-type-low y))
2588 (d (numeric-type-high y)))
2589 (loop for m = (ash 1 (integer-length (logand b d))) then (ash m -1)
2591 (unless (zerop (logand b d m))
2592 (let ((temp (logior (- b m) (1- m))))
2594 ((>= temp a) (setf b temp))
2595 (t (let ((temp (logior (- d m) (1- m))))
2598 finally (return (logxor b d)))))
2600 (defun logxor-derive-type-aux (x y &optional same-leaf)
2602 (return-from logxor-derive-type-aux (specifier-type '(eql 0))))
2603 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2604 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2606 ((and (not x-neg) (not y-neg))
2607 ;; Both are positive
2608 (if (and x-len y-len)
2609 (let ((low (logxor-derive-unsigned-low-bound x y))
2610 (high (logxor-derive-unsigned-high-bound x y)))
2611 (specifier-type `(integer ,low ,high)))
2612 (specifier-type '(unsigned-byte* *))))
2613 ((and (not x-pos) (not y-pos))
2614 ;; Both are negative. The result will be positive, and as long
2616 (specifier-type `(unsigned-byte* ,(if (and x-len y-len)
2619 ((or (and (not x-pos) (not y-neg))
2620 (and (not y-pos) (not x-neg)))
2621 ;; Either X is negative and Y is positive or vice-versa. The
2622 ;; result will be negative.
2623 (specifier-type `(integer ,(if (and x-len y-len)
2624 (ash -1 (max x-len y-len))
2627 ;; We can't tell what the sign of the result is going to be.
2628 ;; All we know is that we don't create new bits.
2630 (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2632 (specifier-type 'integer))))))
2634 (macrolet ((deffrob (logfun)
2635 (let ((fun-aux (symbolicate logfun "-DERIVE-TYPE-AUX")))
2636 `(defoptimizer (,logfun derive-type) ((x y))
2637 (two-arg-derive-type x y #',fun-aux #',logfun)))))
2642 (defoptimizer (logeqv derive-type) ((x y))
2643 (two-arg-derive-type x y (lambda (x y same-leaf)
2644 (lognot-derive-type-aux
2645 (logxor-derive-type-aux x y same-leaf)))
2647 (defoptimizer (lognand derive-type) ((x y))
2648 (two-arg-derive-type x y (lambda (x y same-leaf)
2649 (lognot-derive-type-aux
2650 (logand-derive-type-aux x y same-leaf)))
2652 (defoptimizer (lognor derive-type) ((x y))
2653 (two-arg-derive-type x y (lambda (x y same-leaf)
2654 (lognot-derive-type-aux
2655 (logior-derive-type-aux x y same-leaf)))
2657 (defoptimizer (logandc1 derive-type) ((x y))
2658 (two-arg-derive-type x y (lambda (x y same-leaf)
2660 (specifier-type '(eql 0))
2661 (logand-derive-type-aux
2662 (lognot-derive-type-aux x) y nil)))
2664 (defoptimizer (logandc2 derive-type) ((x y))
2665 (two-arg-derive-type x y (lambda (x y same-leaf)
2667 (specifier-type '(eql 0))
2668 (logand-derive-type-aux
2669 x (lognot-derive-type-aux y) nil)))
2671 (defoptimizer (logorc1 derive-type) ((x y))
2672 (two-arg-derive-type x y (lambda (x y same-leaf)
2674 (specifier-type '(eql -1))
2675 (logior-derive-type-aux
2676 (lognot-derive-type-aux x) y nil)))
2678 (defoptimizer (logorc2 derive-type) ((x y))
2679 (two-arg-derive-type x y (lambda (x y same-leaf)
2681 (specifier-type '(eql -1))
2682 (logior-derive-type-aux
2683 x (lognot-derive-type-aux y) nil)))
2686 ;;;; miscellaneous derive-type methods
2688 (defoptimizer (integer-length derive-type) ((x))
2689 (let ((x-type (lvar-type x)))
2690 (when (numeric-type-p x-type)
2691 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2692 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2693 ;; careful about LO or HI being NIL, though. Also, if 0 is
2694 ;; contained in X, the lower bound is obviously 0.
2695 (flet ((null-or-min (a b)
2696 (and a b (min (integer-length a)
2697 (integer-length b))))
2699 (and a b (max (integer-length a)
2700 (integer-length b)))))
2701 (let* ((min (numeric-type-low x-type))
2702 (max (numeric-type-high x-type))
2703 (min-len (null-or-min min max))
2704 (max-len (null-or-max min max)))
2705 (when (ctypep 0 x-type)
2707 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2709 (defoptimizer (isqrt derive-type) ((x))
2710 (let ((x-type (lvar-type x)))
2711 (when (numeric-type-p x-type)
2712 (let* ((lo (numeric-type-low x-type))
2713 (hi (numeric-type-high x-type))
2714 (lo-res (if lo (isqrt lo) '*))
2715 (hi-res (if hi (isqrt hi) '*)))
2716 (specifier-type `(integer ,lo-res ,hi-res))))))
2718 (defoptimizer (char-code derive-type) ((char))
2719 (let ((type (type-intersection (lvar-type char) (specifier-type 'character))))
2720 (cond ((member-type-p type)
2723 ,@(loop for member in (member-type-members type)
2724 when (characterp member)
2725 collect (char-code member)))))
2726 ((sb!kernel::character-set-type-p type)
2729 ,@(loop for (low . high)
2730 in (character-set-type-pairs type)
2731 collect `(integer ,low ,high)))))
2732 ((csubtypep type (specifier-type 'base-char))
2734 `(mod ,base-char-code-limit)))
2737 `(mod ,char-code-limit))))))
2739 (defoptimizer (code-char derive-type) ((code))
2740 (let ((type (lvar-type code)))
2741 ;; FIXME: unions of integral ranges? It ought to be easier to do
2742 ;; this, given that CHARACTER-SET is basically an integral range
2743 ;; type. -- CSR, 2004-10-04
2744 (when (numeric-type-p type)
2745 (let* ((lo (numeric-type-low type))
2746 (hi (numeric-type-high type))
2747 (type (specifier-type `(character-set ((,lo . ,hi))))))
2749 ;; KLUDGE: when running on the host, we lose a slight amount
2750 ;; of precision so that we don't have to "unparse" types
2751 ;; that formally we can't, such as (CHARACTER-SET ((0
2752 ;; . 0))). -- CSR, 2004-10-06
2754 ((csubtypep type (specifier-type 'standard-char)) type)
2756 ((csubtypep type (specifier-type 'base-char))
2757 (specifier-type 'base-char))
2759 ((csubtypep type (specifier-type 'extended-char))
2760 (specifier-type 'extended-char))
2761 (t #+sb-xc-host (specifier-type 'character)
2762 #-sb-xc-host type))))))
2764 (defoptimizer (values derive-type) ((&rest values))
2765 (make-values-type :required (mapcar #'lvar-type values)))
2767 (defun signum-derive-type-aux (type)
2768 (if (eq (numeric-type-complexp type) :complex)
2769 (let* ((format (case (numeric-type-class type)
2770 ((integer rational) 'single-float)
2771 (t (numeric-type-format type))))
2772 (bound-format (or format 'float)))
2773 (make-numeric-type :class 'float
2776 :low (coerce -1 bound-format)
2777 :high (coerce 1 bound-format)))
2778 (let* ((interval (numeric-type->interval type))
2779 (range-info (interval-range-info interval))
2780 (contains-0-p (interval-contains-p 0 interval))
2781 (class (numeric-type-class type))
2782 (format (numeric-type-format type))
2783 (one (coerce 1 (or format class 'real)))
2784 (zero (coerce 0 (or format class 'real)))
2785 (minus-one (coerce -1 (or format class 'real)))
2786 (plus (make-numeric-type :class class :format format
2787 :low one :high one))
2788 (minus (make-numeric-type :class class :format format
2789 :low minus-one :high minus-one))
2790 ;; KLUDGE: here we have a fairly horrible hack to deal
2791 ;; with the schizophrenia in the type derivation engine.
2792 ;; The problem is that the type derivers reinterpret
2793 ;; numeric types as being exact; so (DOUBLE-FLOAT 0d0
2794 ;; 0d0) within the derivation mechanism doesn't include
2795 ;; -0d0. Ugh. So force it in here, instead.
2796 (zero (make-numeric-type :class class :format format
2797 :low (- zero) :high zero)))
2799 (+ (if contains-0-p (type-union plus zero) plus))
2800 (- (if contains-0-p (type-union minus zero) minus))
2801 (t (type-union minus zero plus))))))
2803 (defoptimizer (signum derive-type) ((num))
2804 (one-arg-derive-type num #'signum-derive-type-aux nil))
2806 ;;;; byte operations
2808 ;;;; We try to turn byte operations into simple logical operations.
2809 ;;;; First, we convert byte specifiers into separate size and position
2810 ;;;; arguments passed to internal %FOO functions. We then attempt to
2811 ;;;; transform the %FOO functions into boolean operations when the
2812 ;;;; size and position are constant and the operands are fixnums.
2814 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2815 ;; expressions that evaluate to the SIZE and POSITION of
2816 ;; the byte-specifier form SPEC. We may wrap a let around
2817 ;; the result of the body to bind some variables.
2819 ;; If the spec is a BYTE form, then bind the vars to the
2820 ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2821 ;; and BYTE-POSITION. The goal of this transformation is to
2822 ;; avoid consing up byte specifiers and then immediately
2823 ;; throwing them away.
2824 (with-byte-specifier ((size-var pos-var spec) &body body)
2825 (once-only ((spec `(macroexpand ,spec))
2827 `(if (and (consp ,spec)
2828 (eq (car ,spec) 'byte)
2829 (= (length ,spec) 3))
2830 (let ((,size-var (second ,spec))
2831 (,pos-var (third ,spec)))
2833 (let ((,size-var `(byte-size ,,temp))
2834 (,pos-var `(byte-position ,,temp)))
2835 `(let ((,,temp ,,spec))
2838 (define-source-transform ldb (spec int)
2839 (with-byte-specifier (size pos spec)
2840 `(%ldb ,size ,pos ,int)))
2842 (define-source-transform dpb (newbyte spec int)
2843 (with-byte-specifier (size pos spec)
2844 `(%dpb ,newbyte ,size ,pos ,int)))
2846 (define-source-transform mask-field (spec int)
2847 (with-byte-specifier (size pos spec)
2848 `(%mask-field ,size ,pos ,int)))
2850 (define-source-transform deposit-field (newbyte spec int)
2851 (with-byte-specifier (size pos spec)
2852 `(%deposit-field ,newbyte ,size ,pos ,int))))
2854 (defoptimizer (%ldb derive-type) ((size posn num))
2855 (let ((size (lvar-type size)))
2856 (if (and (numeric-type-p size)
2857 (csubtypep size (specifier-type 'integer)))
2858 (let ((size-high (numeric-type-high size)))
2859 (if (and size-high (<= size-high sb!vm:n-word-bits))
2860 (specifier-type `(unsigned-byte* ,size-high))
2861 (specifier-type 'unsigned-byte)))
2864 (defoptimizer (%mask-field derive-type) ((size posn num))
2865 (let ((size (lvar-type size))
2866 (posn (lvar-type posn)))
2867 (if (and (numeric-type-p size)
2868 (csubtypep size (specifier-type 'integer))
2869 (numeric-type-p posn)
2870 (csubtypep posn (specifier-type 'integer)))
2871 (let ((size-high (numeric-type-high size))
2872 (posn-high (numeric-type-high posn)))
2873 (if (and size-high posn-high
2874 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2875 (specifier-type `(unsigned-byte* ,(+ size-high posn-high)))
2876 (specifier-type 'unsigned-byte)))
2879 (defun %deposit-field-derive-type-aux (size posn int)
2880 (let ((size (lvar-type size))
2881 (posn (lvar-type posn))
2882 (int (lvar-type int)))
2883 (when (and (numeric-type-p size)
2884 (numeric-type-p posn)
2885 (numeric-type-p int))
2886 (let ((size-high (numeric-type-high size))
2887 (posn-high (numeric-type-high posn))
2888 (high (numeric-type-high int))
2889 (low (numeric-type-low int)))
2890 (when (and size-high posn-high high low
2891 ;; KLUDGE: we need this cutoff here, otherwise we
2892 ;; will merrily derive the type of %DPB as
2893 ;; (UNSIGNED-BYTE 1073741822), and then attempt to
2894 ;; canonicalize this type to (INTEGER 0 (1- (ASH 1
2895 ;; 1073741822))), with hilarious consequences. We
2896 ;; cutoff at 4*SB!VM:N-WORD-BITS to allow inference
2897 ;; over a reasonable amount of shifting, even on
2898 ;; the alpha/32 port, where N-WORD-BITS is 32 but
2899 ;; machine integers are 64-bits. -- CSR,
2901 (<= (+ size-high posn-high) (* 4 sb!vm:n-word-bits)))
2902 (let ((raw-bit-count (max (integer-length high)
2903 (integer-length low)
2904 (+ size-high posn-high))))
2907 `(signed-byte ,(1+ raw-bit-count))
2908 `(unsigned-byte* ,raw-bit-count)))))))))
2910 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2911 (%deposit-field-derive-type-aux size posn int))
2913 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2914 (%deposit-field-derive-type-aux size posn int))
2916 (deftransform %ldb ((size posn int)
2917 (fixnum fixnum integer)
2918 (unsigned-byte #.sb!vm:n-word-bits))
2919 "convert to inline logical operations"
2920 `(logand (ash int (- posn))
2921 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2922 (- size ,sb!vm:n-word-bits))))
2924 (deftransform %mask-field ((size posn int)
2925 (fixnum fixnum integer)
2926 (unsigned-byte #.sb!vm:n-word-bits))
2927 "convert to inline logical operations"
2929 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2930 (- size ,sb!vm:n-word-bits))
2933 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2934 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2935 ;;; as the result type, as that would allow result types that cover
2936 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2937 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2939 (deftransform %dpb ((new size posn int)
2941 (unsigned-byte #.sb!vm:n-word-bits))
2942 "convert to inline logical operations"
2943 `(let ((mask (ldb (byte size 0) -1)))
2944 (logior (ash (logand new mask) posn)
2945 (logand int (lognot (ash mask posn))))))
2947 (deftransform %dpb ((new size posn int)
2949 (signed-byte #.sb!vm:n-word-bits))
2950 "convert to inline logical operations"
2951 `(let ((mask (ldb (byte size 0) -1)))
2952 (logior (ash (logand new mask) posn)
2953 (logand int (lognot (ash mask posn))))))
2955 (deftransform %deposit-field ((new size posn int)
2957 (unsigned-byte #.sb!vm:n-word-bits))
2958 "convert to inline logical operations"
2959 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2960 (logior (logand new mask)
2961 (logand int (lognot mask)))))
2963 (deftransform %deposit-field ((new size posn int)
2965 (signed-byte #.sb!vm:n-word-bits))
2966 "convert to inline logical operations"
2967 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2968 (logior (logand new mask)
2969 (logand int (lognot mask)))))
2971 (defoptimizer (mask-signed-field derive-type) ((size x))
2972 (let ((size (lvar-type size)))
2973 (if (numeric-type-p size)
2974 (let ((size-high (numeric-type-high size)))
2975 (if (and size-high (<= 1 size-high sb!vm:n-word-bits))
2976 (specifier-type `(signed-byte ,size-high))
2981 ;;; Modular functions
2983 ;;; (ldb (byte s 0) (foo x y ...)) =
2984 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2986 ;;; and similar for other arguments.
2988 (defun make-modular-fun-type-deriver (prototype kind width signedp)
2989 (declare (ignore kind))
2991 (binding* ((info (info :function :info prototype) :exit-if-null)
2992 (fun (fun-info-derive-type info) :exit-if-null)
2993 (mask-type (specifier-type
2995 ((nil) (let ((mask (1- (ash 1 width))))
2996 `(integer ,mask ,mask)))
2997 ((t) `(signed-byte ,width))))))
2999 (let ((res (funcall fun call)))
3001 (if (eq signedp nil)
3002 (logand-derive-type-aux res mask-type))))))
3005 (binding* ((info (info :function :info prototype) :exit-if-null)
3006 (fun (fun-info-derive-type info) :exit-if-null)
3007 (res (funcall fun call) :exit-if-null)
3008 (mask-type (specifier-type
3010 ((nil) (let ((mask (1- (ash 1 width))))
3011 `(integer ,mask ,mask)))
3012 ((t) `(signed-byte ,width))))))
3013 (if (eq signedp nil)
3014 (logand-derive-type-aux res mask-type)))))
3016 ;;; Try to recursively cut all uses of LVAR to WIDTH bits.
3018 ;;; For good functions, we just recursively cut arguments; their
3019 ;;; "goodness" means that the result will not increase (in the
3020 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
3021 ;;; replaced with the version, cutting its result to WIDTH or more
3022 ;;; bits. For most functions (e.g. for +) we cut all arguments; for
3023 ;;; others (e.g. for ASH) we have "optimizers", cutting only necessary
3024 ;;; arguments (maybe to a different width) and returning the name of a
3025 ;;; modular version, if it exists, or NIL. If we have changed
3026 ;;; anything, we need to flush old derived types, because they have
3027 ;;; nothing in common with the new code.
3028 (defun cut-to-width (lvar kind width signedp)
3029 (declare (type lvar lvar) (type (integer 0) width))
3030 (let ((type (specifier-type (if (zerop width)
3033 ((nil) 'unsigned-byte)
3036 (labels ((reoptimize-node (node name)
3037 (setf (node-derived-type node)
3039 (info :function :type name)))
3040 (setf (lvar-%derived-type (node-lvar node)) nil)
3041 (setf (node-reoptimize node) t)
3042 (setf (block-reoptimize (node-block node)) t)
3043 (reoptimize-component (node-component node) :maybe))
3044 (cut-node (node &aux did-something)
3045 (when (and (not (block-delete-p (node-block node)))
3046 (combination-p node)
3047 (eq (basic-combination-kind node) :known))
3048 (let* ((fun-ref (lvar-use (combination-fun node)))
3049 (fun-name (leaf-source-name (ref-leaf fun-ref)))
3050 (modular-fun (find-modular-version fun-name kind signedp width)))
3051 (when (and modular-fun
3052 (not (and (eq fun-name 'logand)
3054 (single-value-type (node-derived-type node))
3056 (binding* ((name (etypecase modular-fun
3057 ((eql :good) fun-name)
3059 (modular-fun-info-name modular-fun))
3061 (funcall modular-fun node width)))
3063 (unless (eql modular-fun :good)
3064 (setq did-something t)
3067 (find-free-fun name "in a strange place"))
3068 (setf (combination-kind node) :full))
3069 (unless (functionp modular-fun)
3070 (dolist (arg (basic-combination-args node))
3071 (when (cut-lvar arg)
3072 (setq did-something t))))
3074 (reoptimize-node node name))
3076 (cut-lvar (lvar &aux did-something)
3077 (do-uses (node lvar)
3078 (when (cut-node node)
3079 (setq did-something t)))
3083 (defun best-modular-version (width signedp)
3084 ;; 1. exact width-matched :untagged
3085 ;; 2. >/>= width-matched :tagged
3086 ;; 3. >/>= width-matched :untagged
3087 (let* ((uuwidths (modular-class-widths *untagged-unsigned-modular-class*))
3088 (uswidths (modular-class-widths *untagged-signed-modular-class*))
3089 (uwidths (merge 'list uuwidths uswidths #'< :key #'car))
3090 (twidths (modular-class-widths *tagged-modular-class*)))
3091 (let ((exact (find (cons width signedp) uwidths :test #'equal)))
3093 (return-from best-modular-version (values width :untagged signedp))))
3094 (flet ((inexact-match (w)
3096 ((eq signedp (cdr w)) (<= width (car w)))
3097 ((eq signedp nil) (< width (car w))))))
3098 (let ((tgt (find-if #'inexact-match twidths)))
3100 (return-from best-modular-version
3101 (values (car tgt) :tagged (cdr tgt)))))
3102 (let ((ugt (find-if #'inexact-match uwidths)))
3104 (return-from best-modular-version
3105 (values (car ugt) :untagged (cdr ugt))))))))
3107 (defoptimizer (logand optimizer) ((x y) node)
3108 (let ((result-type (single-value-type (node-derived-type node))))
3109 (when (numeric-type-p result-type)
3110 (let ((low (numeric-type-low result-type))
3111 (high (numeric-type-high result-type)))
3112 (when (and (numberp low)
3115 (let ((width (integer-length high)))
3116 (multiple-value-bind (w kind signedp)
3117 (best-modular-version width nil)
3119 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND WIDTH SIGNEDP).
3120 (cut-to-width x kind width signedp)
3121 (cut-to-width y kind width signedp)
3122 nil ; After fixing above, replace with T.
3125 (defoptimizer (mask-signed-field optimizer) ((width x) node)
3126 (let ((result-type (single-value-type (node-derived-type node))))
3127 (when (numeric-type-p result-type)
3128 (let ((low (numeric-type-low result-type))
3129 (high (numeric-type-high result-type)))
3130 (when (and (numberp low) (numberp high))
3131 (let ((width (max (integer-length high) (integer-length low))))
3132 (multiple-value-bind (w kind)
3133 (best-modular-version width t)
3135 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND WIDTH T).
3136 (cut-to-width x kind width t)
3137 nil ; After fixing above, replace with T.
3140 ;;; miscellanous numeric transforms
3142 ;;; If a constant appears as the first arg, swap the args.
3143 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
3144 (if (and (constant-lvar-p x)
3145 (not (constant-lvar-p y)))
3146 `(,(lvar-fun-name (basic-combination-fun node))
3149 (give-up-ir1-transform)))
3151 (dolist (x '(= char= + * logior logand logxor))
3152 (%deftransform x '(function * *) #'commutative-arg-swap
3153 "place constant arg last"))
3155 ;;; Handle the case of a constant BOOLE-CODE.
3156 (deftransform boole ((op x y) * *)
3157 "convert to inline logical operations"
3158 (unless (constant-lvar-p op)
3159 (give-up-ir1-transform "BOOLE code is not a constant."))
3160 (let ((control (lvar-value op)))
3162 (#.sb!xc:boole-clr 0)
3163 (#.sb!xc:boole-set -1)
3164 (#.sb!xc:boole-1 'x)
3165 (#.sb!xc:boole-2 'y)
3166 (#.sb!xc:boole-c1 '(lognot x))
3167 (#.sb!xc:boole-c2 '(lognot y))
3168 (#.sb!xc:boole-and '(logand x y))
3169 (#.sb!xc:boole-ior '(logior x y))
3170 (#.sb!xc:boole-xor '(logxor x y))
3171 (#.sb!xc:boole-eqv '(logeqv x y))
3172 (#.sb!xc:boole-nand '(lognand x y))
3173 (#.sb!xc:boole-nor '(lognor x y))
3174 (#.sb!xc:boole-andc1 '(logandc1 x y))
3175 (#.sb!xc:boole-andc2 '(logandc2 x y))
3176 (#.sb!xc:boole-orc1 '(logorc1 x y))
3177 (#.sb!xc:boole-orc2 '(logorc2 x y))
3179 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
3182 ;;;; converting special case multiply/divide to shifts
3184 ;;; If arg is a constant power of two, turn * into a shift.
3185 (deftransform * ((x y) (integer integer) *)
3186 "convert x*2^k to shift"
3187 (unless (constant-lvar-p y)
3188 (give-up-ir1-transform))
3189 (let* ((y (lvar-value y))
3191 (len (1- (integer-length y-abs))))
3192 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3193 (give-up-ir1-transform))
3198 ;;; These must come before the ones below, so that they are tried
3199 ;;; first. Since %FLOOR and %CEILING are inlined, this allows
3200 ;;; the general case to be handled by TRUNCATE transforms.
3201 (deftransform floor ((x y))
3204 (deftransform ceiling ((x y))
3207 ;;; If arg is a constant power of two, turn FLOOR into a shift and
3208 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
3210 (flet ((frob (y ceil-p)
3211 (unless (constant-lvar-p y)
3212 (give-up-ir1-transform))
3213 (let* ((y (lvar-value y))
3215 (len (1- (integer-length y-abs))))
3216 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3217 (give-up-ir1-transform))
3218 (let ((shift (- len))
3220 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
3221 `(let ((x (+ x ,delta)))
3223 `(values (ash (- x) ,shift)
3224 (- (- (logand (- x) ,mask)) ,delta))
3225 `(values (ash x ,shift)
3226 (- (logand x ,mask) ,delta))))))))
3227 (deftransform floor ((x y) (integer integer) *)
3228 "convert division by 2^k to shift"
3230 (deftransform ceiling ((x y) (integer integer) *)
3231 "convert division by 2^k to shift"
3234 ;;; Do the same for MOD.
3235 (deftransform mod ((x y) (integer integer) *)
3236 "convert remainder mod 2^k to LOGAND"
3237 (unless (constant-lvar-p y)
3238 (give-up-ir1-transform))
3239 (let* ((y (lvar-value y))
3241 (len (1- (integer-length y-abs))))
3242 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3243 (give-up-ir1-transform))
3244 (let ((mask (1- y-abs)))
3246 `(- (logand (- x) ,mask))
3247 `(logand x ,mask)))))
3249 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
3250 (deftransform truncate ((x y) (integer integer))
3251 "convert division by 2^k to shift"
3252 (unless (constant-lvar-p y)
3253 (give-up-ir1-transform))
3254 (let* ((y (lvar-value y))
3256 (len (1- (integer-length y-abs))))
3257 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3258 (give-up-ir1-transform))
3259 (let* ((shift (- len))
3262 (values ,(if (minusp y)
3264 `(- (ash (- x) ,shift)))
3265 (- (logand (- x) ,mask)))
3266 (values ,(if (minusp y)
3267 `(ash (- ,mask x) ,shift)
3269 (logand x ,mask))))))
3271 ;;; And the same for REM.
3272 (deftransform rem ((x y) (integer integer) *)
3273 "convert remainder mod 2^k to LOGAND"
3274 (unless (constant-lvar-p y)
3275 (give-up-ir1-transform))
3276 (let* ((y (lvar-value y))
3278 (len (1- (integer-length y-abs))))
3279 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3280 (give-up-ir1-transform))
3281 (let ((mask (1- y-abs)))
3283 (- (logand (- x) ,mask))
3284 (logand x ,mask)))))
3286 ;;; Return an expression to calculate the integer quotient of X and
3287 ;;; constant Y, using multiplication, shift and add/sub instead of
3288 ;;; division. Both arguments must be unsigned, fit in a machine word and
3289 ;;; Y must neither be zero nor a power of two. The quotient is rounded
3291 ;;; The algorithm is taken from the paper "Division by Invariant
3292 ;;; Integers using Multiplication", 1994 by Torbj\"{o}rn Granlund and
3293 ;;; Peter L. Montgomery, Figures 4.2 and 6.2, modified to exclude the
3294 ;;; case of division by powers of two.
3295 ;;; The algorithm includes an adaptive precision argument. Use it, since
3296 ;;; we often have sub-word value ranges. Careful, in this case, we need
3297 ;;; p s.t 2^p > n, not the ceiling of the binary log.
3298 ;;; Also, for some reason, the paper prefers shifting to masking. Mask
3299 ;;; instead. Masking is equivalent to shifting right, then left again;
3300 ;;; all the intermediate values are still words, so we just have to shift
3301 ;;; right a bit more to compensate, at the end.
3303 ;;; The following two examples show an average case and the worst case
3304 ;;; with respect to the complexity of the generated expression, under
3305 ;;; a word size of 64 bits:
3307 ;;; (UNSIGNED-DIV-TRANSFORMER 10 MOST-POSITIVE-WORD) ->
3308 ;;; (ASH (%MULTIPLY (LOGANDC2 X 0) 14757395258967641293) -3)
3310 ;;; (UNSIGNED-DIV-TRANSFORMER 7 MOST-POSITIVE-WORD) ->
3312 ;;; (T1 (%MULTIPLY NUM 2635249153387078803)))
3313 ;;; (ASH (LDB (BYTE 64 0)
3314 ;;; (+ T1 (ASH (LDB (BYTE 64 0)
3319 (defun gen-unsigned-div-by-constant-expr (y max-x)
3320 (declare (type (integer 3 #.most-positive-word) y)
3322 (aver (not (zerop (logand y (1- y)))))
3324 ;; the floor of the binary logarithm of (positive) X
3325 (integer-length (1- x)))
3326 (choose-multiplier (y precision)
3328 (shift l (1- shift))
3329 (expt-2-n+l (expt 2 (+ sb!vm:n-word-bits l)))
3330 (m-low (truncate expt-2-n+l y) (ash m-low -1))
3331 (m-high (truncate (+ expt-2-n+l
3332 (ash expt-2-n+l (- precision)))
3335 ((not (and (< (ash m-low -1) (ash m-high -1))
3337 (values m-high shift)))))
3338 (let ((n (expt 2 sb!vm:n-word-bits))
3339 (precision (integer-length max-x))
3341 (multiple-value-bind (m shift2)
3342 (choose-multiplier y precision)
3343 (when (and (>= m n) (evenp y))
3344 (setq shift1 (ld (logand y (- y))))
3345 (multiple-value-setq (m shift2)
3346 (choose-multiplier (/ y (ash 1 shift1))
3347 (- precision shift1))))
3350 `(truly-the word ,x)))
3352 (t1 (%multiply-high num ,(- m n))))
3353 (ash ,(word `(+ t1 (ash ,(word `(- num t1))
3356 ((and (zerop shift1) (zerop shift2))
3357 (let ((max (truncate max-x y)))
3358 ;; Explicit TRULY-THE needed to get the FIXNUM=>FIXNUM
3360 `(truly-the (integer 0 ,max)
3361 (%multiply-high x ,m))))
3363 `(ash (%multiply-high (logandc2 x ,(1- (ash 1 shift1))) ,m)
3364 ,(- (+ shift1 shift2)))))))))
3366 ;;; If the divisor is constant and both args are positive and fit in a
3367 ;;; machine word, replace the division by a multiplication and possibly
3368 ;;; some shifts and an addition. Calculate the remainder by a second
3369 ;;; multiplication and a subtraction. Dead code elimination will
3370 ;;; suppress the latter part if only the quotient is needed. If the type
3371 ;;; of the dividend allows to derive that the quotient will always have
3372 ;;; the same value, emit much simpler code to handle that. (This case
3373 ;;; may be rare but it's easy to detect and the compiler doesn't find
3374 ;;; this optimization on its own.)
3375 (deftransform truncate ((x y) (word (constant-arg word))
3377 :policy (and (> speed compilation-speed)
3379 "convert integer division to multiplication"
3380 (let* ((y (lvar-value y))
3381 (x-type (lvar-type x))
3382 (max-x (or (and (numeric-type-p x-type)
3383 (numeric-type-high x-type))
3384 most-positive-word)))
3385 ;; Division by zero, one or powers of two is handled elsewhere.
3386 (when (zerop (logand y (1- y)))
3387 (give-up-ir1-transform))
3388 `(let* ((quot ,(gen-unsigned-div-by-constant-expr y max-x))
3389 (rem (ldb (byte #.sb!vm:n-word-bits 0)
3390 (- x (* quot ,y)))))
3391 (values quot rem))))
3393 ;;;; arithmetic and logical identity operation elimination
3395 ;;; Flush calls to various arith functions that convert to the
3396 ;;; identity function or a constant.
3397 (macrolet ((def (name identity result)
3398 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
3399 "fold identity operations"
3406 (def logxor -1 (lognot x))
3409 (deftransform logand ((x y) (* (constant-arg t)) *)
3410 "fold identity operation"
3411 (let ((y (lvar-value y)))
3412 (unless (and (plusp y)
3413 (= y (1- (ash 1 (integer-length y)))))
3414 (give-up-ir1-transform))
3415 (unless (csubtypep (lvar-type x)
3416 (specifier-type `(integer 0 ,y)))
3417 (give-up-ir1-transform))
3420 (deftransform mask-signed-field ((size x) ((constant-arg t) *) *)
3421 "fold identity operation"
3422 (let ((size (lvar-value size)))
3423 (unless (csubtypep (lvar-type x) (specifier-type `(signed-byte ,size)))
3424 (give-up-ir1-transform))
3427 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
3428 ;;; (* 0 -4.0) is -0.0.
3429 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
3430 "convert (- 0 x) to negate"
3432 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
3433 "convert (* x 0) to 0"
3436 ;;; Return T if in an arithmetic op including lvars X and Y, the
3437 ;;; result type is not affected by the type of X. That is, Y is at
3438 ;;; least as contagious as X.
3440 (defun not-more-contagious (x y)
3441 (declare (type continuation x y))
3442 (let ((x (lvar-type x))
3444 (values (type= (numeric-contagion x y)
3445 (numeric-contagion y y)))))
3446 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
3447 ;;; XXX needs more work as valid transforms are missed; some cases are
3448 ;;; specific to particular transform functions so the use of this
3449 ;;; function may need a re-think.
3450 (defun not-more-contagious (x y)
3451 (declare (type lvar x y))
3452 (flet ((simple-numeric-type (num)
3453 (and (numeric-type-p num)
3454 ;; Return non-NIL if NUM is integer, rational, or a float
3455 ;; of some type (but not FLOAT)
3456 (case (numeric-type-class num)
3460 (numeric-type-format num))
3463 (let ((x (lvar-type x))
3465 (if (and (simple-numeric-type x)
3466 (simple-numeric-type y))
3467 (values (type= (numeric-contagion x y)
3468 (numeric-contagion y y)))))))
3470 (def!type exact-number ()
3471 '(or rational (complex rational)))
3475 ;;; Only safely applicable for exact numbers. For floating-point
3476 ;;; x, one would have to first show that neither x or y are signed
3477 ;;; 0s, and that x isn't an SNaN.
3478 (deftransform + ((x y) (exact-number (constant-arg (eql 0))) *)
3483 (deftransform - ((x y) (exact-number (constant-arg (eql 0))) *)
3487 ;;; Fold (OP x +/-1)
3489 ;;; %NEGATE might not always signal correctly.
3491 ((def (name result minus-result)
3492 `(deftransform ,name ((x y)
3493 (exact-number (constant-arg (member 1 -1))))
3494 "fold identity operations"
3495 (if (minusp (lvar-value y)) ',minus-result ',result))))
3496 (def * x (%negate x))
3497 (def / x (%negate x))
3498 (def expt x (/ 1 x)))
3500 ;;; Fold (expt x n) into multiplications for small integral values of
3501 ;;; N; convert (expt x 1/2) to sqrt.
3502 (deftransform expt ((x y) (t (constant-arg real)) *)
3503 "recode as multiplication or sqrt"
3504 (let ((val (lvar-value y)))
3505 ;; If Y would cause the result to be promoted to the same type as
3506 ;; Y, we give up. If not, then the result will be the same type
3507 ;; as X, so we can replace the exponentiation with simple
3508 ;; multiplication and division for small integral powers.
3509 (unless (not-more-contagious y x)
3510 (give-up-ir1-transform))
3512 (let ((x-type (lvar-type x)))
3513 (cond ((csubtypep x-type (specifier-type '(or rational
3514 (complex rational))))
3516 ((csubtypep x-type (specifier-type 'real))
3520 ((csubtypep x-type (specifier-type 'complex))
3521 ;; both parts are float
3523 (t (give-up-ir1-transform)))))
3524 ((= val 2) '(* x x))
3525 ((= val -2) '(/ (* x x)))
3526 ((= val 3) '(* x x x))
3527 ((= val -3) '(/ (* x x x)))
3528 ((= val 1/2) '(sqrt x))
3529 ((= val -1/2) '(/ (sqrt x)))
3530 (t (give-up-ir1-transform)))))
3532 (deftransform expt ((x y) ((constant-arg (member -1 -1.0 -1.0d0)) integer) *)
3533 "recode as an ODDP check"
3534 (let ((val (lvar-value x)))
3536 '(- 1 (* 2 (logand 1 y)))
3541 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
3542 ;;; transformations?
3543 ;;; Perhaps we should have to prove that the denominator is nonzero before
3544 ;;; doing them? -- WHN 19990917
3545 (macrolet ((def (name)
3546 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3553 (macrolet ((def (name)
3554 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3563 ;;;; character operations
3565 (deftransform char-equal ((a b) (base-char base-char))
3567 '(let* ((ac (char-code a))
3569 (sum (logxor ac bc)))
3571 (when (eql sum #x20)
3572 (let ((sum (+ ac bc)))
3573 (or (and (> sum 161) (< sum 213))
3574 (and (> sum 415) (< sum 461))
3575 (and (> sum 463) (< sum 477))))))))
3577 (deftransform char-upcase ((x) (base-char))
3579 '(let ((n-code (char-code x)))
3580 (if (or (and (> n-code #o140) ; Octal 141 is #\a.
3581 (< n-code #o173)) ; Octal 172 is #\z.
3582 (and (> n-code #o337)
3584 (and (> n-code #o367)
3586 (code-char (logxor #x20 n-code))
3589 (deftransform char-downcase ((x) (base-char))
3591 '(let ((n-code (char-code x)))
3592 (if (or (and (> n-code 64) ; 65 is #\A.
3593 (< n-code 91)) ; 90 is #\Z.
3598 (code-char (logxor #x20 n-code))
3601 ;;;; equality predicate transforms
3603 ;;; Return true if X and Y are lvars whose only use is a
3604 ;;; reference to the same leaf, and the value of the leaf cannot
3606 (defun same-leaf-ref-p (x y)
3607 (declare (type lvar x y))
3608 (let ((x-use (principal-lvar-use x))
3609 (y-use (principal-lvar-use y)))
3612 (eq (ref-leaf x-use) (ref-leaf y-use))
3613 (constant-reference-p x-use))))
3615 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
3616 ;;; if there is no intersection between the types of the arguments,
3617 ;;; then the result is definitely false.
3618 (deftransform simple-equality-transform ((x y) * *
3621 ((same-leaf-ref-p x y) t)
3622 ((not (types-equal-or-intersect (lvar-type x) (lvar-type y)))
3624 (t (give-up-ir1-transform))))
3627 `(%deftransform ',x '(function * *) #'simple-equality-transform)))
3631 ;;; This is similar to SIMPLE-EQUALITY-TRANSFORM, except that we also
3632 ;;; try to convert to a type-specific predicate or EQ:
3633 ;;; -- If both args are characters, convert to CHAR=. This is better than
3634 ;;; just converting to EQ, since CHAR= may have special compilation
3635 ;;; strategies for non-standard representations, etc.
3636 ;;; -- If either arg is definitely a fixnum, we check to see if X is
3637 ;;; constant and if so, put X second. Doing this results in better
3638 ;;; code from the backend, since the backend assumes that any constant
3639 ;;; argument comes second.
3640 ;;; -- If either arg is definitely not a number or a fixnum, then we
3641 ;;; can compare with EQ.
3642 ;;; -- Otherwise, we try to put the arg we know more about second. If X
3643 ;;; is constant then we put it second. If X is a subtype of Y, we put
3644 ;;; it second. These rules make it easier for the back end to match
3645 ;;; these interesting cases.
3646 (deftransform eql ((x y) * * :node node)
3647 "convert to simpler equality predicate"
3648 (let ((x-type (lvar-type x))
3649 (y-type (lvar-type y))
3650 (char-type (specifier-type 'character)))
3651 (flet ((fixnum-type-p (type)
3652 (csubtypep type (specifier-type 'fixnum))))
3654 ((same-leaf-ref-p x y) t)
3655 ((not (types-equal-or-intersect x-type y-type))
3657 ((and (csubtypep x-type char-type)
3658 (csubtypep y-type char-type))
3660 ((or (fixnum-type-p x-type) (fixnum-type-p y-type))
3661 (commutative-arg-swap node))
3662 ((or (eq-comparable-type-p x-type) (eq-comparable-type-p y-type))
3664 ((and (not (constant-lvar-p y))
3665 (or (constant-lvar-p x)
3666 (and (csubtypep x-type y-type)
3667 (not (csubtypep y-type x-type)))))
3670 (give-up-ir1-transform))))))
3672 ;;; similarly to the EQL transform above, we attempt to constant-fold
3673 ;;; or convert to a simpler predicate: mostly we have to be careful
3674 ;;; with strings and bit-vectors.
3675 (deftransform equal ((x y) * *)
3676 "convert to simpler equality predicate"
3677 (let ((x-type (lvar-type x))
3678 (y-type (lvar-type y))
3679 (string-type (specifier-type 'string))
3680 (bit-vector-type (specifier-type 'bit-vector)))
3682 ((same-leaf-ref-p x y) t)
3683 ((and (csubtypep x-type string-type)
3684 (csubtypep y-type string-type))
3686 ((and (csubtypep x-type bit-vector-type)
3687 (csubtypep y-type bit-vector-type))
3688 '(bit-vector-= x y))
3689 ;; if at least one is not a string, and at least one is not a
3690 ;; bit-vector, then we can reason from types.
3691 ((and (not (and (types-equal-or-intersect x-type string-type)
3692 (types-equal-or-intersect y-type string-type)))
3693 (not (and (types-equal-or-intersect x-type bit-vector-type)
3694 (types-equal-or-intersect y-type bit-vector-type)))
3695 (not (types-equal-or-intersect x-type y-type)))
3697 (t (give-up-ir1-transform)))))
3699 ;;; Convert to EQL if both args are rational and complexp is specified
3700 ;;; and the same for both.
3701 (deftransform = ((x y) (number number) *)
3703 (let ((x-type (lvar-type x))
3704 (y-type (lvar-type y)))
3705 (cond ((or (and (csubtypep x-type (specifier-type 'float))
3706 (csubtypep y-type (specifier-type 'float)))
3707 (and (csubtypep x-type (specifier-type '(complex float)))
3708 (csubtypep y-type (specifier-type '(complex float))))
3709 #!+complex-float-vops
3710 (and (csubtypep x-type (specifier-type '(or single-float (complex single-float))))
3711 (csubtypep y-type (specifier-type '(or single-float (complex single-float)))))
3712 #!+complex-float-vops
3713 (and (csubtypep x-type (specifier-type '(or double-float (complex double-float))))
3714 (csubtypep y-type (specifier-type '(or double-float (complex double-float))))))
3715 ;; They are both floats. Leave as = so that -0.0 is
3716 ;; handled correctly.
3717 (give-up-ir1-transform))
3718 ((or (and (csubtypep x-type (specifier-type 'rational))
3719 (csubtypep y-type (specifier-type 'rational)))
3720 (and (csubtypep x-type
3721 (specifier-type '(complex rational)))
3723 (specifier-type '(complex rational)))))
3724 ;; They are both rationals and complexp is the same.
3728 (give-up-ir1-transform
3729 "The operands might not be the same type.")))))
3731 (defun maybe-float-lvar-p (lvar)
3732 (neq *empty-type* (type-intersection (specifier-type 'float)
3735 (flet ((maybe-invert (node op inverted x y)
3736 ;; Don't invert if either argument can be a float (NaNs)
3738 ((or (maybe-float-lvar-p x) (maybe-float-lvar-p y))
3739 (delay-ir1-transform node :constraint)
3740 `(or (,op x y) (= x y)))
3742 `(if (,inverted x y) nil t)))))
3743 (deftransform >= ((x y) (number number) * :node node)
3744 "invert or open code"
3745 (maybe-invert node '> '< x y))
3746 (deftransform <= ((x y) (number number) * :node node)
3747 "invert or open code"
3748 (maybe-invert node '< '> x y)))
3750 ;;; See whether we can statically determine (< X Y) using type
3751 ;;; information. If X's high bound is < Y's low, then X < Y.
3752 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
3753 ;;; NIL). If not, at least make sure any constant arg is second.
3754 (macrolet ((def (name inverse reflexive-p surely-true surely-false)
3755 `(deftransform ,name ((x y))
3756 "optimize using intervals"
3757 (if (and (same-leaf-ref-p x y)
3758 ;; For non-reflexive functions we don't need
3759 ;; to worry about NaNs: (non-ref-op NaN NaN) => false,
3760 ;; but with reflexive ones we don't know...
3762 '((and (not (maybe-float-lvar-p x))
3763 (not (maybe-float-lvar-p y))))))
3765 (let ((ix (or (type-approximate-interval (lvar-type x))
3766 (give-up-ir1-transform)))
3767 (iy (or (type-approximate-interval (lvar-type y))
3768 (give-up-ir1-transform))))
3773 ((and (constant-lvar-p x)
3774 (not (constant-lvar-p y)))
3777 (give-up-ir1-transform))))))))
3778 (def = = t (interval-= ix iy) (interval-/= ix iy))
3779 (def /= /= nil (interval-/= ix iy) (interval-= ix iy))
3780 (def < > nil (interval-< ix iy) (interval->= ix iy))
3781 (def > < nil (interval-< iy ix) (interval->= iy ix))
3782 (def <= >= t (interval->= iy ix) (interval-< iy ix))
3783 (def >= <= t (interval->= ix iy) (interval-< ix iy)))
3785 (defun ir1-transform-char< (x y first second inverse)
3787 ((same-leaf-ref-p x y) nil)
3788 ;; If we had interval representation of character types, as we
3789 ;; might eventually have to to support 2^21 characters, then here
3790 ;; we could do some compile-time computation as in transforms for
3791 ;; < above. -- CSR, 2003-07-01
3792 ((and (constant-lvar-p first)
3793 (not (constant-lvar-p second)))
3795 (t (give-up-ir1-transform))))
3797 (deftransform char< ((x y) (character character) *)
3798 (ir1-transform-char< x y x y 'char>))
3800 (deftransform char> ((x y) (character character) *)
3801 (ir1-transform-char< y x x y 'char<))
3803 ;;;; converting N-arg comparisons
3805 ;;;; We convert calls to N-arg comparison functions such as < into
3806 ;;;; two-arg calls. This transformation is enabled for all such
3807 ;;;; comparisons in this file. If any of these predicates are not
3808 ;;;; open-coded, then the transformation should be removed at some
3809 ;;;; point to avoid pessimization.
3811 ;;; This function is used for source transformation of N-arg
3812 ;;; comparison functions other than inequality. We deal both with
3813 ;;; converting to two-arg calls and inverting the sense of the test,
3814 ;;; if necessary. If the call has two args, then we pass or return a
3815 ;;; negated test as appropriate. If it is a degenerate one-arg call,
3816 ;;; then we transform to code that returns true. Otherwise, we bind
3817 ;;; all the arguments and expand into a bunch of IFs.
3818 (defun multi-compare (predicate args not-p type &optional force-two-arg-p)
3819 (let ((nargs (length args)))
3820 (cond ((< nargs 1) (values nil t))
3821 ((= nargs 1) `(progn (the ,type ,@args) t))
3824 `(if (,predicate ,(first args) ,(second args)) nil t)
3826 `(,predicate ,(first args) ,(second args))
3829 (do* ((i (1- nargs) (1- i))
3831 (current (gensym) (gensym))
3832 (vars (list current) (cons current vars))
3834 `(if (,predicate ,current ,last)
3836 `(if (,predicate ,current ,last)
3839 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3842 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
3843 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
3844 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
3845 ;;; We cannot do the inversion for >= and <= here, since both
3846 ;;; (< NaN X) and (> NaN X)
3847 ;;; are false, and we don't have type-inforation available yet. The
3848 ;;; deftransforms for two-argument versions of >= and <= takes care of
3849 ;;; the inversion to > and < when possible.
3850 (define-source-transform <= (&rest args) (multi-compare '<= args nil 'real))
3851 (define-source-transform >= (&rest args) (multi-compare '>= args nil 'real))
3853 (define-source-transform char= (&rest args) (multi-compare 'char= args nil
3855 (define-source-transform char< (&rest args) (multi-compare 'char< args nil
3857 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
3859 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
3861 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
3864 (define-source-transform char-equal (&rest args)
3865 (multi-compare 'sb!impl::two-arg-char-equal args nil 'character t))
3866 (define-source-transform char-lessp (&rest args)
3867 (multi-compare 'sb!impl::two-arg-char-lessp args nil 'character t))
3868 (define-source-transform char-greaterp (&rest args)
3869 (multi-compare 'sb!impl::two-arg-char-greaterp args nil 'character t))
3870 (define-source-transform char-not-greaterp (&rest args)
3871 (multi-compare 'sb!impl::two-arg-char-greaterp args t 'character t))
3872 (define-source-transform char-not-lessp (&rest args)
3873 (multi-compare 'sb!impl::two-arg-char-lessp args t 'character t))
3875 ;;; This function does source transformation of N-arg inequality
3876 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3877 ;;; arg cases. If there are more than two args, then we expand into
3878 ;;; the appropriate n^2 comparisons only when speed is important.
3879 (declaim (ftype (function (symbol list t) *) multi-not-equal))
3880 (defun multi-not-equal (predicate args type)
3881 (let ((nargs (length args)))
3882 (cond ((< nargs 1) (values nil t))
3883 ((= nargs 1) `(progn (the ,type ,@args) t))
3885 `(if (,predicate ,(first args) ,(second args)) nil t))
3886 ((not (policy *lexenv*
3887 (and (>= speed space)
3888 (>= speed compilation-speed))))
3891 (let ((vars (make-gensym-list nargs)))
3892 (do ((var vars next)
3893 (next (cdr vars) (cdr next))
3896 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3898 (let ((v1 (first var)))
3900 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3902 (define-source-transform /= (&rest args)
3903 (multi-not-equal '= args 'number))
3904 (define-source-transform char/= (&rest args)
3905 (multi-not-equal 'char= args 'character))
3906 (define-source-transform char-not-equal (&rest args)
3907 (multi-not-equal 'char-equal args 'character))
3909 ;;; Expand MAX and MIN into the obvious comparisons.
3910 (define-source-transform max (arg0 &rest rest)
3911 (once-only ((arg0 arg0))
3913 `(values (the real ,arg0))
3914 `(let ((maxrest (max ,@rest)))
3915 (if (>= ,arg0 maxrest) ,arg0 maxrest)))))
3916 (define-source-transform min (arg0 &rest rest)
3917 (once-only ((arg0 arg0))
3919 `(values (the real ,arg0))
3920 `(let ((minrest (min ,@rest)))
3921 (if (<= ,arg0 minrest) ,arg0 minrest)))))
3923 ;;;; converting N-arg arithmetic functions
3925 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3926 ;;;; versions, and degenerate cases are flushed.
3928 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3929 (declaim (ftype (sfunction (symbol t list t) list) associate-args))
3930 (defun associate-args (fun first-arg more-args identity)
3931 (let ((next (rest more-args))
3932 (arg (first more-args)))
3934 `(,fun ,first-arg ,(if arg arg identity))
3935 (associate-args fun `(,fun ,first-arg ,arg) next identity))))
3937 ;;; Reduce constants in ARGS list.
3938 (declaim (ftype (sfunction (symbol list t symbol) list) reduce-constants))
3939 (defun reduce-constants (fun args identity one-arg-result-type)
3940 (let ((one-arg-constant-p (ecase one-arg-result-type
3942 (integer #'integerp)))
3943 (reduced-value identity)
3945 (collect ((not-constants))
3947 (if (funcall one-arg-constant-p arg)
3948 (setf reduced-value (funcall fun reduced-value arg)
3950 (not-constants arg)))
3951 ;; It is tempting to drop constants reduced to identity here,
3952 ;; but if X is SNaN in (* X 1), we cannot drop the 1.
3955 `(,reduced-value ,@(not-constants))
3957 `(,reduced-value)))))
3959 ;;; Do source transformations for transitive functions such as +.
3960 ;;; One-arg cases are replaced with the arg and zero arg cases with
3961 ;;; the identity. ONE-ARG-RESULT-TYPE is the type to ensure (with THE)
3962 ;;; that the argument in one-argument calls is.
3963 (declaim (ftype (function (symbol list t &optional symbol list)
3964 (values t &optional (member nil t)))
3965 source-transform-transitive))
3966 (defun source-transform-transitive (fun args identity
3967 &optional (one-arg-result-type 'number)
3968 (one-arg-prefixes '(values)))
3971 (1 `(,@one-arg-prefixes (the ,one-arg-result-type ,(first args))))
3973 (t (let ((reduced-args (reduce-constants fun args identity one-arg-result-type)))
3974 (associate-args fun (first reduced-args) (rest reduced-args) identity)))))
3976 (define-source-transform + (&rest args)
3977 (source-transform-transitive '+ args 0))
3978 (define-source-transform * (&rest args)
3979 (source-transform-transitive '* args 1))
3980 (define-source-transform logior (&rest args)
3981 (source-transform-transitive 'logior args 0 'integer))
3982 (define-source-transform logxor (&rest args)
3983 (source-transform-transitive 'logxor args 0 'integer))
3984 (define-source-transform logand (&rest args)
3985 (source-transform-transitive 'logand args -1 'integer))
3986 (define-source-transform logeqv (&rest args)
3987 (source-transform-transitive 'logeqv args -1 'integer))
3988 (define-source-transform gcd (&rest args)
3989 (source-transform-transitive 'gcd args 0 'integer '(abs)))
3990 (define-source-transform lcm (&rest args)
3991 (source-transform-transitive 'lcm args 1 'integer '(abs)))
3993 ;;; Do source transformations for intransitive n-arg functions such as
3994 ;;; /. With one arg, we form the inverse. With two args we pass.
3995 ;;; Otherwise we associate into two-arg calls.
3996 (declaim (ftype (function (symbol symbol list t list &optional symbol)
3997 (values list &optional (member nil t)))
3998 source-transform-intransitive))
3999 (defun source-transform-intransitive (fun fun* args identity one-arg-prefixes
4000 &optional (one-arg-result-type 'number))
4002 ((0 2) (values nil t))
4003 (1 `(,@one-arg-prefixes (the ,one-arg-result-type ,(first args))))
4004 (t (let ((reduced-args
4005 (reduce-constants fun* (rest args) identity one-arg-result-type)))
4006 (associate-args fun (first args) reduced-args identity)))))
4008 (define-source-transform - (&rest args)
4009 (source-transform-intransitive '- '+ args 0 '(%negate)))
4010 (define-source-transform / (&rest args)
4011 (source-transform-intransitive '/ '* args 1 '(/ 1)))
4013 ;;;; transforming APPLY
4015 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
4016 ;;; only needs to understand one kind of variable-argument call. It is
4017 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
4018 (define-source-transform apply (fun arg &rest more-args)
4019 (let ((args (cons arg more-args)))
4020 `(multiple-value-call ,fun
4021 ,@(mapcar (lambda (x) `(values ,x)) (butlast args))
4022 (values-list ,(car (last args))))))
4024 ;;; When &REST argument are at play, we also have extra context and count
4025 ;;; arguments -- convert to %VALUES-LIST-OR-CONTEXT when possible, so that the
4026 ;;; deftransform can decide what to do after everything has been converted.
4027 (define-source-transform values-list (list)
4029 (let* ((var (lexenv-find list vars))
4030 (info (when (lambda-var-p var)
4031 (lambda-var-arg-info var))))
4033 (eq :rest (arg-info-kind info))
4034 (consp (arg-info-default info)))
4035 (destructuring-bind (context count &optional used) (arg-info-default info)
4036 (declare (ignore used))
4037 `(%values-list-or-context ,list ,context ,count))
4041 (deftransform %values-list-or-context ((list context count) * * :node node)
4042 (let* ((use (lvar-use list))
4043 (var (when (ref-p use) (ref-leaf use)))
4044 (home (when (lambda-var-p var) (lambda-var-home var)))
4045 (info (when (lambda-var-p var) (lambda-var-arg-info var))))
4046 (flet ((ref-good-for-more-context-p (ref)
4047 (let ((dest (principal-lvar-end (node-lvar ref))))
4048 (and (combination-p dest)
4049 ;; Uses outside VALUES-LIST will require a &REST list anyways,
4050 ;; to it's no use saving effort here -- plus they might modify
4051 ;; the list destructively.
4052 (eq '%values-list-or-context (lvar-fun-name (combination-fun dest)))
4053 ;; If the home lambda is different and isn't DX, it might
4054 ;; escape -- in which case using the more context isn't safe.
4055 (let ((clambda (node-home-lambda dest)))
4056 (or (eq home clambda)
4057 (leaf-dynamic-extent clambda)))))))
4060 (consp (arg-info-default info))
4061 (not (lambda-var-specvar var))
4062 (not (lambda-var-sets var))
4063 (every #'ref-good-for-more-context-p (lambda-var-refs var))
4064 (policy node (= 3 rest-conversion)))))
4066 (destructuring-bind (context count &optional used) (arg-info-default info)
4067 (declare (ignore used))
4068 (setf (arg-info-default info) (list context count t)))
4069 `(%more-arg-values context 0 count))
4072 (setf (arg-info-default info) t))
4073 `(values-list list)))))))
4076 ;;;; transforming FORMAT
4078 ;;;; If the control string is a compile-time constant, then replace it
4079 ;;;; with a use of the FORMATTER macro so that the control string is
4080 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
4081 ;;;; or T and the control string is a function (i.e. FORMATTER), then
4082 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
4084 ;;; for compile-time argument count checking.
4086 ;;; FIXME II: In some cases, type information could be correlated; for
4087 ;;; instance, ~{ ... ~} requires a list argument, so if the lvar-type
4088 ;;; of a corresponding argument is known and does not intersect the
4089 ;;; list type, a warning could be signalled.
4090 (defun check-format-args (string args fun)
4091 (declare (type string string))
4092 (unless (typep string 'simple-string)
4093 (setq string (coerce string 'simple-string)))
4094 (multiple-value-bind (min max)
4095 (handler-case (sb!format:%compiler-walk-format-string string args)
4096 (sb!format:format-error (c)
4097 (compiler-warn "~A" c)))
4099 (let ((nargs (length args)))
4102 (warn 'format-too-few-args-warning
4104 "Too few arguments (~D) to ~S ~S: requires at least ~D."
4105 :format-arguments (list nargs fun string min)))
4107 (warn 'format-too-many-args-warning
4109 "Too many arguments (~D) to ~S ~S: uses at most ~D."
4110 :format-arguments (list nargs fun string max))))))))
4112 (defoptimizer (format optimizer) ((dest control &rest args))
4113 (when (constant-lvar-p control)
4114 (let ((x (lvar-value control)))
4116 (check-format-args x args 'format)))))
4118 ;;; We disable this transform in the cross-compiler to save memory in
4119 ;;; the target image; most of the uses of FORMAT in the compiler are for
4120 ;;; error messages, and those don't need to be particularly fast.
4122 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
4123 :policy (>= speed space))
4124 (unless (constant-lvar-p control)
4125 (give-up-ir1-transform "The control string is not a constant."))
4126 (let ((arg-names (make-gensym-list (length args))))
4127 `(lambda (dest control ,@arg-names)
4128 (declare (ignore control))
4129 (format dest (formatter ,(lvar-value control)) ,@arg-names))))
4131 (deftransform format ((stream control &rest args) (stream function &rest t))
4132 (let ((arg-names (make-gensym-list (length args))))
4133 `(lambda (stream control ,@arg-names)
4134 (funcall control stream ,@arg-names)
4137 (deftransform format ((tee control &rest args) ((member t) function &rest t))
4138 (let ((arg-names (make-gensym-list (length args))))
4139 `(lambda (tee control ,@arg-names)
4140 (declare (ignore tee))
4141 (funcall control *standard-output* ,@arg-names)
4144 (deftransform pathname ((pathspec) (pathname) *)
4147 (deftransform pathname ((pathspec) (string) *)
4148 '(values (parse-namestring pathspec)))
4152 `(defoptimizer (,name optimizer) ((control &rest args))
4153 (when (constant-lvar-p control)
4154 (let ((x (lvar-value control)))
4156 (check-format-args x args ',name)))))))
4159 #+sb-xc-host ; Only we should be using these
4162 (def compiler-error)
4164 (def compiler-style-warn)
4165 (def compiler-notify)
4166 (def maybe-compiler-notify)
4169 (defoptimizer (cerror optimizer) ((report control &rest args))
4170 (when (and (constant-lvar-p control)
4171 (constant-lvar-p report))
4172 (let ((x (lvar-value control))
4173 (y (lvar-value report)))
4174 (when (and (stringp x) (stringp y))
4175 (multiple-value-bind (min1 max1)
4177 (sb!format:%compiler-walk-format-string x args)
4178 (sb!format:format-error (c)
4179 (compiler-warn "~A" c)))
4181 (multiple-value-bind (min2 max2)
4183 (sb!format:%compiler-walk-format-string y args)
4184 (sb!format:format-error (c)
4185 (compiler-warn "~A" c)))
4187 (let ((nargs (length args)))
4189 ((< nargs (min min1 min2))
4190 (warn 'format-too-few-args-warning
4192 "Too few arguments (~D) to ~S ~S ~S: ~
4193 requires at least ~D."
4195 (list nargs 'cerror y x (min min1 min2))))
4196 ((> nargs (max max1 max2))
4197 (warn 'format-too-many-args-warning
4199 "Too many arguments (~D) to ~S ~S ~S: ~
4202 (list nargs 'cerror y x (max max1 max2))))))))))))))
4204 (defoptimizer (coerce derive-type) ((value type) node)
4206 ((constant-lvar-p type)
4207 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
4208 ;; but dealing with the niggle that complex canonicalization gets
4209 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
4211 (let* ((specifier (lvar-value type))
4212 (result-typeoid (careful-specifier-type specifier)))
4214 ((null result-typeoid) nil)
4215 ((csubtypep result-typeoid (specifier-type 'number))
4216 ;; the difficult case: we have to cope with ANSI 12.1.5.3
4217 ;; Rule of Canonical Representation for Complex Rationals,
4218 ;; which is a truly nasty delivery to field.
4220 ((csubtypep result-typeoid (specifier-type 'real))
4221 ;; cleverness required here: it would be nice to deduce
4222 ;; that something of type (INTEGER 2 3) coerced to type
4223 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
4224 ;; FLOAT gets its own clause because it's implemented as
4225 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
4228 ((and (numeric-type-p result-typeoid)
4229 (eq (numeric-type-complexp result-typeoid) :real))
4230 ;; FIXME: is this clause (a) necessary or (b) useful?
4232 ((or (csubtypep result-typeoid
4233 (specifier-type '(complex single-float)))
4234 (csubtypep result-typeoid
4235 (specifier-type '(complex double-float)))
4237 (csubtypep result-typeoid
4238 (specifier-type '(complex long-float))))
4239 ;; float complex types are never canonicalized.
4242 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
4243 ;; probably just a COMPLEX or equivalent. So, in that
4244 ;; case, we will return a complex or an object of the
4245 ;; provided type if it's rational:
4246 (type-union result-typeoid
4247 (type-intersection (lvar-type value)
4248 (specifier-type 'rational))))))
4249 ((and (policy node (zerop safety))
4250 (csubtypep result-typeoid (specifier-type '(array * (*)))))
4251 ;; At zero safety the deftransform for COERCE can elide dimension
4252 ;; checks for the things like (COERCE X '(SIMPLE-VECTOR 5)) -- so we
4253 ;; need to simplify the type to drop the dimension information.
4254 (let ((vtype (simplify-vector-type result-typeoid)))
4256 (specifier-type vtype)
4261 ;; OK, the result-type argument isn't constant. However, there
4262 ;; are common uses where we can still do better than just
4263 ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
4264 ;; where Y is of a known type. See messages on cmucl-imp
4265 ;; 2001-02-14 and sbcl-devel 2002-12-12. We only worry here
4266 ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
4267 ;; the basis that it's unlikely that other uses are both
4268 ;; time-critical and get to this branch of the COND (non-constant
4269 ;; second argument to COERCE). -- CSR, 2002-12-16
4270 (let ((value-type (lvar-type value))
4271 (type-type (lvar-type type)))
4273 ((good-cons-type-p (cons-type)
4274 ;; Make sure the cons-type we're looking at is something
4275 ;; we're prepared to handle which is basically something
4276 ;; that array-element-type can return.
4277 (or (and (member-type-p cons-type)
4278 (eql 1 (member-type-size cons-type))
4279 (null (first (member-type-members cons-type))))
4280 (let ((car-type (cons-type-car-type cons-type)))
4281 (and (member-type-p car-type)
4282 (eql 1 (member-type-members car-type))
4283 (let ((elt (first (member-type-members car-type))))
4287 (numberp (first elt)))))
4288 (good-cons-type-p (cons-type-cdr-type cons-type))))))
4289 (unconsify-type (good-cons-type)
4290 ;; Convert the "printed" respresentation of a cons
4291 ;; specifier into a type specifier. That is, the
4292 ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
4293 ;; NULL)) is converted to (SIGNED-BYTE 16).
4294 (cond ((or (null good-cons-type)
4295 (eq good-cons-type 'null))
4297 ((and (eq (first good-cons-type) 'cons)
4298 (eq (first (second good-cons-type)) 'member))
4299 `(,(second (second good-cons-type))
4300 ,@(unconsify-type (caddr good-cons-type))))))
4301 (coerceable-p (part)
4302 ;; Can the value be coerced to the given type? Coerce is
4303 ;; complicated, so we don't handle every possible case
4304 ;; here---just the most common and easiest cases:
4306 ;; * Any REAL can be coerced to a FLOAT type.
4307 ;; * Any NUMBER can be coerced to a (COMPLEX
4308 ;; SINGLE/DOUBLE-FLOAT).
4310 ;; FIXME I: we should also be able to deal with characters
4313 ;; FIXME II: I'm not sure that anything is necessary
4314 ;; here, at least while COMPLEX is not a specialized
4315 ;; array element type in the system. Reasoning: if
4316 ;; something cannot be coerced to the requested type, an
4317 ;; error will be raised (and so any downstream compiled
4318 ;; code on the assumption of the returned type is
4319 ;; unreachable). If something can, then it will be of
4320 ;; the requested type, because (by assumption) COMPLEX
4321 ;; (and other difficult types like (COMPLEX INTEGER)
4322 ;; aren't specialized types.
4323 (let ((coerced-type (careful-specifier-type part)))
4325 (or (and (csubtypep coerced-type (specifier-type 'float))
4326 (csubtypep value-type (specifier-type 'real)))
4327 (and (csubtypep coerced-type
4328 (specifier-type `(or (complex single-float)
4329 (complex double-float))))
4330 (csubtypep value-type (specifier-type 'number)))))))
4331 (process-types (type)
4332 ;; FIXME: This needs some work because we should be able
4333 ;; to derive the resulting type better than just the
4334 ;; type arg of coerce. That is, if X is (INTEGER 10
4335 ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
4336 ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
4338 (cond ((member-type-p type)
4341 (mapc-member-type-members
4343 (if (coerceable-p member)
4344 (push member members)
4345 (return-from punt *universal-type*)))
4347 (specifier-type `(or ,@members)))))
4348 ((and (cons-type-p type)
4349 (good-cons-type-p type))
4350 (let ((c-type (unconsify-type (type-specifier type))))
4351 (if (coerceable-p c-type)
4352 (specifier-type c-type)
4355 *universal-type*))))
4356 (cond ((union-type-p type-type)
4357 (apply #'type-union (mapcar #'process-types
4358 (union-type-types type-type))))
4359 ((or (member-type-p type-type)
4360 (cons-type-p type-type))
4361 (process-types type-type))
4363 *universal-type*)))))))
4365 (defoptimizer (compile derive-type) ((nameoid function))
4366 (when (csubtypep (lvar-type nameoid)
4367 (specifier-type 'null))
4368 (values-specifier-type '(values function boolean boolean))))
4370 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
4371 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
4372 ;;; optimizer, above).
4373 (defoptimizer (array-element-type derive-type) ((array))
4374 (let ((array-type (lvar-type array)))
4375 (labels ((consify (list)
4378 `(cons (eql ,(car list)) ,(consify (rest list)))))
4379 (get-element-type (a)
4381 (type-specifier (array-type-specialized-element-type a))))
4382 (cond ((eq element-type '*)
4383 (specifier-type 'type-specifier))
4384 ((symbolp element-type)
4385 (make-member-type :members (list element-type)))
4386 ((consp element-type)
4387 (specifier-type (consify element-type)))
4389 (error "can't understand type ~S~%" element-type))))))
4390 (labels ((recurse (type)
4391 (cond ((array-type-p type)
4392 (get-element-type type))
4393 ((union-type-p type)
4395 (mapcar #'recurse (union-type-types type))))
4397 *universal-type*))))
4398 (recurse array-type)))))
4400 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
4401 ;; Like CMU CL, we use HEAPSORT. However, other than that, this code
4402 ;; isn't really related to the CMU CL code, since instead of trying
4403 ;; to generalize the CMU CL code to allow START and END values, this
4404 ;; code has been written from scratch following Chapter 7 of
4405 ;; _Introduction to Algorithms_ by Corman, Rivest, and Shamir.
4406 `(macrolet ((%index (x) `(truly-the index ,x))
4407 (%parent (i) `(ash ,i -1))
4408 (%left (i) `(%index (ash ,i 1)))
4409 (%right (i) `(%index (1+ (ash ,i 1))))
4412 (left (%left i) (%left i)))
4413 ((> left current-heap-size))
4414 (declare (type index i left))
4415 (let* ((i-elt (%elt i))
4416 (i-key (funcall keyfun i-elt))
4417 (left-elt (%elt left))
4418 (left-key (funcall keyfun left-elt)))
4419 (multiple-value-bind (large large-elt large-key)
4420 (if (funcall ,',predicate i-key left-key)
4421 (values left left-elt left-key)
4422 (values i i-elt i-key))
4423 (let ((right (%right i)))
4424 (multiple-value-bind (largest largest-elt)
4425 (if (> right current-heap-size)
4426 (values large large-elt)
4427 (let* ((right-elt (%elt right))
4428 (right-key (funcall keyfun right-elt)))
4429 (if (funcall ,',predicate large-key right-key)
4430 (values right right-elt)
4431 (values large large-elt))))
4432 (cond ((= largest i)
4435 (setf (%elt i) largest-elt
4436 (%elt largest) i-elt
4438 (%sort-vector (keyfun &optional (vtype 'vector))
4439 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had
4440 ;; trouble getting type inference to
4441 ;; propagate all the way through this
4442 ;; tangled mess of inlining. The TRULY-THE
4443 ;; here works around that. -- WHN
4445 `(aref (truly-the ,',vtype ,',',vector)
4446 (%index (+ (%index ,i) start-1)))))
4447 (let (;; Heaps prefer 1-based addressing.
4448 (start-1 (1- ,',start))
4449 (current-heap-size (- ,',end ,',start))
4451 (declare (type (integer -1 #.(1- sb!xc:most-positive-fixnum))
4453 (declare (type index current-heap-size))
4454 (declare (type function keyfun))
4455 (loop for i of-type index
4456 from (ash current-heap-size -1) downto 1 do
4459 (when (< current-heap-size 2)
4461 (rotatef (%elt 1) (%elt current-heap-size))
4462 (decf current-heap-size)
4464 (if (typep ,vector 'simple-vector)
4465 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
4466 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
4468 ;; Special-casing the KEY=NIL case lets us avoid some
4470 (%sort-vector #'identity simple-vector)
4471 (%sort-vector ,key simple-vector))
4472 ;; It's hard to anticipate many speed-critical applications for
4473 ;; sorting vector types other than (VECTOR T), so we just lump
4474 ;; them all together in one slow dynamically typed mess.
4476 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
4477 (%sort-vector (or ,key #'identity))))))
4479 ;;;; debuggers' little helpers
4481 ;;; for debugging when transforms are behaving mysteriously,
4482 ;;; e.g. when debugging a problem with an ASH transform
4483 ;;; (defun foo (&optional s)
4484 ;;; (sb-c::/report-lvar s "S outside WHEN")
4485 ;;; (when (and (integerp s) (> s 3))
4486 ;;; (sb-c::/report-lvar s "S inside WHEN")
4487 ;;; (let ((bound (ash 1 (1- s))))
4488 ;;; (sb-c::/report-lvar bound "BOUND")
4489 ;;; (let ((x (- bound))
4491 ;;; (sb-c::/report-lvar x "X")
4492 ;;; (sb-c::/report-lvar x "Y"))
4493 ;;; `(integer ,(- bound) ,(1- bound)))))
4494 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
4495 ;;; and the function doesn't do anything at all.)
4498 (defknown /report-lvar (t t) null)
4499 (deftransform /report-lvar ((x message) (t t))
4500 (format t "~%/in /REPORT-LVAR~%")
4501 (format t "/(LVAR-TYPE X)=~S~%" (lvar-type x))
4502 (when (constant-lvar-p x)
4503 (format t "/(LVAR-VALUE X)=~S~%" (lvar-value x)))
4504 (format t "/MESSAGE=~S~%" (lvar-value message))
4505 (give-up-ir1-transform "not a real transform"))
4506 (defun /report-lvar (x message)
4507 (declare (ignore x message))))
4510 ;;;; Transforms for internal compiler utilities
4512 ;;; If QUALITY-NAME is constant and a valid name, don't bother
4513 ;;; checking that it's still valid at run-time.
4514 (deftransform policy-quality ((policy quality-name)
4516 (unless (and (constant-lvar-p quality-name)
4517 (policy-quality-name-p (lvar-value quality-name)))
4518 (give-up-ir1-transform))
4519 '(%policy-quality policy quality-name))