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.")))))
62 ;;; Translate CxR into CAR/CDR combos.
63 (defun source-transform-cxr (form)
64 (if (/= (length form) 2)
66 (let* ((name (car form))
70 (leaf (leaf-source-name name))))))
71 (do ((i (- (length string) 2) (1- i))
73 `(,(ecase (char string i)
79 ;;; Make source transforms to turn CxR forms into combinations of CAR
80 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
82 (/show0 "about to set CxR source transforms")
83 (loop for i of-type index from 2 upto 4 do
84 ;; Iterate over BUF = all names CxR where x = an I-element
85 ;; string of #\A or #\D characters.
86 (let ((buf (make-string (+ 2 i))))
87 (setf (aref buf 0) #\C
88 (aref buf (1+ i)) #\R)
89 (dotimes (j (ash 2 i))
90 (declare (type index j))
92 (declare (type index k))
93 (setf (aref buf (1+ k))
94 (if (logbitp k j) #\A #\D)))
95 (setf (info :function :source-transform (intern buf))
96 #'source-transform-cxr))))
97 (/show0 "done setting CxR source transforms")
99 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
100 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
101 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
103 (define-source-transform first (x) `(car ,x))
104 (define-source-transform rest (x) `(cdr ,x))
105 (define-source-transform second (x) `(cadr ,x))
106 (define-source-transform third (x) `(caddr ,x))
107 (define-source-transform fourth (x) `(cadddr ,x))
108 (define-source-transform fifth (x) `(nth 4 ,x))
109 (define-source-transform sixth (x) `(nth 5 ,x))
110 (define-source-transform seventh (x) `(nth 6 ,x))
111 (define-source-transform eighth (x) `(nth 7 ,x))
112 (define-source-transform ninth (x) `(nth 8 ,x))
113 (define-source-transform tenth (x) `(nth 9 ,x))
115 ;;; LIST with one arg is an extremely common operation (at least inside
116 ;;; SBCL itself); translate it to CONS to take advantage of common
117 ;;; allocation routines.
118 (define-source-transform list (&rest args)
120 (1 `(cons ,(first args) nil))
123 ;;; And similarly for LIST*.
124 (define-source-transform list* (arg &rest others)
125 (cond ((not others) arg)
126 ((not (cdr others)) `(cons ,arg ,(car others)))
129 (defoptimizer (list* derive-type) ((arg &rest args))
131 (specifier-type 'cons)
134 ;;; Translate RPLACx to LET and SETF.
135 (define-source-transform rplaca (x y)
140 (define-source-transform rplacd (x y)
146 (define-source-transform nth (n l) `(car (nthcdr ,n ,l)))
148 (deftransform last ((list &optional n) (t &optional t))
149 (let ((c (constant-lvar-p n)))
151 (and c (eql 1 (lvar-value n))))
153 ((and c (eql 0 (lvar-value n)))
156 (let ((type (lvar-type n)))
157 (cond ((csubtypep type (specifier-type 'fixnum))
158 '(%lastn/fixnum list n))
159 ((csubtypep type (specifier-type 'bignum))
160 '(%lastn/bignum list n))
162 (give-up-ir1-transform "second argument type too vague"))))))))
164 (define-source-transform gethash (&rest args)
166 (2 `(sb!impl::gethash3 ,@args nil))
167 (3 `(sb!impl::gethash3 ,@args))
169 (define-source-transform get (&rest args)
171 (2 `(sb!impl::get2 ,@args))
172 (3 `(sb!impl::get3 ,@args))
175 (defvar *default-nthcdr-open-code-limit* 6)
176 (defvar *extreme-nthcdr-open-code-limit* 20)
178 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
179 "convert NTHCDR to CAxxR"
180 (unless (constant-lvar-p n)
181 (give-up-ir1-transform))
182 (let ((n (lvar-value n)))
184 (if (policy node (and (= speed 3) (= space 0)))
185 *extreme-nthcdr-open-code-limit*
186 *default-nthcdr-open-code-limit*))
187 (give-up-ir1-transform))
192 `(cdr ,(frob (1- n))))))
195 ;;;; arithmetic and numerology
197 (define-source-transform plusp (x) `(> ,x 0))
198 (define-source-transform minusp (x) `(< ,x 0))
199 (define-source-transform zerop (x) `(= ,x 0))
201 (define-source-transform 1+ (x) `(+ ,x 1))
202 (define-source-transform 1- (x) `(- ,x 1))
204 (define-source-transform oddp (x) `(logtest ,x 1))
205 (define-source-transform evenp (x) `(not (logtest ,x 1)))
207 ;;; Note that all the integer division functions are available for
208 ;;; inline expansion.
210 (macrolet ((deffrob (fun)
211 `(define-source-transform ,fun (x &optional (y nil y-p))
218 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
220 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
223 ;;; This used to be a source transform (hence the lack of restrictions
224 ;;; on the argument types), but we make it a regular transform so that
225 ;;; the VM has a chance to see the bare LOGTEST and potentiall choose
226 ;;; to implement it differently. --njf, 06-02-2006
227 (deftransform logtest ((x y) * *)
228 `(not (zerop (logand x y))))
230 (deftransform logbitp
231 ((index integer) (unsigned-byte (or (signed-byte #.sb!vm:n-word-bits)
232 (unsigned-byte #.sb!vm:n-word-bits))))
233 `(if (>= index #.sb!vm:n-word-bits)
235 (not (zerop (logand integer (ash 1 index))))))
237 (define-source-transform byte (size position)
238 `(cons ,size ,position))
239 (define-source-transform byte-size (spec) `(car ,spec))
240 (define-source-transform byte-position (spec) `(cdr ,spec))
241 (define-source-transform ldb-test (bytespec integer)
242 `(not (zerop (mask-field ,bytespec ,integer))))
244 ;;; With the ratio and complex accessors, we pick off the "identity"
245 ;;; case, and use a primitive to handle the cell access case.
246 (define-source-transform numerator (num)
247 (once-only ((n-num `(the rational ,num)))
251 (define-source-transform denominator (num)
252 (once-only ((n-num `(the rational ,num)))
254 (%denominator ,n-num)
257 ;;;; interval arithmetic for computing bounds
259 ;;;; This is a set of routines for operating on intervals. It
260 ;;;; implements a simple interval arithmetic package. Although SBCL
261 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
262 ;;;; for two reasons:
264 ;;;; 1. This package is simpler than NUMERIC-TYPE.
266 ;;;; 2. It makes debugging much easier because you can just strip
267 ;;;; out these routines and test them independently of SBCL. (This is a
270 ;;;; One disadvantage is a probable increase in consing because we
271 ;;;; have to create these new interval structures even though
272 ;;;; numeric-type has everything we want to know. Reason 2 wins for
275 ;;; Support operations that mimic real arithmetic comparison
276 ;;; operators, but imposing a total order on the floating points such
277 ;;; that negative zeros are strictly less than positive zeros.
278 (macrolet ((def (name op)
281 (if (and (floatp x) (floatp y) (zerop x) (zerop y))
282 (,op (float-sign x) (float-sign y))
284 (def signed-zero->= >=)
285 (def signed-zero-> >)
286 (def signed-zero-= =)
287 (def signed-zero-< <)
288 (def signed-zero-<= <=))
290 ;;; The basic interval type. It can handle open and closed intervals.
291 ;;; A bound is open if it is a list containing a number, just like
292 ;;; Lisp says. NIL means unbounded.
293 (defstruct (interval (:constructor %make-interval)
297 (defun make-interval (&key low high)
298 (labels ((normalize-bound (val)
301 (float-infinity-p val))
302 ;; Handle infinities.
306 ;; Handle any closed bounds.
309 ;; We have an open bound. Normalize the numeric
310 ;; bound. If the normalized bound is still a number
311 ;; (not nil), keep the bound open. Otherwise, the
312 ;; bound is really unbounded, so drop the openness.
313 (let ((new-val (normalize-bound (first val))))
315 ;; The bound exists, so keep it open still.
318 (error "unknown bound type in MAKE-INTERVAL")))))
319 (%make-interval :low (normalize-bound low)
320 :high (normalize-bound high))))
322 ;;; Given a number X, create a form suitable as a bound for an
323 ;;; interval. Make the bound open if OPEN-P is T. NIL remains NIL.
324 #!-sb-fluid (declaim (inline set-bound))
325 (defun set-bound (x open-p)
326 (if (and x open-p) (list x) x))
328 ;;; Apply the function F to a bound X. If X is an open bound, then
329 ;;; the result will be open. IF X is NIL, the result is NIL.
330 (defun bound-func (f x)
331 (declare (type function f))
333 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
334 ;; With these traps masked, we might get things like infinity
335 ;; or negative infinity returned. Check for this and return
336 ;; NIL to indicate unbounded.
337 (let ((y (funcall f (type-bound-number x))))
339 (float-infinity-p y))
341 (set-bound y (consp x)))))))
343 (defun safe-double-coercion-p (x)
344 (or (typep x 'double-float)
345 (<= most-negative-double-float x most-positive-double-float)))
347 (defun safe-single-coercion-p (x)
348 (or (typep x 'single-float)
349 ;; Fix for bug 420, and related issues: during type derivation we often
350 ;; end up deriving types for both
352 ;; (some-op <int> <single>)
354 ;; (some-op (coerce <int> 'single-float) <single>)
356 ;; or other equivalent transformed forms. The problem with this is that
357 ;; on some platforms like x86 (+ <int> <single>) is on the machine level
360 ;; (coerce (+ (coerce <int> 'double-float)
361 ;; (coerce <single> 'double-float))
364 ;; so if the result of (coerce <int> 'single-float) is not exact, the
365 ;; derived types for the transformed forms will have an empty
366 ;; intersection -- which in turn means that the compiler will conclude
367 ;; that the call never returns, and all hell breaks lose when it *does*
368 ;; return at runtime. (This affects not just +, but other operators are
370 (and (not (typep x `(or (integer * (,most-negative-exactly-single-float-fixnum))
371 (integer (,most-positive-exactly-single-float-fixnum) *))))
372 (<= most-negative-single-float x most-positive-single-float))))
374 ;;; Apply a binary operator OP to two bounds X and Y. The result is
375 ;;; NIL if either is NIL. Otherwise bound is computed and the result
376 ;;; is open if either X or Y is open.
378 ;;; FIXME: only used in this file, not needed in target runtime
380 ;;; ANSI contaigon specifies coercion to floating point if one of the
381 ;;; arguments is floating point. Here we should check to be sure that
382 ;;; the other argument is within the bounds of that floating point
385 (defmacro safely-binop (op x y)
387 ((typep ,x 'double-float)
388 (when (safe-double-coercion-p ,y)
390 ((typep ,y 'double-float)
391 (when (safe-double-coercion-p ,x)
393 ((typep ,x 'single-float)
394 (when (safe-single-coercion-p ,y)
396 ((typep ,y 'single-float)
397 (when (safe-single-coercion-p ,x)
401 (defmacro bound-binop (op x y)
403 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
404 (set-bound (safely-binop ,op (type-bound-number ,x)
405 (type-bound-number ,y))
406 (or (consp ,x) (consp ,y))))))
408 (defun coerce-for-bound (val type)
410 (list (coerce-for-bound (car val) type))
412 ((subtypep type 'double-float)
413 (if (<= most-negative-double-float val most-positive-double-float)
415 ((or (subtypep type 'single-float) (subtypep type 'float))
416 ;; coerce to float returns a single-float
417 (if (<= most-negative-single-float val most-positive-single-float)
419 (t (coerce val type)))))
421 (defun coerce-and-truncate-floats (val type)
424 (list (coerce-and-truncate-floats (car val) type))
426 ((subtypep type 'double-float)
427 (if (<= most-negative-double-float val most-positive-double-float)
429 (if (< val most-negative-double-float)
430 most-negative-double-float most-positive-double-float)))
431 ((or (subtypep type 'single-float) (subtypep type 'float))
432 ;; coerce to float returns a single-float
433 (if (<= most-negative-single-float val most-positive-single-float)
435 (if (< val most-negative-single-float)
436 most-negative-single-float most-positive-single-float)))
437 (t (coerce val type))))))
439 ;;; Convert a numeric-type object to an interval object.
440 (defun numeric-type->interval (x)
441 (declare (type numeric-type x))
442 (make-interval :low (numeric-type-low x)
443 :high (numeric-type-high x)))
445 (defun type-approximate-interval (type)
446 (declare (type ctype type))
447 (let ((types (prepare-arg-for-derive-type type))
450 (let ((type (if (member-type-p type)
451 (convert-member-type type)
453 (unless (numeric-type-p type)
454 (return-from type-approximate-interval nil))
455 (let ((interval (numeric-type->interval type)))
458 (interval-approximate-union result interval)
462 (defun copy-interval-limit (limit)
467 (defun copy-interval (x)
468 (declare (type interval x))
469 (make-interval :low (copy-interval-limit (interval-low x))
470 :high (copy-interval-limit (interval-high x))))
472 ;;; Given a point P contained in the interval X, split X into two
473 ;;; interval at the point P. If CLOSE-LOWER is T, then the left
474 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
475 ;;; contains P. You can specify both to be T or NIL.
476 (defun interval-split (p x &optional close-lower close-upper)
477 (declare (type number p)
479 (list (make-interval :low (copy-interval-limit (interval-low x))
480 :high (if close-lower p (list p)))
481 (make-interval :low (if close-upper (list p) p)
482 :high (copy-interval-limit (interval-high x)))))
484 ;;; Return the closure of the interval. That is, convert open bounds
485 ;;; to closed bounds.
486 (defun interval-closure (x)
487 (declare (type interval x))
488 (make-interval :low (type-bound-number (interval-low x))
489 :high (type-bound-number (interval-high x))))
491 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
492 ;;; '-. Otherwise return NIL.
493 (defun interval-range-info (x &optional (point 0))
494 (declare (type interval x))
495 (let ((lo (interval-low x))
496 (hi (interval-high x)))
497 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
499 ((and hi (signed-zero->= point (type-bound-number hi)))
504 ;;; Test to see whether the interval X is bounded. HOW determines the
505 ;;; test, and should be either ABOVE, BELOW, or BOTH.
506 (defun interval-bounded-p (x how)
507 (declare (type interval x))
514 (and (interval-low x) (interval-high x)))))
516 ;;; See whether the interval X contains the number P, taking into
517 ;;; account that the interval might not be closed.
518 (defun interval-contains-p (p x)
519 (declare (type number p)
521 ;; Does the interval X contain the number P? This would be a lot
522 ;; easier if all intervals were closed!
523 (let ((lo (interval-low x))
524 (hi (interval-high x)))
526 ;; The interval is bounded
527 (if (and (signed-zero-<= (type-bound-number lo) p)
528 (signed-zero-<= p (type-bound-number hi)))
529 ;; P is definitely in the closure of the interval.
530 ;; We just need to check the end points now.
531 (cond ((signed-zero-= p (type-bound-number lo))
533 ((signed-zero-= p (type-bound-number hi))
538 ;; Interval with upper bound
539 (if (signed-zero-< p (type-bound-number hi))
541 (and (numberp hi) (signed-zero-= p hi))))
543 ;; Interval with lower bound
544 (if (signed-zero-> p (type-bound-number lo))
546 (and (numberp lo) (signed-zero-= p lo))))
548 ;; Interval with no bounds
551 ;;; Determine whether two intervals X and Y intersect. Return T if so.
552 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
553 ;;; were closed. Otherwise the intervals are treated as they are.
555 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
556 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
557 ;;; is T, then they do intersect because we use the closure of X = [0,
558 ;;; 1] and Y = [1, 2] to determine intersection.
559 (defun interval-intersect-p (x y &optional closed-intervals-p)
560 (declare (type interval x y))
561 (and (interval-intersection/difference (if closed-intervals-p
564 (if closed-intervals-p
569 ;;; Are the two intervals adjacent? That is, is there a number
570 ;;; between the two intervals that is not an element of either
571 ;;; interval? If so, they are not adjacent. For example [0, 1) and
572 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
573 ;;; between both intervals.
574 (defun interval-adjacent-p (x y)
575 (declare (type interval x y))
576 (flet ((adjacent (lo hi)
577 ;; Check to see whether lo and hi are adjacent. If either is
578 ;; nil, they can't be adjacent.
579 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
580 ;; The bounds are equal. They are adjacent if one of
581 ;; them is closed (a number). If both are open (consp),
582 ;; then there is a number that lies between them.
583 (or (numberp lo) (numberp hi)))))
584 (or (adjacent (interval-low y) (interval-high x))
585 (adjacent (interval-low x) (interval-high y)))))
587 ;;; Compute the intersection and difference between two intervals.
588 ;;; Two values are returned: the intersection and the difference.
590 ;;; Let the two intervals be X and Y, and let I and D be the two
591 ;;; values returned by this function. Then I = X intersect Y. If I
592 ;;; is NIL (the empty set), then D is X union Y, represented as the
593 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
594 ;;; - I, which is a list of two intervals.
596 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
597 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
598 (defun interval-intersection/difference (x y)
599 (declare (type interval x y))
600 (let ((x-lo (interval-low x))
601 (x-hi (interval-high x))
602 (y-lo (interval-low y))
603 (y-hi (interval-high y)))
606 ;; If p is an open bound, make it closed. If p is a closed
607 ;; bound, make it open.
611 (test-number (p int bound)
612 ;; Test whether P is in the interval.
613 (let ((pn (type-bound-number p)))
614 (when (interval-contains-p pn (interval-closure int))
615 ;; Check for endpoints.
616 (let* ((lo (interval-low int))
617 (hi (interval-high int))
618 (lon (type-bound-number lo))
619 (hin (type-bound-number hi)))
621 ;; Interval may be a point.
622 ((and lon hin (= lon hin pn))
623 (and (numberp p) (numberp lo) (numberp hi)))
624 ;; Point matches the low end.
625 ;; [P] [P,?} => TRUE [P] (P,?} => FALSE
626 ;; (P [P,?} => TRUE P) [P,?} => FALSE
627 ;; (P (P,?} => TRUE P) (P,?} => FALSE
628 ((and lon (= pn lon))
629 (or (and (numberp p) (numberp lo))
630 (and (consp p) (eq :low bound))))
631 ;; [P] {?,P] => TRUE [P] {?,P) => FALSE
632 ;; P) {?,P] => TRUE (P {?,P] => FALSE
633 ;; P) {?,P) => TRUE (P {?,P) => FALSE
634 ((and hin (= pn hin))
635 (or (and (numberp p) (numberp hi))
636 (and (consp p) (eq :high bound))))
637 ;; Not an endpoint, all is well.
640 (test-lower-bound (p int)
641 ;; P is a lower bound of an interval.
643 (test-number p int :low)
644 (not (interval-bounded-p int 'below))))
645 (test-upper-bound (p int)
646 ;; P is an upper bound of an interval.
648 (test-number p int :high)
649 (not (interval-bounded-p int 'above)))))
650 (let ((x-lo-in-y (test-lower-bound x-lo y))
651 (x-hi-in-y (test-upper-bound x-hi y))
652 (y-lo-in-x (test-lower-bound y-lo x))
653 (y-hi-in-x (test-upper-bound y-hi x)))
654 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
655 ;; Intervals intersect. Let's compute the intersection
656 ;; and the difference.
657 (multiple-value-bind (lo left-lo left-hi)
658 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
659 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
660 (multiple-value-bind (hi right-lo right-hi)
662 (values x-hi (opposite-bound x-hi) y-hi))
664 (values y-hi (opposite-bound y-hi) x-hi)))
665 (values (make-interval :low lo :high hi)
666 (list (make-interval :low left-lo
668 (make-interval :low right-lo
671 (values nil (list x y))))))))
673 ;;; If intervals X and Y intersect, return a new interval that is the
674 ;;; union of the two. If they do not intersect, return NIL.
675 (defun interval-merge-pair (x y)
676 (declare (type interval x y))
677 ;; If x and y intersect or are adjacent, create the union.
678 ;; Otherwise return nil
679 (when (or (interval-intersect-p x y)
680 (interval-adjacent-p x y))
681 (flet ((select-bound (x1 x2 min-op max-op)
682 (let ((x1-val (type-bound-number x1))
683 (x2-val (type-bound-number x2)))
685 ;; Both bounds are finite. Select the right one.
686 (cond ((funcall min-op x1-val x2-val)
687 ;; x1 is definitely better.
689 ((funcall max-op x1-val x2-val)
690 ;; x2 is definitely better.
693 ;; Bounds are equal. Select either
694 ;; value and make it open only if
696 (set-bound x1-val (and (consp x1) (consp x2))))))
698 ;; At least one bound is not finite. The
699 ;; non-finite bound always wins.
701 (let* ((x-lo (copy-interval-limit (interval-low x)))
702 (x-hi (copy-interval-limit (interval-high x)))
703 (y-lo (copy-interval-limit (interval-low y)))
704 (y-hi (copy-interval-limit (interval-high y))))
705 (make-interval :low (select-bound x-lo y-lo #'< #'>)
706 :high (select-bound x-hi y-hi #'> #'<))))))
708 ;;; return the minimal interval, containing X and Y
709 (defun interval-approximate-union (x y)
710 (cond ((interval-merge-pair x y))
712 (make-interval :low (copy-interval-limit (interval-low x))
713 :high (copy-interval-limit (interval-high y))))
715 (make-interval :low (copy-interval-limit (interval-low y))
716 :high (copy-interval-limit (interval-high x))))))
718 ;;; basic arithmetic operations on intervals. We probably should do
719 ;;; true interval arithmetic here, but it's complicated because we
720 ;;; have float and integer types and bounds can be open or closed.
722 ;;; the negative of an interval
723 (defun interval-neg (x)
724 (declare (type interval x))
725 (make-interval :low (bound-func #'- (interval-high x))
726 :high (bound-func #'- (interval-low x))))
728 ;;; Add two intervals.
729 (defun interval-add (x y)
730 (declare (type interval x y))
731 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
732 :high (bound-binop + (interval-high x) (interval-high y))))
734 ;;; Subtract two intervals.
735 (defun interval-sub (x y)
736 (declare (type interval x y))
737 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
738 :high (bound-binop - (interval-high x) (interval-low y))))
740 ;;; Multiply two intervals.
741 (defun interval-mul (x y)
742 (declare (type interval x y))
743 (flet ((bound-mul (x y)
744 (cond ((or (null x) (null y))
745 ;; Multiply by infinity is infinity
747 ((or (and (numberp x) (zerop x))
748 (and (numberp y) (zerop y)))
749 ;; Multiply by closed zero is special. The result
750 ;; is always a closed bound. But don't replace this
751 ;; with zero; we want the multiplication to produce
752 ;; the correct signed zero, if needed. Use SIGNUM
753 ;; to avoid trying to multiply huge bignums with 0.0.
754 (* (signum (type-bound-number x)) (signum (type-bound-number y))))
755 ((or (and (floatp x) (float-infinity-p x))
756 (and (floatp y) (float-infinity-p y)))
757 ;; Infinity times anything is infinity
760 ;; General multiply. The result is open if either is open.
761 (bound-binop * x y)))))
762 (let ((x-range (interval-range-info x))
763 (y-range (interval-range-info y)))
764 (cond ((null x-range)
765 ;; Split x into two and multiply each separately
766 (destructuring-bind (x- x+) (interval-split 0 x t t)
767 (interval-merge-pair (interval-mul x- y)
768 (interval-mul x+ y))))
770 ;; Split y into two and multiply each separately
771 (destructuring-bind (y- y+) (interval-split 0 y t t)
772 (interval-merge-pair (interval-mul x y-)
773 (interval-mul x y+))))
775 (interval-neg (interval-mul (interval-neg x) y)))
777 (interval-neg (interval-mul x (interval-neg y))))
778 ((and (eq x-range '+) (eq y-range '+))
779 ;; If we are here, X and Y are both positive.
781 :low (bound-mul (interval-low x) (interval-low y))
782 :high (bound-mul (interval-high x) (interval-high y))))
784 (bug "excluded case in INTERVAL-MUL"))))))
786 ;;; Divide two intervals.
787 (defun interval-div (top bot)
788 (declare (type interval top bot))
789 (flet ((bound-div (x y y-low-p)
792 ;; Divide by infinity means result is 0. However,
793 ;; we need to watch out for the sign of the result,
794 ;; to correctly handle signed zeros. We also need
795 ;; to watch out for positive or negative infinity.
796 (if (floatp (type-bound-number x))
798 (- (float-sign (type-bound-number x) 0.0))
799 (float-sign (type-bound-number x) 0.0))
801 ((zerop (type-bound-number y))
802 ;; Divide by zero means result is infinity
804 ((and (numberp x) (zerop x))
805 ;; Zero divided by anything is zero.
808 (bound-binop / x y)))))
809 (let ((top-range (interval-range-info top))
810 (bot-range (interval-range-info bot)))
811 (cond ((null bot-range)
812 ;; The denominator contains zero, so anything goes!
813 (make-interval :low nil :high nil))
815 ;; Denominator is negative so flip the sign, compute the
816 ;; result, and flip it back.
817 (interval-neg (interval-div top (interval-neg bot))))
819 ;; Split top into two positive and negative parts, and
820 ;; divide each separately
821 (destructuring-bind (top- top+) (interval-split 0 top t t)
822 (interval-merge-pair (interval-div top- bot)
823 (interval-div top+ bot))))
825 ;; Top is negative so flip the sign, divide, and flip the
826 ;; sign of the result.
827 (interval-neg (interval-div (interval-neg top) bot)))
828 ((and (eq top-range '+) (eq bot-range '+))
831 :low (bound-div (interval-low top) (interval-high bot) t)
832 :high (bound-div (interval-high top) (interval-low bot) nil)))
834 (bug "excluded case in INTERVAL-DIV"))))))
836 ;;; Apply the function F to the interval X. If X = [a, b], then the
837 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
838 ;;; result makes sense. It will if F is monotonic increasing (or
840 (defun interval-func (f x)
841 (declare (type function f)
843 (let ((lo (bound-func f (interval-low x)))
844 (hi (bound-func f (interval-high x))))
845 (make-interval :low lo :high hi)))
847 ;;; Return T if X < Y. That is every number in the interval X is
848 ;;; always less than any number in the interval Y.
849 (defun interval-< (x y)
850 (declare (type interval x y))
851 ;; X < Y only if X is bounded above, Y is bounded below, and they
853 (when (and (interval-bounded-p x 'above)
854 (interval-bounded-p y 'below))
855 ;; Intervals are bounded in the appropriate way. Make sure they
857 (let ((left (interval-high x))
858 (right (interval-low y)))
859 (cond ((> (type-bound-number left)
860 (type-bound-number right))
861 ;; The intervals definitely overlap, so result is NIL.
863 ((< (type-bound-number left)
864 (type-bound-number right))
865 ;; The intervals definitely don't touch, so result is T.
868 ;; Limits are equal. Check for open or closed bounds.
869 ;; Don't overlap if one or the other are open.
870 (or (consp left) (consp right)))))))
872 ;;; Return T if X >= Y. That is, every number in the interval X is
873 ;;; always greater than any number in the interval Y.
874 (defun interval->= (x y)
875 (declare (type interval x y))
876 ;; X >= Y if lower bound of X >= upper bound of Y
877 (when (and (interval-bounded-p x 'below)
878 (interval-bounded-p y 'above))
879 (>= (type-bound-number (interval-low x))
880 (type-bound-number (interval-high y)))))
882 ;;; Return T if X = Y.
883 (defun interval-= (x y)
884 (declare (type interval x y))
885 (and (interval-bounded-p x 'both)
886 (interval-bounded-p y 'both)
890 ;; Open intervals cannot be =
891 (return-from interval-= nil))))
892 ;; Both intervals refer to the same point
893 (= (bound (interval-high x)) (bound (interval-low x))
894 (bound (interval-high y)) (bound (interval-low y))))))
896 ;;; Return T if X /= Y
897 (defun interval-/= (x y)
898 (not (interval-intersect-p x y)))
900 ;;; Return an interval that is the absolute value of X. Thus, if
901 ;;; X = [-1 10], the result is [0, 10].
902 (defun interval-abs (x)
903 (declare (type interval x))
904 (case (interval-range-info x)
910 (destructuring-bind (x- x+) (interval-split 0 x t t)
911 (interval-merge-pair (interval-neg x-) x+)))))
913 ;;; Compute the square of an interval.
914 (defun interval-sqr (x)
915 (declare (type interval x))
916 (interval-func (lambda (x) (* x x))
919 ;;;; numeric DERIVE-TYPE methods
921 ;;; a utility for defining derive-type methods of integer operations. If
922 ;;; the types of both X and Y are integer types, then we compute a new
923 ;;; integer type with bounds determined Fun when applied to X and Y.
924 ;;; Otherwise, we use NUMERIC-CONTAGION.
925 (defun derive-integer-type-aux (x y fun)
926 (declare (type function fun))
927 (if (and (numeric-type-p x) (numeric-type-p y)
928 (eq (numeric-type-class x) 'integer)
929 (eq (numeric-type-class y) 'integer)
930 (eq (numeric-type-complexp x) :real)
931 (eq (numeric-type-complexp y) :real))
932 (multiple-value-bind (low high) (funcall fun x y)
933 (make-numeric-type :class 'integer
937 (numeric-contagion x y)))
939 (defun derive-integer-type (x y fun)
940 (declare (type lvar x y) (type function fun))
941 (let ((x (lvar-type x))
943 (derive-integer-type-aux x y fun)))
945 ;;; simple utility to flatten a list
946 (defun flatten-list (x)
947 (labels ((flatten-and-append (tree list)
948 (cond ((null tree) list)
949 ((atom tree) (cons tree list))
950 (t (flatten-and-append
951 (car tree) (flatten-and-append (cdr tree) list))))))
952 (flatten-and-append x nil)))
954 ;;; Take some type of lvar and massage it so that we get a list of the
955 ;;; constituent types. If ARG is *EMPTY-TYPE*, return NIL to indicate
957 (defun prepare-arg-for-derive-type (arg)
958 (flet ((listify (arg)
963 (union-type-types arg))
966 (unless (eq arg *empty-type*)
967 ;; Make sure all args are some type of numeric-type. For member
968 ;; types, convert the list of members into a union of equivalent
969 ;; single-element member-type's.
970 (let ((new-args nil))
971 (dolist (arg (listify arg))
972 (if (member-type-p arg)
973 ;; Run down the list of members and convert to a list of
975 (mapc-member-type-members
977 (push (if (numberp member)
978 (make-member-type :members (list member))
982 (push arg new-args)))
983 (unless (member *empty-type* new-args)
986 ;;; Convert from the standard type convention for which -0.0 and 0.0
987 ;;; are equal to an intermediate convention for which they are
988 ;;; considered different which is more natural for some of the
990 (defun convert-numeric-type (type)
991 (declare (type numeric-type type))
992 ;;; Only convert real float interval delimiters types.
993 (if (eq (numeric-type-complexp type) :real)
994 (let* ((lo (numeric-type-low type))
995 (lo-val (type-bound-number lo))
996 (lo-float-zero-p (and lo (floatp lo-val) (= lo-val 0.0)))
997 (hi (numeric-type-high type))
998 (hi-val (type-bound-number hi))
999 (hi-float-zero-p (and hi (floatp hi-val) (= hi-val 0.0))))
1000 (if (or lo-float-zero-p hi-float-zero-p)
1002 :class (numeric-type-class type)
1003 :format (numeric-type-format type)
1005 :low (if lo-float-zero-p
1007 (list (float 0.0 lo-val))
1008 (float (load-time-value (make-unportable-float :single-float-negative-zero)) lo-val))
1010 :high (if hi-float-zero-p
1012 (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val))
1019 ;;; Convert back from the intermediate convention for which -0.0 and
1020 ;;; 0.0 are considered different to the standard type convention for
1021 ;;; which and equal.
1022 (defun convert-back-numeric-type (type)
1023 (declare (type numeric-type type))
1024 ;;; Only convert real float interval delimiters types.
1025 (if (eq (numeric-type-complexp type) :real)
1026 (let* ((lo (numeric-type-low type))
1027 (lo-val (type-bound-number lo))
1029 (and lo (floatp lo-val) (= lo-val 0.0)
1030 (float-sign lo-val)))
1031 (hi (numeric-type-high type))
1032 (hi-val (type-bound-number hi))
1034 (and hi (floatp hi-val) (= hi-val 0.0)
1035 (float-sign hi-val))))
1037 ;; (float +0.0 +0.0) => (member 0.0)
1038 ;; (float -0.0 -0.0) => (member -0.0)
1039 ((and lo-float-zero-p hi-float-zero-p)
1040 ;; shouldn't have exclusive bounds here..
1041 (aver (and (not (consp lo)) (not (consp hi))))
1042 (if (= lo-float-zero-p hi-float-zero-p)
1043 ;; (float +0.0 +0.0) => (member 0.0)
1044 ;; (float -0.0 -0.0) => (member -0.0)
1045 (specifier-type `(member ,lo-val))
1046 ;; (float -0.0 +0.0) => (float 0.0 0.0)
1047 ;; (float +0.0 -0.0) => (float 0.0 0.0)
1048 (make-numeric-type :class (numeric-type-class type)
1049 :format (numeric-type-format type)
1055 ;; (float -0.0 x) => (float 0.0 x)
1056 ((and (not (consp lo)) (minusp lo-float-zero-p))
1057 (make-numeric-type :class (numeric-type-class type)
1058 :format (numeric-type-format type)
1060 :low (float 0.0 lo-val)
1062 ;; (float (+0.0) x) => (float (0.0) x)
1063 ((and (consp lo) (plusp lo-float-zero-p))
1064 (make-numeric-type :class (numeric-type-class type)
1065 :format (numeric-type-format type)
1067 :low (list (float 0.0 lo-val))
1070 ;; (float +0.0 x) => (or (member 0.0) (float (0.0) x))
1071 ;; (float (-0.0) x) => (or (member 0.0) (float (0.0) x))
1072 (list (make-member-type :members (list (float 0.0 lo-val)))
1073 (make-numeric-type :class (numeric-type-class type)
1074 :format (numeric-type-format type)
1076 :low (list (float 0.0 lo-val))
1080 ;; (float x +0.0) => (float x 0.0)
1081 ((and (not (consp hi)) (plusp hi-float-zero-p))
1082 (make-numeric-type :class (numeric-type-class type)
1083 :format (numeric-type-format type)
1086 :high (float 0.0 hi-val)))
1087 ;; (float x (-0.0)) => (float x (0.0))
1088 ((and (consp hi) (minusp hi-float-zero-p))
1089 (make-numeric-type :class (numeric-type-class type)
1090 :format (numeric-type-format type)
1093 :high (list (float 0.0 hi-val))))
1095 ;; (float x (+0.0)) => (or (member -0.0) (float x (0.0)))
1096 ;; (float x -0.0) => (or (member -0.0) (float x (0.0)))
1097 (list (make-member-type :members (list (float (load-time-value (make-unportable-float :single-float-negative-zero)) hi-val)))
1098 (make-numeric-type :class (numeric-type-class type)
1099 :format (numeric-type-format type)
1102 :high (list (float 0.0 hi-val)))))))
1108 ;;; Convert back a possible list of numeric types.
1109 (defun convert-back-numeric-type-list (type-list)
1112 (let ((results '()))
1113 (dolist (type type-list)
1114 (if (numeric-type-p type)
1115 (let ((result (convert-back-numeric-type type)))
1117 (setf results (append results result))
1118 (push result results)))
1119 (push type results)))
1122 (convert-back-numeric-type type-list))
1124 (convert-back-numeric-type-list (union-type-types type-list)))
1128 ;;; Take a list of types and return a canonical type specifier,
1129 ;;; combining any MEMBER types together. If both positive and negative
1130 ;;; MEMBER types are present they are converted to a float type.
1131 ;;; XXX This would be far simpler if the type-union methods could handle
1132 ;;; member/number unions.
1134 ;;; If we're about to generate an overly complex union of numeric types, start
1135 ;;; collapse the ranges together.
1137 ;;; FIXME: The MEMBER canonicalization parts of MAKE-DERIVED-UNION-TYPE and
1138 ;;; entire CONVERT-MEMBER-TYPE probably belong in the kernel's type logic,
1139 ;;; invoked always, instead of in the compiler, invoked only during some type
1141 (defvar *derived-numeric-union-complexity-limit* 6)
1143 (defun make-derived-union-type (type-list)
1144 (let ((xset (alloc-xset))
1147 (numeric-type *empty-type*))
1148 (dolist (type type-list)
1149 (cond ((member-type-p type)
1150 (mapc-member-type-members
1152 (if (fp-zero-p member)
1153 (unless (member member fp-zeroes)
1154 (pushnew member fp-zeroes))
1155 (add-to-xset member xset)))
1157 ((numeric-type-p type)
1158 (let ((*approximate-numeric-unions*
1159 (when (and (union-type-p numeric-type)
1160 (nthcdr *derived-numeric-union-complexity-limit*
1161 (union-type-types numeric-type)))
1163 (setf numeric-type (type-union type numeric-type))))
1165 (push type misc-types))))
1166 (if (and (xset-empty-p xset) (not fp-zeroes))
1167 (apply #'type-union numeric-type misc-types)
1168 (apply #'type-union (make-member-type :xset xset :fp-zeroes fp-zeroes)
1169 numeric-type misc-types))))
1171 ;;; Convert a member type with a single member to a numeric type.
1172 (defun convert-member-type (arg)
1173 (let* ((members (member-type-members arg))
1174 (member (first members))
1175 (member-type (type-of member)))
1176 (aver (not (rest members)))
1177 (specifier-type (cond ((typep member 'integer)
1178 `(integer ,member ,member))
1179 ((memq member-type '(short-float single-float
1180 double-float long-float))
1181 `(,member-type ,member ,member))
1185 ;;; This is used in defoptimizers for computing the resulting type of
1188 ;;; Given the lvar ARG, derive the resulting type using the
1189 ;;; DERIVE-FUN. DERIVE-FUN takes exactly one argument which is some
1190 ;;; "atomic" lvar type like numeric-type or member-type (containing
1191 ;;; just one element). It should return the resulting type, which can
1192 ;;; be a list of types.
1194 ;;; For the case of member types, if a MEMBER-FUN is given it is
1195 ;;; called to compute the result otherwise the member type is first
1196 ;;; converted to a numeric type and the DERIVE-FUN is called.
1197 (defun one-arg-derive-type (arg derive-fun member-fun
1198 &optional (convert-type t))
1199 (declare (type function derive-fun)
1200 (type (or null function) member-fun))
1201 (let ((arg-list (prepare-arg-for-derive-type (lvar-type arg))))
1207 (with-float-traps-masked
1208 (:underflow :overflow :divide-by-zero)
1210 `(eql ,(funcall member-fun
1211 (first (member-type-members x))))))
1212 ;; Otherwise convert to a numeric type.
1213 (let ((result-type-list
1214 (funcall derive-fun (convert-member-type x))))
1216 (convert-back-numeric-type-list result-type-list)
1217 result-type-list))))
1220 (convert-back-numeric-type-list
1221 (funcall derive-fun (convert-numeric-type x)))
1222 (funcall derive-fun x)))
1224 *universal-type*))))
1225 ;; Run down the list of args and derive the type of each one,
1226 ;; saving all of the results in a list.
1227 (let ((results nil))
1228 (dolist (arg arg-list)
1229 (let ((result (deriver arg)))
1231 (setf results (append results result))
1232 (push result results))))
1234 (make-derived-union-type results)
1235 (first results)))))))
1237 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1238 ;;; two arguments. DERIVE-FUN takes 3 args in this case: the two
1239 ;;; original args and a third which is T to indicate if the two args
1240 ;;; really represent the same lvar. This is useful for deriving the
1241 ;;; type of things like (* x x), which should always be positive. If
1242 ;;; we didn't do this, we wouldn't be able to tell.
1243 (defun two-arg-derive-type (arg1 arg2 derive-fun fun
1244 &optional (convert-type t))
1245 (declare (type function derive-fun fun))
1246 (flet ((deriver (x y same-arg)
1247 (cond ((and (member-type-p x) (member-type-p y))
1248 (let* ((x (first (member-type-members x)))
1249 (y (first (member-type-members y)))
1250 (result (ignore-errors
1251 (with-float-traps-masked
1252 (:underflow :overflow :divide-by-zero
1254 (funcall fun x y)))))
1255 (cond ((null result) *empty-type*)
1256 ((and (floatp result) (float-nan-p result))
1257 (make-numeric-type :class 'float
1258 :format (type-of result)
1261 (specifier-type `(eql ,result))))))
1262 ((and (member-type-p x) (numeric-type-p y))
1263 (let* ((x (convert-member-type x))
1264 (y (if convert-type (convert-numeric-type y) y))
1265 (result (funcall derive-fun x y same-arg)))
1267 (convert-back-numeric-type-list result)
1269 ((and (numeric-type-p x) (member-type-p y))
1270 (let* ((x (if convert-type (convert-numeric-type x) x))
1271 (y (convert-member-type y))
1272 (result (funcall derive-fun x y same-arg)))
1274 (convert-back-numeric-type-list result)
1276 ((and (numeric-type-p x) (numeric-type-p y))
1277 (let* ((x (if convert-type (convert-numeric-type x) x))
1278 (y (if convert-type (convert-numeric-type y) y))
1279 (result (funcall derive-fun x y same-arg)))
1281 (convert-back-numeric-type-list result)
1284 *universal-type*))))
1285 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1286 (a1 (prepare-arg-for-derive-type (lvar-type arg1)))
1287 (a2 (prepare-arg-for-derive-type (lvar-type arg2))))
1289 (let ((results nil))
1291 ;; Since the args are the same LVARs, just run down the
1294 (let ((result (deriver x x same-arg)))
1296 (setf results (append results result))
1297 (push result results))))
1298 ;; Try all pairwise combinations.
1301 (let ((result (or (deriver x y same-arg)
1302 (numeric-contagion x y))))
1304 (setf results (append results result))
1305 (push result results))))))
1307 (make-derived-union-type results)
1308 (first results)))))))
1310 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1312 (defoptimizer (+ derive-type) ((x y))
1313 (derive-integer-type
1320 (values (frob (numeric-type-low x) (numeric-type-low y))
1321 (frob (numeric-type-high x) (numeric-type-high y)))))))
1323 (defoptimizer (- derive-type) ((x y))
1324 (derive-integer-type
1331 (values (frob (numeric-type-low x) (numeric-type-high y))
1332 (frob (numeric-type-high x) (numeric-type-low y)))))))
1334 (defoptimizer (* derive-type) ((x y))
1335 (derive-integer-type
1338 (let ((x-low (numeric-type-low x))
1339 (x-high (numeric-type-high x))
1340 (y-low (numeric-type-low y))
1341 (y-high (numeric-type-high y)))
1342 (cond ((not (and x-low y-low))
1344 ((or (minusp x-low) (minusp y-low))
1345 (if (and x-high y-high)
1346 (let ((max (* (max (abs x-low) (abs x-high))
1347 (max (abs y-low) (abs y-high)))))
1348 (values (- max) max))
1351 (values (* x-low y-low)
1352 (if (and x-high y-high)
1356 (defoptimizer (/ derive-type) ((x y))
1357 (numeric-contagion (lvar-type x) (lvar-type y)))
1361 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1363 (defun +-derive-type-aux (x y same-arg)
1364 (if (and (numeric-type-real-p x)
1365 (numeric-type-real-p y))
1368 (let ((x-int (numeric-type->interval x)))
1369 (interval-add x-int x-int))
1370 (interval-add (numeric-type->interval x)
1371 (numeric-type->interval y))))
1372 (result-type (numeric-contagion x y)))
1373 ;; If the result type is a float, we need to be sure to coerce
1374 ;; the bounds into the correct type.
1375 (when (eq (numeric-type-class result-type) 'float)
1376 (setf result (interval-func
1378 (coerce-for-bound x (or (numeric-type-format result-type)
1382 :class (if (and (eq (numeric-type-class x) 'integer)
1383 (eq (numeric-type-class y) 'integer))
1384 ;; The sum of integers is always an integer.
1386 (numeric-type-class result-type))
1387 :format (numeric-type-format result-type)
1388 :low (interval-low result)
1389 :high (interval-high result)))
1390 ;; general contagion
1391 (numeric-contagion x y)))
1393 (defoptimizer (+ derive-type) ((x y))
1394 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1396 (defun --derive-type-aux (x y same-arg)
1397 (if (and (numeric-type-real-p x)
1398 (numeric-type-real-p y))
1400 ;; (- X X) is always 0.
1402 (make-interval :low 0 :high 0)
1403 (interval-sub (numeric-type->interval x)
1404 (numeric-type->interval y))))
1405 (result-type (numeric-contagion x y)))
1406 ;; If the result type is a float, we need to be sure to coerce
1407 ;; the bounds into the correct type.
1408 (when (eq (numeric-type-class result-type) 'float)
1409 (setf result (interval-func
1411 (coerce-for-bound x (or (numeric-type-format result-type)
1415 :class (if (and (eq (numeric-type-class x) 'integer)
1416 (eq (numeric-type-class y) 'integer))
1417 ;; The difference of integers is always an integer.
1419 (numeric-type-class result-type))
1420 :format (numeric-type-format result-type)
1421 :low (interval-low result)
1422 :high (interval-high result)))
1423 ;; general contagion
1424 (numeric-contagion x y)))
1426 (defoptimizer (- derive-type) ((x y))
1427 (two-arg-derive-type x y #'--derive-type-aux #'-))
1429 (defun *-derive-type-aux (x y same-arg)
1430 (if (and (numeric-type-real-p x)
1431 (numeric-type-real-p y))
1433 ;; (* X X) is always positive, so take care to do it right.
1435 (interval-sqr (numeric-type->interval x))
1436 (interval-mul (numeric-type->interval x)
1437 (numeric-type->interval y))))
1438 (result-type (numeric-contagion x y)))
1439 ;; If the result type is a float, we need to be sure to coerce
1440 ;; the bounds into the correct type.
1441 (when (eq (numeric-type-class result-type) 'float)
1442 (setf result (interval-func
1444 (coerce-for-bound x (or (numeric-type-format result-type)
1448 :class (if (and (eq (numeric-type-class x) 'integer)
1449 (eq (numeric-type-class y) 'integer))
1450 ;; The product of integers is always an integer.
1452 (numeric-type-class result-type))
1453 :format (numeric-type-format result-type)
1454 :low (interval-low result)
1455 :high (interval-high result)))
1456 (numeric-contagion x y)))
1458 (defoptimizer (* derive-type) ((x y))
1459 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1461 (defun /-derive-type-aux (x y same-arg)
1462 (if (and (numeric-type-real-p x)
1463 (numeric-type-real-p y))
1465 ;; (/ X X) is always 1, except if X can contain 0. In
1466 ;; that case, we shouldn't optimize the division away
1467 ;; because we want 0/0 to signal an error.
1469 (not (interval-contains-p
1470 0 (interval-closure (numeric-type->interval y)))))
1471 (make-interval :low 1 :high 1)
1472 (interval-div (numeric-type->interval x)
1473 (numeric-type->interval y))))
1474 (result-type (numeric-contagion x y)))
1475 ;; If the result type is a float, we need to be sure to coerce
1476 ;; the bounds into the correct type.
1477 (when (eq (numeric-type-class result-type) 'float)
1478 (setf result (interval-func
1480 (coerce-for-bound x (or (numeric-type-format result-type)
1483 (make-numeric-type :class (numeric-type-class result-type)
1484 :format (numeric-type-format result-type)
1485 :low (interval-low result)
1486 :high (interval-high result)))
1487 (numeric-contagion x y)))
1489 (defoptimizer (/ derive-type) ((x y))
1490 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1494 (defun ash-derive-type-aux (n-type shift same-arg)
1495 (declare (ignore same-arg))
1496 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1497 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1498 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1499 ;; two bignums yielding zero) and it's hard to avoid that
1500 ;; calculation in here.
1501 #+(and cmu sb-xc-host)
1502 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1503 (typep (numeric-type-high n-type) 'bignum))
1504 (or (typep (numeric-type-low shift) 'bignum)
1505 (typep (numeric-type-high shift) 'bignum)))
1506 (return-from ash-derive-type-aux *universal-type*))
1507 (flet ((ash-outer (n s)
1508 (when (and (fixnump s)
1510 (> s sb!xc:most-negative-fixnum))
1512 ;; KLUDGE: The bare 64's here should be related to
1513 ;; symbolic machine word size values somehow.
1516 (if (and (fixnump s)
1517 (> s sb!xc:most-negative-fixnum))
1519 (if (minusp n) -1 0))))
1520 (or (and (csubtypep n-type (specifier-type 'integer))
1521 (csubtypep shift (specifier-type 'integer))
1522 (let ((n-low (numeric-type-low n-type))
1523 (n-high (numeric-type-high n-type))
1524 (s-low (numeric-type-low shift))
1525 (s-high (numeric-type-high shift)))
1526 (make-numeric-type :class 'integer :complexp :real
1529 (ash-outer n-low s-high)
1530 (ash-inner n-low s-low)))
1533 (ash-inner n-high s-low)
1534 (ash-outer n-high s-high))))))
1537 (defoptimizer (ash derive-type) ((n shift))
1538 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1540 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1541 (macrolet ((frob (fun)
1542 `#'(lambda (type type2)
1543 (declare (ignore type2))
1544 (let ((lo (numeric-type-low type))
1545 (hi (numeric-type-high type)))
1546 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1548 (defoptimizer (%negate derive-type) ((num))
1549 (derive-integer-type num num (frob -))))
1551 (defun lognot-derive-type-aux (int)
1552 (derive-integer-type-aux int int
1553 (lambda (type type2)
1554 (declare (ignore type2))
1555 (let ((lo (numeric-type-low type))
1556 (hi (numeric-type-high type)))
1557 (values (if hi (lognot hi) nil)
1558 (if lo (lognot lo) nil)
1559 (numeric-type-class type)
1560 (numeric-type-format type))))))
1562 (defoptimizer (lognot derive-type) ((int))
1563 (lognot-derive-type-aux (lvar-type int)))
1565 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1566 (defoptimizer (%negate derive-type) ((num))
1567 (flet ((negate-bound (b)
1569 (set-bound (- (type-bound-number b))
1571 (one-arg-derive-type num
1573 (modified-numeric-type
1575 :low (negate-bound (numeric-type-high type))
1576 :high (negate-bound (numeric-type-low type))))
1579 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1580 (defoptimizer (abs derive-type) ((num))
1581 (let ((type (lvar-type num)))
1582 (if (and (numeric-type-p type)
1583 (eq (numeric-type-class type) 'integer)
1584 (eq (numeric-type-complexp type) :real))
1585 (let ((lo (numeric-type-low type))
1586 (hi (numeric-type-high type)))
1587 (make-numeric-type :class 'integer :complexp :real
1588 :low (cond ((and hi (minusp hi))
1594 :high (if (and hi lo)
1595 (max (abs hi) (abs lo))
1597 (numeric-contagion type type))))
1599 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1600 (defun abs-derive-type-aux (type)
1601 (cond ((eq (numeric-type-complexp type) :complex)
1602 ;; The absolute value of a complex number is always a
1603 ;; non-negative float.
1604 (let* ((format (case (numeric-type-class type)
1605 ((integer rational) 'single-float)
1606 (t (numeric-type-format type))))
1607 (bound-format (or format 'float)))
1608 (make-numeric-type :class 'float
1611 :low (coerce 0 bound-format)
1614 ;; The absolute value of a real number is a non-negative real
1615 ;; of the same type.
1616 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1617 (class (numeric-type-class type))
1618 (format (numeric-type-format type))
1619 (bound-type (or format class 'real)))
1624 :low (coerce-and-truncate-floats (interval-low abs-bnd) bound-type)
1625 :high (coerce-and-truncate-floats
1626 (interval-high abs-bnd) bound-type))))))
1628 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1629 (defoptimizer (abs derive-type) ((num))
1630 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1632 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1633 (defoptimizer (truncate derive-type) ((number divisor))
1634 (let ((number-type (lvar-type number))
1635 (divisor-type (lvar-type divisor))
1636 (integer-type (specifier-type 'integer)))
1637 (if (and (numeric-type-p number-type)
1638 (csubtypep number-type integer-type)
1639 (numeric-type-p divisor-type)
1640 (csubtypep divisor-type integer-type))
1641 (let ((number-low (numeric-type-low number-type))
1642 (number-high (numeric-type-high number-type))
1643 (divisor-low (numeric-type-low divisor-type))
1644 (divisor-high (numeric-type-high divisor-type)))
1645 (values-specifier-type
1646 `(values ,(integer-truncate-derive-type number-low number-high
1647 divisor-low divisor-high)
1648 ,(integer-rem-derive-type number-low number-high
1649 divisor-low divisor-high))))
1652 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1655 (defun rem-result-type (number-type divisor-type)
1656 ;; Figure out what the remainder type is. The remainder is an
1657 ;; integer if both args are integers; a rational if both args are
1658 ;; rational; and a float otherwise.
1659 (cond ((and (csubtypep number-type (specifier-type 'integer))
1660 (csubtypep divisor-type (specifier-type 'integer)))
1662 ((and (csubtypep number-type (specifier-type 'rational))
1663 (csubtypep divisor-type (specifier-type 'rational)))
1665 ((and (csubtypep number-type (specifier-type 'float))
1666 (csubtypep divisor-type (specifier-type 'float)))
1667 ;; Both are floats so the result is also a float, of
1668 ;; the largest type.
1669 (or (float-format-max (numeric-type-format number-type)
1670 (numeric-type-format divisor-type))
1672 ((and (csubtypep number-type (specifier-type 'float))
1673 (csubtypep divisor-type (specifier-type 'rational)))
1674 ;; One of the arguments is a float and the other is a
1675 ;; rational. The remainder is a float of the same
1677 (or (numeric-type-format number-type) 'float))
1678 ((and (csubtypep divisor-type (specifier-type 'float))
1679 (csubtypep number-type (specifier-type 'rational)))
1680 ;; One of the arguments is a float and the other is a
1681 ;; rational. The remainder is a float of the same
1683 (or (numeric-type-format divisor-type) 'float))
1685 ;; Some unhandled combination. This usually means both args
1686 ;; are REAL so the result is a REAL.
1689 (defun truncate-derive-type-quot (number-type divisor-type)
1690 (let* ((rem-type (rem-result-type number-type divisor-type))
1691 (number-interval (numeric-type->interval number-type))
1692 (divisor-interval (numeric-type->interval divisor-type)))
1693 ;;(declare (type (member '(integer rational float)) rem-type))
1694 ;; We have real numbers now.
1695 (cond ((eq rem-type 'integer)
1696 ;; Since the remainder type is INTEGER, both args are
1698 (let* ((res (integer-truncate-derive-type
1699 (interval-low number-interval)
1700 (interval-high number-interval)
1701 (interval-low divisor-interval)
1702 (interval-high divisor-interval))))
1703 (specifier-type (if (listp res) res 'integer))))
1705 (let ((quot (truncate-quotient-bound
1706 (interval-div number-interval
1707 divisor-interval))))
1708 (specifier-type `(integer ,(or (interval-low quot) '*)
1709 ,(or (interval-high quot) '*))))))))
1711 (defun truncate-derive-type-rem (number-type divisor-type)
1712 (let* ((rem-type (rem-result-type number-type divisor-type))
1713 (number-interval (numeric-type->interval number-type))
1714 (divisor-interval (numeric-type->interval divisor-type))
1715 (rem (truncate-rem-bound number-interval divisor-interval)))
1716 ;;(declare (type (member '(integer rational float)) rem-type))
1717 ;; We have real numbers now.
1718 (cond ((eq rem-type 'integer)
1719 ;; Since the remainder type is INTEGER, both args are
1721 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1722 ,(or (interval-high rem) '*))))
1724 (multiple-value-bind (class format)
1727 (values 'integer nil))
1729 (values 'rational nil))
1730 ((or single-float double-float #!+long-float long-float)
1731 (values 'float rem-type))
1733 (values 'float nil))
1736 (when (member rem-type '(float single-float double-float
1737 #!+long-float long-float))
1738 (setf rem (interval-func #'(lambda (x)
1739 (coerce-for-bound x rem-type))
1741 (make-numeric-type :class class
1743 :low (interval-low rem)
1744 :high (interval-high rem)))))))
1746 (defun truncate-derive-type-quot-aux (num div same-arg)
1747 (declare (ignore same-arg))
1748 (if (and (numeric-type-real-p num)
1749 (numeric-type-real-p div))
1750 (truncate-derive-type-quot num div)
1753 (defun truncate-derive-type-rem-aux (num div same-arg)
1754 (declare (ignore same-arg))
1755 (if (and (numeric-type-real-p num)
1756 (numeric-type-real-p div))
1757 (truncate-derive-type-rem num div)
1760 (defoptimizer (truncate derive-type) ((number divisor))
1761 (let ((quot (two-arg-derive-type number divisor
1762 #'truncate-derive-type-quot-aux #'truncate))
1763 (rem (two-arg-derive-type number divisor
1764 #'truncate-derive-type-rem-aux #'rem)))
1765 (when (and quot rem)
1766 (make-values-type :required (list quot rem)))))
1768 (defun ftruncate-derive-type-quot (number-type divisor-type)
1769 ;; The bounds are the same as for truncate. However, the first
1770 ;; result is a float of some type. We need to determine what that
1771 ;; type is. Basically it's the more contagious of the two types.
1772 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1773 (res-type (numeric-contagion number-type divisor-type)))
1774 (make-numeric-type :class 'float
1775 :format (numeric-type-format res-type)
1776 :low (numeric-type-low q-type)
1777 :high (numeric-type-high q-type))))
1779 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1780 (declare (ignore same-arg))
1781 (if (and (numeric-type-real-p n)
1782 (numeric-type-real-p d))
1783 (ftruncate-derive-type-quot n d)
1786 (defoptimizer (ftruncate derive-type) ((number divisor))
1788 (two-arg-derive-type number divisor
1789 #'ftruncate-derive-type-quot-aux #'ftruncate))
1790 (rem (two-arg-derive-type number divisor
1791 #'truncate-derive-type-rem-aux #'rem)))
1792 (when (and quot rem)
1793 (make-values-type :required (list quot rem)))))
1795 (defun %unary-truncate-derive-type-aux (number)
1796 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1798 (defoptimizer (%unary-truncate derive-type) ((number))
1799 (one-arg-derive-type number
1800 #'%unary-truncate-derive-type-aux
1803 (defoptimizer (%unary-truncate/single-float derive-type) ((number))
1804 (one-arg-derive-type number
1805 #'%unary-truncate-derive-type-aux
1808 (defoptimizer (%unary-truncate/double-float derive-type) ((number))
1809 (one-arg-derive-type number
1810 #'%unary-truncate-derive-type-aux
1813 (defoptimizer (%unary-ftruncate derive-type) ((number))
1814 (let ((divisor (specifier-type '(integer 1 1))))
1815 (one-arg-derive-type number
1817 (ftruncate-derive-type-quot-aux n divisor nil))
1818 #'%unary-ftruncate)))
1820 (defoptimizer (%unary-round derive-type) ((number))
1821 (one-arg-derive-type number
1824 (unless (numeric-type-real-p n)
1825 (return *empty-type*))
1826 (let* ((interval (numeric-type->interval n))
1827 (low (interval-low interval))
1828 (high (interval-high interval)))
1830 (setf low (car low)))
1832 (setf high (car high)))
1842 ;;; Define optimizers for FLOOR and CEILING.
1844 ((def (name q-name r-name)
1845 (let ((q-aux (symbolicate q-name "-AUX"))
1846 (r-aux (symbolicate r-name "-AUX")))
1848 ;; Compute type of quotient (first) result.
1849 (defun ,q-aux (number-type divisor-type)
1850 (let* ((number-interval
1851 (numeric-type->interval number-type))
1853 (numeric-type->interval divisor-type))
1854 (quot (,q-name (interval-div number-interval
1855 divisor-interval))))
1856 (specifier-type `(integer ,(or (interval-low quot) '*)
1857 ,(or (interval-high quot) '*)))))
1858 ;; Compute type of remainder.
1859 (defun ,r-aux (number-type divisor-type)
1860 (let* ((divisor-interval
1861 (numeric-type->interval divisor-type))
1862 (rem (,r-name divisor-interval))
1863 (result-type (rem-result-type number-type divisor-type)))
1864 (multiple-value-bind (class format)
1867 (values 'integer nil))
1869 (values 'rational nil))
1870 ((or single-float double-float #!+long-float long-float)
1871 (values 'float result-type))
1873 (values 'float nil))
1876 (when (member result-type '(float single-float double-float
1877 #!+long-float long-float))
1878 ;; Make sure that the limits on the interval have
1880 (setf rem (interval-func (lambda (x)
1881 (coerce-for-bound x result-type))
1883 (make-numeric-type :class class
1885 :low (interval-low rem)
1886 :high (interval-high rem)))))
1887 ;; the optimizer itself
1888 (defoptimizer (,name derive-type) ((number divisor))
1889 (flet ((derive-q (n d same-arg)
1890 (declare (ignore same-arg))
1891 (if (and (numeric-type-real-p n)
1892 (numeric-type-real-p d))
1895 (derive-r (n d same-arg)
1896 (declare (ignore same-arg))
1897 (if (and (numeric-type-real-p n)
1898 (numeric-type-real-p d))
1901 (let ((quot (two-arg-derive-type
1902 number divisor #'derive-q #',name))
1903 (rem (two-arg-derive-type
1904 number divisor #'derive-r #'mod)))
1905 (when (and quot rem)
1906 (make-values-type :required (list quot rem))))))))))
1908 (def floor floor-quotient-bound floor-rem-bound)
1909 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1911 ;;; Define optimizers for FFLOOR and FCEILING
1912 (macrolet ((def (name q-name r-name)
1913 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1914 (r-aux (symbolicate r-name "-AUX")))
1916 ;; Compute type of quotient (first) result.
1917 (defun ,q-aux (number-type divisor-type)
1918 (let* ((number-interval
1919 (numeric-type->interval number-type))
1921 (numeric-type->interval divisor-type))
1922 (quot (,q-name (interval-div number-interval
1924 (res-type (numeric-contagion number-type
1927 :class (numeric-type-class res-type)
1928 :format (numeric-type-format res-type)
1929 :low (interval-low quot)
1930 :high (interval-high quot))))
1932 (defoptimizer (,name derive-type) ((number divisor))
1933 (flet ((derive-q (n d same-arg)
1934 (declare (ignore same-arg))
1935 (if (and (numeric-type-real-p n)
1936 (numeric-type-real-p d))
1939 (derive-r (n d same-arg)
1940 (declare (ignore same-arg))
1941 (if (and (numeric-type-real-p n)
1942 (numeric-type-real-p d))
1945 (let ((quot (two-arg-derive-type
1946 number divisor #'derive-q #',name))
1947 (rem (two-arg-derive-type
1948 number divisor #'derive-r #'mod)))
1949 (when (and quot rem)
1950 (make-values-type :required (list quot rem))))))))))
1952 (def ffloor floor-quotient-bound floor-rem-bound)
1953 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1955 ;;; functions to compute the bounds on the quotient and remainder for
1956 ;;; the FLOOR function
1957 (defun floor-quotient-bound (quot)
1958 ;; Take the floor of the quotient and then massage it into what we
1960 (let ((lo (interval-low quot))
1961 (hi (interval-high quot)))
1962 ;; Take the floor of the lower bound. The result is always a
1963 ;; closed lower bound.
1965 (floor (type-bound-number lo))
1967 ;; For the upper bound, we need to be careful.
1970 ;; An open bound. We need to be careful here because
1971 ;; the floor of '(10.0) is 9, but the floor of
1973 (multiple-value-bind (q r) (floor (first hi))
1978 ;; A closed bound, so the answer is obvious.
1982 (make-interval :low lo :high hi)))
1983 (defun floor-rem-bound (div)
1984 ;; The remainder depends only on the divisor. Try to get the
1985 ;; correct sign for the remainder if we can.
1986 (case (interval-range-info div)
1988 ;; The divisor is always positive.
1989 (let ((rem (interval-abs div)))
1990 (setf (interval-low rem) 0)
1991 (when (and (numberp (interval-high rem))
1992 (not (zerop (interval-high rem))))
1993 ;; The remainder never contains the upper bound. However,
1994 ;; watch out for the case where the high limit is zero!
1995 (setf (interval-high rem) (list (interval-high rem))))
1998 ;; The divisor is always negative.
1999 (let ((rem (interval-neg (interval-abs div))))
2000 (setf (interval-high rem) 0)
2001 (when (numberp (interval-low rem))
2002 ;; The remainder never contains the lower bound.
2003 (setf (interval-low rem) (list (interval-low rem))))
2006 ;; The divisor can be positive or negative. All bets off. The
2007 ;; magnitude of remainder is the maximum value of the divisor.
2008 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
2009 ;; The bound never reaches the limit, so make the interval open.
2010 (make-interval :low (if limit
2013 :high (list limit))))))
2015 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
2016 => #S(INTERVAL :LOW 0 :HIGH 10)
2017 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
2018 => #S(INTERVAL :LOW 0 :HIGH 10)
2019 (floor-quotient-bound (make-interval :low 0.3 :high 10))
2020 => #S(INTERVAL :LOW 0 :HIGH 10)
2021 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
2022 => #S(INTERVAL :LOW 0 :HIGH 9)
2023 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
2024 => #S(INTERVAL :LOW 0 :HIGH 10)
2025 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
2026 => #S(INTERVAL :LOW 0 :HIGH 10)
2027 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
2028 => #S(INTERVAL :LOW -2 :HIGH 10)
2029 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
2030 => #S(INTERVAL :LOW -1 :HIGH 10)
2031 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
2032 => #S(INTERVAL :LOW -1 :HIGH 10)
2034 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
2035 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2036 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
2037 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2038 (floor-rem-bound (make-interval :low -10 :high -2.3))
2039 #S(INTERVAL :LOW (-10) :HIGH 0)
2040 (floor-rem-bound (make-interval :low 0.3 :high 10))
2041 => #S(INTERVAL :LOW 0 :HIGH '(10))
2042 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
2043 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
2044 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
2045 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
2048 ;;; same functions for CEILING
2049 (defun ceiling-quotient-bound (quot)
2050 ;; Take the ceiling of the quotient and then massage it into what we
2052 (let ((lo (interval-low quot))
2053 (hi (interval-high quot)))
2054 ;; Take the ceiling of the upper bound. The result is always a
2055 ;; closed upper bound.
2057 (ceiling (type-bound-number hi))
2059 ;; For the lower bound, we need to be careful.
2062 ;; An open bound. We need to be careful here because
2063 ;; the ceiling of '(10.0) is 11, but the ceiling of
2065 (multiple-value-bind (q r) (ceiling (first lo))
2070 ;; A closed bound, so the answer is obvious.
2074 (make-interval :low lo :high hi)))
2075 (defun ceiling-rem-bound (div)
2076 ;; The remainder depends only on the divisor. Try to get the
2077 ;; correct sign for the remainder if we can.
2078 (case (interval-range-info div)
2080 ;; Divisor is always positive. The remainder is negative.
2081 (let ((rem (interval-neg (interval-abs div))))
2082 (setf (interval-high rem) 0)
2083 (when (and (numberp (interval-low rem))
2084 (not (zerop (interval-low rem))))
2085 ;; The remainder never contains the upper bound. However,
2086 ;; watch out for the case when the upper bound is zero!
2087 (setf (interval-low rem) (list (interval-low rem))))
2090 ;; Divisor is always negative. The remainder is positive
2091 (let ((rem (interval-abs div)))
2092 (setf (interval-low rem) 0)
2093 (when (numberp (interval-high rem))
2094 ;; The remainder never contains the lower bound.
2095 (setf (interval-high rem) (list (interval-high rem))))
2098 ;; The divisor can be positive or negative. All bets off. The
2099 ;; magnitude of remainder is the maximum value of the divisor.
2100 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
2101 ;; The bound never reaches the limit, so make the interval open.
2102 (make-interval :low (if limit
2105 :high (list limit))))))
2108 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
2109 => #S(INTERVAL :LOW 1 :HIGH 11)
2110 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
2111 => #S(INTERVAL :LOW 1 :HIGH 11)
2112 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
2113 => #S(INTERVAL :LOW 1 :HIGH 10)
2114 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
2115 => #S(INTERVAL :LOW 1 :HIGH 10)
2116 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
2117 => #S(INTERVAL :LOW 1 :HIGH 11)
2118 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
2119 => #S(INTERVAL :LOW 1 :HIGH 11)
2120 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
2121 => #S(INTERVAL :LOW -1 :HIGH 11)
2122 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
2123 => #S(INTERVAL :LOW 0 :HIGH 11)
2124 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
2125 => #S(INTERVAL :LOW -1 :HIGH 11)
2127 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
2128 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
2129 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
2130 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2131 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
2132 => #S(INTERVAL :LOW 0 :HIGH (10))
2133 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
2134 => #S(INTERVAL :LOW (-10) :HIGH 0)
2135 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
2136 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
2137 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
2138 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
2141 (defun truncate-quotient-bound (quot)
2142 ;; For positive quotients, truncate is exactly like floor. For
2143 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
2144 ;; it's the union of the two pieces.
2145 (case (interval-range-info quot)
2148 (floor-quotient-bound quot))
2150 ;; just like CEILING
2151 (ceiling-quotient-bound quot))
2153 ;; Split the interval into positive and negative pieces, compute
2154 ;; the result for each piece and put them back together.
2155 (destructuring-bind (neg pos) (interval-split 0 quot t t)
2156 (interval-merge-pair (ceiling-quotient-bound neg)
2157 (floor-quotient-bound pos))))))
2159 (defun truncate-rem-bound (num div)
2160 ;; This is significantly more complicated than FLOOR or CEILING. We
2161 ;; need both the number and the divisor to determine the range. The
2162 ;; basic idea is to split the ranges of NUM and DEN into positive
2163 ;; and negative pieces and deal with each of the four possibilities
2165 (case (interval-range-info num)
2167 (case (interval-range-info div)
2169 (floor-rem-bound div))
2171 (ceiling-rem-bound div))
2173 (destructuring-bind (neg pos) (interval-split 0 div t t)
2174 (interval-merge-pair (truncate-rem-bound num neg)
2175 (truncate-rem-bound num pos))))))
2177 (case (interval-range-info div)
2179 (ceiling-rem-bound div))
2181 (floor-rem-bound div))
2183 (destructuring-bind (neg pos) (interval-split 0 div t t)
2184 (interval-merge-pair (truncate-rem-bound num neg)
2185 (truncate-rem-bound num pos))))))
2187 (destructuring-bind (neg pos) (interval-split 0 num t t)
2188 (interval-merge-pair (truncate-rem-bound neg div)
2189 (truncate-rem-bound pos div))))))
2192 ;;; Derive useful information about the range. Returns three values:
2193 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
2194 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
2195 ;;; - The abs of the maximal value if there is one, or nil if it is
2197 (defun numeric-range-info (low high)
2198 (cond ((and low (not (minusp low)))
2199 (values '+ low high))
2200 ((and high (not (plusp high)))
2201 (values '- (- high) (if low (- low) nil)))
2203 (values nil 0 (and low high (max (- low) high))))))
2205 (defun integer-truncate-derive-type
2206 (number-low number-high divisor-low divisor-high)
2207 ;; The result cannot be larger in magnitude than the number, but the
2208 ;; sign might change. If we can determine the sign of either the
2209 ;; number or the divisor, we can eliminate some of the cases.
2210 (multiple-value-bind (number-sign number-min number-max)
2211 (numeric-range-info number-low number-high)
2212 (multiple-value-bind (divisor-sign divisor-min divisor-max)
2213 (numeric-range-info divisor-low divisor-high)
2214 (when (and divisor-max (zerop divisor-max))
2215 ;; We've got a problem: guaranteed division by zero.
2216 (return-from integer-truncate-derive-type t))
2217 (when (zerop divisor-min)
2218 ;; We'll assume that they aren't going to divide by zero.
2220 (cond ((and number-sign divisor-sign)
2221 ;; We know the sign of both.
2222 (if (eq number-sign divisor-sign)
2223 ;; Same sign, so the result will be positive.
2224 `(integer ,(if divisor-max
2225 (truncate number-min divisor-max)
2228 (truncate number-max divisor-min)
2230 ;; Different signs, the result will be negative.
2231 `(integer ,(if number-max
2232 (- (truncate number-max divisor-min))
2235 (- (truncate number-min divisor-max))
2237 ((eq divisor-sign '+)
2238 ;; The divisor is positive. Therefore, the number will just
2239 ;; become closer to zero.
2240 `(integer ,(if number-low
2241 (truncate number-low divisor-min)
2244 (truncate number-high divisor-min)
2246 ((eq divisor-sign '-)
2247 ;; The divisor is negative. Therefore, the absolute value of
2248 ;; the number will become closer to zero, but the sign will also
2250 `(integer ,(if number-high
2251 (- (truncate number-high divisor-min))
2254 (- (truncate number-low divisor-min))
2256 ;; The divisor could be either positive or negative.
2258 ;; The number we are dividing has a bound. Divide that by the
2259 ;; smallest posible divisor.
2260 (let ((bound (truncate number-max divisor-min)))
2261 `(integer ,(- bound) ,bound)))
2263 ;; The number we are dividing is unbounded, so we can't tell
2264 ;; anything about the result.
2267 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2268 (defun integer-rem-derive-type
2269 (number-low number-high divisor-low divisor-high)
2270 (if (and divisor-low divisor-high)
2271 ;; We know the range of the divisor, and the remainder must be
2272 ;; smaller than the divisor. We can tell the sign of the
2273 ;; remainer if we know the sign of the number.
2274 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2275 `(integer ,(if (or (null number-low)
2276 (minusp number-low))
2279 ,(if (or (null number-high)
2280 (plusp number-high))
2283 ;; The divisor is potentially either very positive or very
2284 ;; negative. Therefore, the remainer is unbounded, but we might
2285 ;; be able to tell something about the sign from the number.
2286 `(integer ,(if (and number-low (not (minusp number-low)))
2287 ;; The number we are dividing is positive.
2288 ;; Therefore, the remainder must be positive.
2291 ,(if (and number-high (not (plusp number-high)))
2292 ;; The number we are dividing is negative.
2293 ;; Therefore, the remainder must be negative.
2297 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2298 (defoptimizer (random derive-type) ((bound &optional state))
2299 (let ((type (lvar-type bound)))
2300 (when (numeric-type-p type)
2301 (let ((class (numeric-type-class type))
2302 (high (numeric-type-high type))
2303 (format (numeric-type-format type)))
2307 :low (coerce 0 (or format class 'real))
2308 :high (cond ((not high) nil)
2309 ((eq class 'integer) (max (1- high) 0))
2310 ((or (consp high) (zerop high)) high)
2313 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2314 (defun random-derive-type-aux (type)
2315 (let ((class (numeric-type-class type))
2316 (high (numeric-type-high type))
2317 (format (numeric-type-format type)))
2321 :low (coerce 0 (or format class 'real))
2322 :high (cond ((not high) nil)
2323 ((eq class 'integer) (max (1- high) 0))
2324 ((or (consp high) (zerop high)) high)
2327 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2328 (defoptimizer (random derive-type) ((bound &optional state))
2329 (one-arg-derive-type bound #'random-derive-type-aux nil))
2331 ;;;; DERIVE-TYPE methods for LOGAND, LOGIOR, and friends
2333 ;;; Return the maximum number of bits an integer of the supplied type
2334 ;;; can take up, or NIL if it is unbounded. The second (third) value
2335 ;;; is T if the integer can be positive (negative) and NIL if not.
2336 ;;; Zero counts as positive.
2337 (defun integer-type-length (type)
2338 (if (numeric-type-p type)
2339 (let ((min (numeric-type-low type))
2340 (max (numeric-type-high type)))
2341 (values (and min max (max (integer-length min) (integer-length max)))
2342 (or (null max) (not (minusp max)))
2343 (or (null min) (minusp min))))
2346 ;;; See _Hacker's Delight_, Henry S. Warren, Jr. pp 58-63 for an
2347 ;;; explanation of LOG{AND,IOR,XOR}-DERIVE-UNSIGNED-{LOW,HIGH}-BOUND.
2348 ;;; Credit also goes to Raymond Toy for writing (and debugging!) similar
2349 ;;; versions in CMUCL, from which these functions copy liberally.
2351 (defun logand-derive-unsigned-low-bound (x y)
2352 (let ((a (numeric-type-low x))
2353 (b (numeric-type-high x))
2354 (c (numeric-type-low y))
2355 (d (numeric-type-high y)))
2356 (loop for m = (ash 1 (integer-length (lognor a c))) then (ash m -1)
2358 (unless (zerop (logand m (lognot a) (lognot c)))
2359 (let ((temp (logandc2 (logior a m) (1- m))))
2363 (setf temp (logandc2 (logior c m) (1- m)))
2367 finally (return (logand a c)))))
2369 (defun logand-derive-unsigned-high-bound (x y)
2370 (let ((a (numeric-type-low x))
2371 (b (numeric-type-high x))
2372 (c (numeric-type-low y))
2373 (d (numeric-type-high y)))
2374 (loop for m = (ash 1 (integer-length (logxor b d))) then (ash m -1)
2377 ((not (zerop (logand b (lognot d) m)))
2378 (let ((temp (logior (logandc2 b m) (1- m))))
2382 ((not (zerop (logand (lognot b) d m)))
2383 (let ((temp (logior (logandc2 d m) (1- m))))
2387 finally (return (logand b d)))))
2389 (defun logand-derive-type-aux (x y &optional same-leaf)
2391 (return-from logand-derive-type-aux x))
2392 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2393 (declare (ignore x-pos))
2394 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2395 (declare (ignore y-pos))
2397 ;; X must be positive.
2399 ;; They must both be positive.
2400 (cond ((and (null x-len) (null y-len))
2401 (specifier-type 'unsigned-byte))
2403 (specifier-type `(unsigned-byte* ,y-len)))
2405 (specifier-type `(unsigned-byte* ,x-len)))
2407 (let ((low (logand-derive-unsigned-low-bound x y))
2408 (high (logand-derive-unsigned-high-bound x y)))
2409 (specifier-type `(integer ,low ,high)))))
2410 ;; X is positive, but Y might be negative.
2412 (specifier-type 'unsigned-byte))
2414 (specifier-type `(unsigned-byte* ,x-len)))))
2415 ;; X might be negative.
2417 ;; Y must be positive.
2419 (specifier-type 'unsigned-byte))
2420 (t (specifier-type `(unsigned-byte* ,y-len))))
2421 ;; Either might be negative.
2422 (if (and x-len y-len)
2423 ;; The result is bounded.
2424 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2425 ;; We can't tell squat about the result.
2426 (specifier-type 'integer)))))))
2428 (defun logior-derive-unsigned-low-bound (x y)
2429 (let ((a (numeric-type-low x))
2430 (b (numeric-type-high x))
2431 (c (numeric-type-low y))
2432 (d (numeric-type-high y)))
2433 (loop for m = (ash 1 (integer-length (logxor a c))) then (ash m -1)
2436 ((not (zerop (logandc2 (logand c m) a)))
2437 (let ((temp (logand (logior a m) (1+ (lognot m)))))
2441 ((not (zerop (logandc2 (logand a m) c)))
2442 (let ((temp (logand (logior c m) (1+ (lognot m)))))
2446 finally (return (logior a c)))))
2448 (defun logior-derive-unsigned-high-bound (x y)
2449 (let ((a (numeric-type-low x))
2450 (b (numeric-type-high x))
2451 (c (numeric-type-low y))
2452 (d (numeric-type-high y)))
2453 (loop for m = (ash 1 (integer-length (logand b d))) then (ash m -1)
2455 (unless (zerop (logand b d m))
2456 (let ((temp (logior (- b m) (1- m))))
2460 (setf temp (logior (- d m) (1- m)))
2464 finally (return (logior b d)))))
2466 (defun logior-derive-type-aux (x y &optional same-leaf)
2468 (return-from logior-derive-type-aux x))
2469 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2470 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2472 ((and (not x-neg) (not y-neg))
2473 ;; Both are positive.
2474 (if (and x-len y-len)
2475 (let ((low (logior-derive-unsigned-low-bound x y))
2476 (high (logior-derive-unsigned-high-bound x y)))
2477 (specifier-type `(integer ,low ,high)))
2478 (specifier-type `(unsigned-byte* *))))
2480 ;; X must be negative.
2482 ;; Both are negative. The result is going to be negative
2483 ;; and be the same length or shorter than the smaller.
2484 (if (and x-len y-len)
2486 (specifier-type `(integer ,(ash -1 (min x-len y-len)) -1))
2488 (specifier-type '(integer * -1)))
2489 ;; X is negative, but we don't know about Y. The result
2490 ;; will be negative, but no more negative than X.
2492 `(integer ,(or (numeric-type-low x) '*)
2495 ;; X might be either positive or negative.
2497 ;; But Y is negative. The result will be negative.
2499 `(integer ,(or (numeric-type-low y) '*)
2501 ;; We don't know squat about either. It won't get any bigger.
2502 (if (and x-len y-len)
2504 (specifier-type `(signed-byte ,(1+ (max x-len y-len))))
2506 (specifier-type 'integer))))))))
2508 (defun logxor-derive-unsigned-low-bound (x y)
2509 (let ((a (numeric-type-low x))
2510 (b (numeric-type-high x))
2511 (c (numeric-type-low y))
2512 (d (numeric-type-high y)))
2513 (loop for m = (ash 1 (integer-length (logxor a c))) then (ash m -1)
2516 ((not (zerop (logandc2 (logand c m) a)))
2517 (let ((temp (logand (logior a m)
2521 ((not (zerop (logandc2 (logand a m) c)))
2522 (let ((temp (logand (logior c m)
2526 finally (return (logxor a c)))))
2528 (defun logxor-derive-unsigned-high-bound (x y)
2529 (let ((a (numeric-type-low x))
2530 (b (numeric-type-high x))
2531 (c (numeric-type-low y))
2532 (d (numeric-type-high y)))
2533 (loop for m = (ash 1 (integer-length (logand b d))) then (ash m -1)
2535 (unless (zerop (logand b d m))
2536 (let ((temp (logior (- b m) (1- m))))
2538 ((>= temp a) (setf b temp))
2539 (t (let ((temp (logior (- d m) (1- m))))
2542 finally (return (logxor b d)))))
2544 (defun logxor-derive-type-aux (x y &optional same-leaf)
2546 (return-from logxor-derive-type-aux (specifier-type '(eql 0))))
2547 (multiple-value-bind (x-len x-pos x-neg) (integer-type-length x)
2548 (multiple-value-bind (y-len y-pos y-neg) (integer-type-length y)
2550 ((and (not x-neg) (not y-neg))
2551 ;; Both are positive
2552 (if (and x-len y-len)
2553 (let ((low (logxor-derive-unsigned-low-bound x y))
2554 (high (logxor-derive-unsigned-high-bound x y)))
2555 (specifier-type `(integer ,low ,high)))
2556 (specifier-type '(unsigned-byte* *))))
2557 ((and (not x-pos) (not y-pos))
2558 ;; Both are negative. The result will be positive, and as long
2560 (specifier-type `(unsigned-byte* ,(if (and x-len y-len)
2563 ((or (and (not x-pos) (not y-neg))
2564 (and (not y-pos) (not x-neg)))
2565 ;; Either X is negative and Y is positive or vice-versa. The
2566 ;; result will be negative.
2567 (specifier-type `(integer ,(if (and x-len y-len)
2568 (ash -1 (max x-len y-len))
2571 ;; We can't tell what the sign of the result is going to be.
2572 ;; All we know is that we don't create new bits.
2574 (specifier-type `(signed-byte ,(1+ (max x-len y-len)))))
2576 (specifier-type 'integer))))))
2578 (macrolet ((deffrob (logfun)
2579 (let ((fun-aux (symbolicate logfun "-DERIVE-TYPE-AUX")))
2580 `(defoptimizer (,logfun derive-type) ((x y))
2581 (two-arg-derive-type x y #',fun-aux #',logfun)))))
2586 (defoptimizer (logeqv derive-type) ((x y))
2587 (two-arg-derive-type x y (lambda (x y same-leaf)
2588 (lognot-derive-type-aux
2589 (logxor-derive-type-aux x y same-leaf)))
2591 (defoptimizer (lognand derive-type) ((x y))
2592 (two-arg-derive-type x y (lambda (x y same-leaf)
2593 (lognot-derive-type-aux
2594 (logand-derive-type-aux x y same-leaf)))
2596 (defoptimizer (lognor derive-type) ((x y))
2597 (two-arg-derive-type x y (lambda (x y same-leaf)
2598 (lognot-derive-type-aux
2599 (logior-derive-type-aux x y same-leaf)))
2601 (defoptimizer (logandc1 derive-type) ((x y))
2602 (two-arg-derive-type x y (lambda (x y same-leaf)
2604 (specifier-type '(eql 0))
2605 (logand-derive-type-aux
2606 (lognot-derive-type-aux x) y nil)))
2608 (defoptimizer (logandc2 derive-type) ((x y))
2609 (two-arg-derive-type x y (lambda (x y same-leaf)
2611 (specifier-type '(eql 0))
2612 (logand-derive-type-aux
2613 x (lognot-derive-type-aux y) nil)))
2615 (defoptimizer (logorc1 derive-type) ((x y))
2616 (two-arg-derive-type x y (lambda (x y same-leaf)
2618 (specifier-type '(eql -1))
2619 (logior-derive-type-aux
2620 (lognot-derive-type-aux x) y nil)))
2622 (defoptimizer (logorc2 derive-type) ((x y))
2623 (two-arg-derive-type x y (lambda (x y same-leaf)
2625 (specifier-type '(eql -1))
2626 (logior-derive-type-aux
2627 x (lognot-derive-type-aux y) nil)))
2630 ;;;; miscellaneous derive-type methods
2632 (defoptimizer (integer-length derive-type) ((x))
2633 (let ((x-type (lvar-type x)))
2634 (when (numeric-type-p x-type)
2635 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2636 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2637 ;; careful about LO or HI being NIL, though. Also, if 0 is
2638 ;; contained in X, the lower bound is obviously 0.
2639 (flet ((null-or-min (a b)
2640 (and a b (min (integer-length a)
2641 (integer-length b))))
2643 (and a b (max (integer-length a)
2644 (integer-length b)))))
2645 (let* ((min (numeric-type-low x-type))
2646 (max (numeric-type-high x-type))
2647 (min-len (null-or-min min max))
2648 (max-len (null-or-max min max)))
2649 (when (ctypep 0 x-type)
2651 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2653 (defoptimizer (isqrt derive-type) ((x))
2654 (let ((x-type (lvar-type x)))
2655 (when (numeric-type-p x-type)
2656 (let* ((lo (numeric-type-low x-type))
2657 (hi (numeric-type-high x-type))
2658 (lo-res (if lo (isqrt lo) '*))
2659 (hi-res (if hi (isqrt hi) '*)))
2660 (specifier-type `(integer ,lo-res ,hi-res))))))
2662 (defoptimizer (char-code derive-type) ((char))
2663 (let ((type (type-intersection (lvar-type char) (specifier-type 'character))))
2664 (cond ((member-type-p type)
2667 ,@(loop for member in (member-type-members type)
2668 when (characterp member)
2669 collect (char-code member)))))
2670 ((sb!kernel::character-set-type-p type)
2673 ,@(loop for (low . high)
2674 in (character-set-type-pairs type)
2675 collect `(integer ,low ,high)))))
2676 ((csubtypep type (specifier-type 'base-char))
2678 `(mod ,base-char-code-limit)))
2681 `(mod ,char-code-limit))))))
2683 (defoptimizer (code-char derive-type) ((code))
2684 (let ((type (lvar-type code)))
2685 ;; FIXME: unions of integral ranges? It ought to be easier to do
2686 ;; this, given that CHARACTER-SET is basically an integral range
2687 ;; type. -- CSR, 2004-10-04
2688 (when (numeric-type-p type)
2689 (let* ((lo (numeric-type-low type))
2690 (hi (numeric-type-high type))
2691 (type (specifier-type `(character-set ((,lo . ,hi))))))
2693 ;; KLUDGE: when running on the host, we lose a slight amount
2694 ;; of precision so that we don't have to "unparse" types
2695 ;; that formally we can't, such as (CHARACTER-SET ((0
2696 ;; . 0))). -- CSR, 2004-10-06
2698 ((csubtypep type (specifier-type 'standard-char)) type)
2700 ((csubtypep type (specifier-type 'base-char))
2701 (specifier-type 'base-char))
2703 ((csubtypep type (specifier-type 'extended-char))
2704 (specifier-type 'extended-char))
2705 (t #+sb-xc-host (specifier-type 'character)
2706 #-sb-xc-host type))))))
2708 (defoptimizer (values derive-type) ((&rest values))
2709 (make-values-type :required (mapcar #'lvar-type values)))
2711 (defun signum-derive-type-aux (type)
2712 (if (eq (numeric-type-complexp type) :complex)
2713 (let* ((format (case (numeric-type-class type)
2714 ((integer rational) 'single-float)
2715 (t (numeric-type-format type))))
2716 (bound-format (or format 'float)))
2717 (make-numeric-type :class 'float
2720 :low (coerce -1 bound-format)
2721 :high (coerce 1 bound-format)))
2722 (let* ((interval (numeric-type->interval type))
2723 (range-info (interval-range-info interval))
2724 (contains-0-p (interval-contains-p 0 interval))
2725 (class (numeric-type-class type))
2726 (format (numeric-type-format type))
2727 (one (coerce 1 (or format class 'real)))
2728 (zero (coerce 0 (or format class 'real)))
2729 (minus-one (coerce -1 (or format class 'real)))
2730 (plus (make-numeric-type :class class :format format
2731 :low one :high one))
2732 (minus (make-numeric-type :class class :format format
2733 :low minus-one :high minus-one))
2734 ;; KLUDGE: here we have a fairly horrible hack to deal
2735 ;; with the schizophrenia in the type derivation engine.
2736 ;; The problem is that the type derivers reinterpret
2737 ;; numeric types as being exact; so (DOUBLE-FLOAT 0d0
2738 ;; 0d0) within the derivation mechanism doesn't include
2739 ;; -0d0. Ugh. So force it in here, instead.
2740 (zero (make-numeric-type :class class :format format
2741 :low (- zero) :high zero)))
2743 (+ (if contains-0-p (type-union plus zero) plus))
2744 (- (if contains-0-p (type-union minus zero) minus))
2745 (t (type-union minus zero plus))))))
2747 (defoptimizer (signum derive-type) ((num))
2748 (one-arg-derive-type num #'signum-derive-type-aux nil))
2750 ;;;; byte operations
2752 ;;;; We try to turn byte operations into simple logical operations.
2753 ;;;; First, we convert byte specifiers into separate size and position
2754 ;;;; arguments passed to internal %FOO functions. We then attempt to
2755 ;;;; transform the %FOO functions into boolean operations when the
2756 ;;;; size and position are constant and the operands are fixnums.
2758 (macrolet (;; Evaluate body with SIZE-VAR and POS-VAR bound to
2759 ;; expressions that evaluate to the SIZE and POSITION of
2760 ;; the byte-specifier form SPEC. We may wrap a let around
2761 ;; the result of the body to bind some variables.
2763 ;; If the spec is a BYTE form, then bind the vars to the
2764 ;; subforms. otherwise, evaluate SPEC and use the BYTE-SIZE
2765 ;; and BYTE-POSITION. The goal of this transformation is to
2766 ;; avoid consing up byte specifiers and then immediately
2767 ;; throwing them away.
2768 (with-byte-specifier ((size-var pos-var spec) &body body)
2769 (once-only ((spec `(macroexpand ,spec))
2771 `(if (and (consp ,spec)
2772 (eq (car ,spec) 'byte)
2773 (= (length ,spec) 3))
2774 (let ((,size-var (second ,spec))
2775 (,pos-var (third ,spec)))
2777 (let ((,size-var `(byte-size ,,temp))
2778 (,pos-var `(byte-position ,,temp)))
2779 `(let ((,,temp ,,spec))
2782 (define-source-transform ldb (spec int)
2783 (with-byte-specifier (size pos spec)
2784 `(%ldb ,size ,pos ,int)))
2786 (define-source-transform dpb (newbyte spec int)
2787 (with-byte-specifier (size pos spec)
2788 `(%dpb ,newbyte ,size ,pos ,int)))
2790 (define-source-transform mask-field (spec int)
2791 (with-byte-specifier (size pos spec)
2792 `(%mask-field ,size ,pos ,int)))
2794 (define-source-transform deposit-field (newbyte spec int)
2795 (with-byte-specifier (size pos spec)
2796 `(%deposit-field ,newbyte ,size ,pos ,int))))
2798 (defoptimizer (%ldb derive-type) ((size posn num))
2799 (let ((size (lvar-type size)))
2800 (if (and (numeric-type-p size)
2801 (csubtypep size (specifier-type 'integer)))
2802 (let ((size-high (numeric-type-high size)))
2803 (if (and size-high (<= size-high sb!vm:n-word-bits))
2804 (specifier-type `(unsigned-byte* ,size-high))
2805 (specifier-type 'unsigned-byte)))
2808 (defoptimizer (%mask-field derive-type) ((size posn num))
2809 (let ((size (lvar-type size))
2810 (posn (lvar-type posn)))
2811 (if (and (numeric-type-p size)
2812 (csubtypep size (specifier-type 'integer))
2813 (numeric-type-p posn)
2814 (csubtypep posn (specifier-type 'integer)))
2815 (let ((size-high (numeric-type-high size))
2816 (posn-high (numeric-type-high posn)))
2817 (if (and size-high posn-high
2818 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2819 (specifier-type `(unsigned-byte* ,(+ size-high posn-high)))
2820 (specifier-type 'unsigned-byte)))
2823 (defun %deposit-field-derive-type-aux (size posn int)
2824 (let ((size (lvar-type size))
2825 (posn (lvar-type posn))
2826 (int (lvar-type int)))
2827 (when (and (numeric-type-p size)
2828 (numeric-type-p posn)
2829 (numeric-type-p int))
2830 (let ((size-high (numeric-type-high size))
2831 (posn-high (numeric-type-high posn))
2832 (high (numeric-type-high int))
2833 (low (numeric-type-low int)))
2834 (when (and size-high posn-high high low
2835 ;; KLUDGE: we need this cutoff here, otherwise we
2836 ;; will merrily derive the type of %DPB as
2837 ;; (UNSIGNED-BYTE 1073741822), and then attempt to
2838 ;; canonicalize this type to (INTEGER 0 (1- (ASH 1
2839 ;; 1073741822))), with hilarious consequences. We
2840 ;; cutoff at 4*SB!VM:N-WORD-BITS to allow inference
2841 ;; over a reasonable amount of shifting, even on
2842 ;; the alpha/32 port, where N-WORD-BITS is 32 but
2843 ;; machine integers are 64-bits. -- CSR,
2845 (<= (+ size-high posn-high) (* 4 sb!vm:n-word-bits)))
2846 (let ((raw-bit-count (max (integer-length high)
2847 (integer-length low)
2848 (+ size-high posn-high))))
2851 `(signed-byte ,(1+ raw-bit-count))
2852 `(unsigned-byte* ,raw-bit-count)))))))))
2854 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2855 (%deposit-field-derive-type-aux size posn int))
2857 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2858 (%deposit-field-derive-type-aux size posn int))
2860 (deftransform %ldb ((size posn int)
2861 (fixnum fixnum integer)
2862 (unsigned-byte #.sb!vm:n-word-bits))
2863 "convert to inline logical operations"
2864 `(logand (ash int (- posn))
2865 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2866 (- size ,sb!vm:n-word-bits))))
2868 (deftransform %mask-field ((size posn int)
2869 (fixnum fixnum integer)
2870 (unsigned-byte #.sb!vm:n-word-bits))
2871 "convert to inline logical operations"
2873 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2874 (- size ,sb!vm:n-word-bits))
2877 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2878 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2879 ;;; as the result type, as that would allow result types that cover
2880 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2881 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2883 (deftransform %dpb ((new size posn int)
2885 (unsigned-byte #.sb!vm:n-word-bits))
2886 "convert to inline logical operations"
2887 `(let ((mask (ldb (byte size 0) -1)))
2888 (logior (ash (logand new mask) posn)
2889 (logand int (lognot (ash mask posn))))))
2891 (deftransform %dpb ((new size posn int)
2893 (signed-byte #.sb!vm:n-word-bits))
2894 "convert to inline logical operations"
2895 `(let ((mask (ldb (byte size 0) -1)))
2896 (logior (ash (logand new mask) posn)
2897 (logand int (lognot (ash mask posn))))))
2899 (deftransform %deposit-field ((new size posn int)
2901 (unsigned-byte #.sb!vm:n-word-bits))
2902 "convert to inline logical operations"
2903 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2904 (logior (logand new mask)
2905 (logand int (lognot mask)))))
2907 (deftransform %deposit-field ((new size posn int)
2909 (signed-byte #.sb!vm:n-word-bits))
2910 "convert to inline logical operations"
2911 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2912 (logior (logand new mask)
2913 (logand int (lognot mask)))))
2915 (defoptimizer (mask-signed-field derive-type) ((size x))
2916 (let ((size (lvar-type size)))
2917 (if (numeric-type-p size)
2918 (let ((size-high (numeric-type-high size)))
2919 (if (and size-high (<= 1 size-high sb!vm:n-word-bits))
2920 (specifier-type `(signed-byte ,size-high))
2925 ;;; Modular functions
2927 ;;; (ldb (byte s 0) (foo x y ...)) =
2928 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2930 ;;; and similar for other arguments.
2932 (defun make-modular-fun-type-deriver (prototype kind width signedp)
2933 (declare (ignore kind))
2935 (binding* ((info (info :function :info prototype) :exit-if-null)
2936 (fun (fun-info-derive-type info) :exit-if-null)
2937 (mask-type (specifier-type
2939 ((nil) (let ((mask (1- (ash 1 width))))
2940 `(integer ,mask ,mask)))
2941 ((t) `(signed-byte ,width))))))
2943 (let ((res (funcall fun call)))
2945 (if (eq signedp nil)
2946 (logand-derive-type-aux res mask-type))))))
2949 (binding* ((info (info :function :info prototype) :exit-if-null)
2950 (fun (fun-info-derive-type info) :exit-if-null)
2951 (res (funcall fun call) :exit-if-null)
2952 (mask-type (specifier-type
2954 ((nil) (let ((mask (1- (ash 1 width))))
2955 `(integer ,mask ,mask)))
2956 ((t) `(signed-byte ,width))))))
2957 (if (eq signedp nil)
2958 (logand-derive-type-aux res mask-type)))))
2960 ;;; Try to recursively cut all uses of LVAR to WIDTH bits.
2962 ;;; For good functions, we just recursively cut arguments; their
2963 ;;; "goodness" means that the result will not increase (in the
2964 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
2965 ;;; replaced with the version, cutting its result to WIDTH or more
2966 ;;; bits. For most functions (e.g. for +) we cut all arguments; for
2967 ;;; others (e.g. for ASH) we have "optimizers", cutting only necessary
2968 ;;; arguments (maybe to a different width) and returning the name of a
2969 ;;; modular version, if it exists, or NIL. If we have changed
2970 ;;; anything, we need to flush old derived types, because they have
2971 ;;; nothing in common with the new code.
2972 (defun cut-to-width (lvar kind width signedp)
2973 (declare (type lvar lvar) (type (integer 0) width))
2974 (let ((type (specifier-type (if (zerop width)
2977 ((nil) 'unsigned-byte)
2980 (labels ((reoptimize-node (node name)
2981 (setf (node-derived-type node)
2983 (info :function :type name)))
2984 (setf (lvar-%derived-type (node-lvar node)) nil)
2985 (setf (node-reoptimize node) t)
2986 (setf (block-reoptimize (node-block node)) t)
2987 (reoptimize-component (node-component node) :maybe))
2988 (cut-node (node &aux did-something)
2989 (when (and (not (block-delete-p (node-block node)))
2990 (combination-p node)
2991 (eq (basic-combination-kind node) :known))
2992 (let* ((fun-ref (lvar-use (combination-fun node)))
2993 (fun-name (leaf-source-name (ref-leaf fun-ref)))
2994 (modular-fun (find-modular-version fun-name kind signedp width)))
2995 (when (and modular-fun
2996 (not (and (eq fun-name 'logand)
2998 (single-value-type (node-derived-type node))
3000 (binding* ((name (etypecase modular-fun
3001 ((eql :good) fun-name)
3003 (modular-fun-info-name modular-fun))
3005 (funcall modular-fun node width)))
3007 (unless (eql modular-fun :good)
3008 (setq did-something t)
3011 (find-free-fun name "in a strange place"))
3012 (setf (combination-kind node) :full))
3013 (unless (functionp modular-fun)
3014 (dolist (arg (basic-combination-args node))
3015 (when (cut-lvar arg)
3016 (setq did-something t))))
3018 (reoptimize-node node name))
3020 (cut-lvar (lvar &aux did-something)
3021 (do-uses (node lvar)
3022 (when (cut-node node)
3023 (setq did-something t)))
3027 (defun best-modular-version (width signedp)
3028 ;; 1. exact width-matched :untagged
3029 ;; 2. >/>= width-matched :tagged
3030 ;; 3. >/>= width-matched :untagged
3031 (let* ((uuwidths (modular-class-widths *untagged-unsigned-modular-class*))
3032 (uswidths (modular-class-widths *untagged-signed-modular-class*))
3033 (uwidths (merge 'list uuwidths uswidths #'< :key #'car))
3034 (twidths (modular-class-widths *tagged-modular-class*)))
3035 (let ((exact (find (cons width signedp) uwidths :test #'equal)))
3037 (return-from best-modular-version (values width :untagged signedp))))
3038 (flet ((inexact-match (w)
3040 ((eq signedp (cdr w)) (<= width (car w)))
3041 ((eq signedp nil) (< width (car w))))))
3042 (let ((tgt (find-if #'inexact-match twidths)))
3044 (return-from best-modular-version
3045 (values (car tgt) :tagged (cdr tgt)))))
3046 (let ((ugt (find-if #'inexact-match uwidths)))
3048 (return-from best-modular-version
3049 (values (car ugt) :untagged (cdr ugt))))))))
3051 (defoptimizer (logand optimizer) ((x y) node)
3052 (let ((result-type (single-value-type (node-derived-type node))))
3053 (when (numeric-type-p result-type)
3054 (let ((low (numeric-type-low result-type))
3055 (high (numeric-type-high result-type)))
3056 (when (and (numberp low)
3059 (let ((width (integer-length high)))
3060 (multiple-value-bind (w kind signedp)
3061 (best-modular-version width nil)
3063 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND WIDTH SIGNEDP).
3064 (cut-to-width x kind width signedp)
3065 (cut-to-width y kind width signedp)
3066 nil ; After fixing above, replace with T.
3069 (defoptimizer (mask-signed-field optimizer) ((width x) node)
3070 (let ((result-type (single-value-type (node-derived-type node))))
3071 (when (numeric-type-p result-type)
3072 (let ((low (numeric-type-low result-type))
3073 (high (numeric-type-high result-type)))
3074 (when (and (numberp low) (numberp high))
3075 (let ((width (max (integer-length high) (integer-length low))))
3076 (multiple-value-bind (w kind)
3077 (best-modular-version width t)
3079 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND WIDTH T).
3080 (cut-to-width x kind width t)
3081 nil ; After fixing above, replace with T.
3084 ;;; miscellanous numeric transforms
3086 ;;; If a constant appears as the first arg, swap the args.
3087 (deftransform commutative-arg-swap ((x y) * * :defun-only t :node node)
3088 (if (and (constant-lvar-p x)
3089 (not (constant-lvar-p y)))
3090 `(,(lvar-fun-name (basic-combination-fun node))
3093 (give-up-ir1-transform)))
3095 (dolist (x '(= char= + * logior logand logxor))
3096 (%deftransform x '(function * *) #'commutative-arg-swap
3097 "place constant arg last"))
3099 ;;; Handle the case of a constant BOOLE-CODE.
3100 (deftransform boole ((op x y) * *)
3101 "convert to inline logical operations"
3102 (unless (constant-lvar-p op)
3103 (give-up-ir1-transform "BOOLE code is not a constant."))
3104 (let ((control (lvar-value op)))
3106 (#.sb!xc:boole-clr 0)
3107 (#.sb!xc:boole-set -1)
3108 (#.sb!xc:boole-1 'x)
3109 (#.sb!xc:boole-2 'y)
3110 (#.sb!xc:boole-c1 '(lognot x))
3111 (#.sb!xc:boole-c2 '(lognot y))
3112 (#.sb!xc:boole-and '(logand x y))
3113 (#.sb!xc:boole-ior '(logior x y))
3114 (#.sb!xc:boole-xor '(logxor x y))
3115 (#.sb!xc:boole-eqv '(logeqv x y))
3116 (#.sb!xc:boole-nand '(lognand x y))
3117 (#.sb!xc:boole-nor '(lognor x y))
3118 (#.sb!xc:boole-andc1 '(logandc1 x y))
3119 (#.sb!xc:boole-andc2 '(logandc2 x y))
3120 (#.sb!xc:boole-orc1 '(logorc1 x y))
3121 (#.sb!xc:boole-orc2 '(logorc2 x y))
3123 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
3126 ;;;; converting special case multiply/divide to shifts
3128 ;;; If arg is a constant power of two, turn * into a shift.
3129 (deftransform * ((x y) (integer integer) *)
3130 "convert x*2^k to shift"
3131 (unless (constant-lvar-p y)
3132 (give-up-ir1-transform))
3133 (let* ((y (lvar-value y))
3135 (len (1- (integer-length y-abs))))
3136 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3137 (give-up-ir1-transform))
3142 ;;; If arg is a constant power of two, turn FLOOR into a shift and
3143 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
3145 (flet ((frob (y ceil-p)
3146 (unless (constant-lvar-p y)
3147 (give-up-ir1-transform))
3148 (let* ((y (lvar-value y))
3150 (len (1- (integer-length y-abs))))
3151 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3152 (give-up-ir1-transform))
3153 (let ((shift (- len))
3155 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
3156 `(let ((x (+ x ,delta)))
3158 `(values (ash (- x) ,shift)
3159 (- (- (logand (- x) ,mask)) ,delta))
3160 `(values (ash x ,shift)
3161 (- (logand x ,mask) ,delta))))))))
3162 (deftransform floor ((x y) (integer integer) *)
3163 "convert division by 2^k to shift"
3165 (deftransform ceiling ((x y) (integer integer) *)
3166 "convert division by 2^k to shift"
3169 ;;; Do the same for MOD.
3170 (deftransform mod ((x y) (integer integer) *)
3171 "convert remainder mod 2^k to LOGAND"
3172 (unless (constant-lvar-p y)
3173 (give-up-ir1-transform))
3174 (let* ((y (lvar-value y))
3176 (len (1- (integer-length y-abs))))
3177 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3178 (give-up-ir1-transform))
3179 (let ((mask (1- y-abs)))
3181 `(- (logand (- x) ,mask))
3182 `(logand x ,mask)))))
3184 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
3185 (deftransform truncate ((x y) (integer integer))
3186 "convert division by 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))
3194 (let* ((shift (- len))
3197 (values ,(if (minusp y)
3199 `(- (ash (- x) ,shift)))
3200 (- (logand (- x) ,mask)))
3201 (values ,(if (minusp y)
3202 `(ash (- ,mask x) ,shift)
3204 (logand x ,mask))))))
3206 ;;; And the same for REM.
3207 (deftransform rem ((x y) (integer integer) *)
3208 "convert remainder mod 2^k to LOGAND"
3209 (unless (constant-lvar-p y)
3210 (give-up-ir1-transform))
3211 (let* ((y (lvar-value y))
3213 (len (1- (integer-length y-abs))))
3214 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3215 (give-up-ir1-transform))
3216 (let ((mask (1- y-abs)))
3218 (- (logand (- x) ,mask))
3219 (logand x ,mask)))))
3221 ;;;; arithmetic and logical identity operation elimination
3223 ;;; Flush calls to various arith functions that convert to the
3224 ;;; identity function or a constant.
3225 (macrolet ((def (name identity result)
3226 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
3227 "fold identity operations"
3234 (def logxor -1 (lognot x))
3237 (deftransform logand ((x y) (* (constant-arg t)) *)
3238 "fold identity operation"
3239 (let ((y (lvar-value y)))
3240 (unless (and (plusp y)
3241 (= y (1- (ash 1 (integer-length y)))))
3242 (give-up-ir1-transform))
3243 (unless (csubtypep (lvar-type x)
3244 (specifier-type `(integer 0 ,y)))
3245 (give-up-ir1-transform))
3248 (deftransform mask-signed-field ((size x) ((constant-arg t) *) *)
3249 "fold identity operation"
3250 (let ((size (lvar-value size)))
3251 (unless (csubtypep (lvar-type x) (specifier-type `(signed-byte ,size)))
3252 (give-up-ir1-transform))
3255 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
3256 ;;; (* 0 -4.0) is -0.0.
3257 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
3258 "convert (- 0 x) to negate"
3260 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
3261 "convert (* x 0) to 0"
3264 ;;; Return T if in an arithmetic op including lvars X and Y, the
3265 ;;; result type is not affected by the type of X. That is, Y is at
3266 ;;; least as contagious as X.
3268 (defun not-more-contagious (x y)
3269 (declare (type continuation x y))
3270 (let ((x (lvar-type x))
3272 (values (type= (numeric-contagion x y)
3273 (numeric-contagion y y)))))
3274 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
3275 ;;; XXX needs more work as valid transforms are missed; some cases are
3276 ;;; specific to particular transform functions so the use of this
3277 ;;; function may need a re-think.
3278 (defun not-more-contagious (x y)
3279 (declare (type lvar x y))
3280 (flet ((simple-numeric-type (num)
3281 (and (numeric-type-p num)
3282 ;; Return non-NIL if NUM is integer, rational, or a float
3283 ;; of some type (but not FLOAT)
3284 (case (numeric-type-class num)
3288 (numeric-type-format num))
3291 (let ((x (lvar-type x))
3293 (if (and (simple-numeric-type x)
3294 (simple-numeric-type y))
3295 (values (type= (numeric-contagion x y)
3296 (numeric-contagion y y)))))))
3298 (def!type exact-number ()
3299 '(or rational (complex rational)))
3303 ;;; Only safely applicable for exact numbers. For floating-point
3304 ;;; x, one would have to first show that neither x or y are signed
3305 ;;; 0s, and that x isn't an SNaN.
3306 (deftransform + ((x y) (exact-number (constant-arg (eql 0))) *)
3311 (deftransform - ((x y) (exact-number (constant-arg (eql 0))) *)
3315 ;;; Fold (OP x +/-1)
3317 ;;; %NEGATE might not always signal correctly.
3319 ((def (name result minus-result)
3320 `(deftransform ,name ((x y)
3321 (exact-number (constant-arg (member 1 -1))))
3322 "fold identity operations"
3323 (if (minusp (lvar-value y)) ',minus-result ',result))))
3324 (def * x (%negate x))
3325 (def / x (%negate x))
3326 (def expt x (/ 1 x)))
3328 ;;; Fold (expt x n) into multiplications for small integral values of
3329 ;;; N; convert (expt x 1/2) to sqrt.
3330 (deftransform expt ((x y) (t (constant-arg real)) *)
3331 "recode as multiplication or sqrt"
3332 (let ((val (lvar-value y)))
3333 ;; If Y would cause the result to be promoted to the same type as
3334 ;; Y, we give up. If not, then the result will be the same type
3335 ;; as X, so we can replace the exponentiation with simple
3336 ;; multiplication and division for small integral powers.
3337 (unless (not-more-contagious y x)
3338 (give-up-ir1-transform))
3340 (let ((x-type (lvar-type x)))
3341 (cond ((csubtypep x-type (specifier-type '(or rational
3342 (complex rational))))
3344 ((csubtypep x-type (specifier-type 'real))
3348 ((csubtypep x-type (specifier-type 'complex))
3349 ;; both parts are float
3351 (t (give-up-ir1-transform)))))
3352 ((= val 2) '(* x x))
3353 ((= val -2) '(/ (* x x)))
3354 ((= val 3) '(* x x x))
3355 ((= val -3) '(/ (* x x x)))
3356 ((= val 1/2) '(sqrt x))
3357 ((= val -1/2) '(/ (sqrt x)))
3358 (t (give-up-ir1-transform)))))
3360 (deftransform expt ((x y) ((constant-arg (member -1 -1.0 -1.0d0)) integer) *)
3361 "recode as an ODDP check"
3362 (let ((val (lvar-value x)))
3364 '(- 1 (* 2 (logand 1 y)))
3369 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
3370 ;;; transformations?
3371 ;;; Perhaps we should have to prove that the denominator is nonzero before
3372 ;;; doing them? -- WHN 19990917
3373 (macrolet ((def (name)
3374 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3381 (macrolet ((def (name)
3382 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3391 ;;;; character operations
3393 (deftransform char-equal ((a b) (base-char base-char))
3395 '(let* ((ac (char-code a))
3397 (sum (logxor ac bc)))
3399 (when (eql sum #x20)
3400 (let ((sum (+ ac bc)))
3401 (or (and (> sum 161) (< sum 213))
3402 (and (> sum 415) (< sum 461))
3403 (and (> sum 463) (< sum 477))))))))
3405 (deftransform char-upcase ((x) (base-char))
3407 '(let ((n-code (char-code x)))
3408 (if (or (and (> n-code #o140) ; Octal 141 is #\a.
3409 (< n-code #o173)) ; Octal 172 is #\z.
3410 (and (> n-code #o337)
3412 (and (> n-code #o367)
3414 (code-char (logxor #x20 n-code))
3417 (deftransform char-downcase ((x) (base-char))
3419 '(let ((n-code (char-code x)))
3420 (if (or (and (> n-code 64) ; 65 is #\A.
3421 (< n-code 91)) ; 90 is #\Z.
3426 (code-char (logxor #x20 n-code))
3429 ;;;; equality predicate transforms
3431 ;;; Return true if X and Y are lvars whose only use is a
3432 ;;; reference to the same leaf, and the value of the leaf cannot
3434 (defun same-leaf-ref-p (x y)
3435 (declare (type lvar x y))
3436 (let ((x-use (principal-lvar-use x))
3437 (y-use (principal-lvar-use y)))
3440 (eq (ref-leaf x-use) (ref-leaf y-use))
3441 (constant-reference-p x-use))))
3443 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
3444 ;;; if there is no intersection between the types of the arguments,
3445 ;;; then the result is definitely false.
3446 (deftransform simple-equality-transform ((x y) * *
3449 ((same-leaf-ref-p x y) t)
3450 ((not (types-equal-or-intersect (lvar-type x) (lvar-type y)))
3452 (t (give-up-ir1-transform))))
3455 `(%deftransform ',x '(function * *) #'simple-equality-transform)))
3459 ;;; This is similar to SIMPLE-EQUALITY-TRANSFORM, except that we also
3460 ;;; try to convert to a type-specific predicate or EQ:
3461 ;;; -- If both args are characters, convert to CHAR=. This is better than
3462 ;;; just converting to EQ, since CHAR= may have special compilation
3463 ;;; strategies for non-standard representations, etc.
3464 ;;; -- If either arg is definitely a fixnum, we check to see if X is
3465 ;;; constant and if so, put X second. Doing this results in better
3466 ;;; code from the backend, since the backend assumes that any constant
3467 ;;; argument comes second.
3468 ;;; -- If either arg is definitely not a number or a fixnum, then we
3469 ;;; can compare with EQ.
3470 ;;; -- Otherwise, we try to put the arg we know more about second. If X
3471 ;;; is constant then we put it second. If X is a subtype of Y, we put
3472 ;;; it second. These rules make it easier for the back end to match
3473 ;;; these interesting cases.
3474 (deftransform eql ((x y) * * :node node)
3475 "convert to simpler equality predicate"
3476 (let ((x-type (lvar-type x))
3477 (y-type (lvar-type y))
3478 (char-type (specifier-type 'character)))
3479 (flet ((fixnum-type-p (type)
3480 (csubtypep type (specifier-type 'fixnum))))
3482 ((same-leaf-ref-p x y) t)
3483 ((not (types-equal-or-intersect x-type y-type))
3485 ((and (csubtypep x-type char-type)
3486 (csubtypep y-type char-type))
3488 ((or (fixnum-type-p x-type) (fixnum-type-p y-type))
3489 (commutative-arg-swap node))
3490 ((or (eq-comparable-type-p x-type) (eq-comparable-type-p y-type))
3492 ((and (not (constant-lvar-p y))
3493 (or (constant-lvar-p x)
3494 (and (csubtypep x-type y-type)
3495 (not (csubtypep y-type x-type)))))
3498 (give-up-ir1-transform))))))
3500 ;;; similarly to the EQL transform above, we attempt to constant-fold
3501 ;;; or convert to a simpler predicate: mostly we have to be careful
3502 ;;; with strings and bit-vectors.
3503 (deftransform equal ((x y) * *)
3504 "convert to simpler equality predicate"
3505 (let ((x-type (lvar-type x))
3506 (y-type (lvar-type y))
3507 (string-type (specifier-type 'string))
3508 (bit-vector-type (specifier-type 'bit-vector)))
3510 ((same-leaf-ref-p x y) t)
3511 ((and (csubtypep x-type string-type)
3512 (csubtypep y-type string-type))
3514 ((and (csubtypep x-type bit-vector-type)
3515 (csubtypep y-type bit-vector-type))
3516 '(bit-vector-= x y))
3517 ;; if at least one is not a string, and at least one is not a
3518 ;; bit-vector, then we can reason from types.
3519 ((and (not (and (types-equal-or-intersect x-type string-type)
3520 (types-equal-or-intersect y-type string-type)))
3521 (not (and (types-equal-or-intersect x-type bit-vector-type)
3522 (types-equal-or-intersect y-type bit-vector-type)))
3523 (not (types-equal-or-intersect x-type y-type)))
3525 (t (give-up-ir1-transform)))))
3527 ;;; Convert to EQL if both args are rational and complexp is specified
3528 ;;; and the same for both.
3529 (deftransform = ((x y) (number number) *)
3531 (let ((x-type (lvar-type x))
3532 (y-type (lvar-type y)))
3533 (cond ((or (and (csubtypep x-type (specifier-type 'float))
3534 (csubtypep y-type (specifier-type 'float)))
3535 (and (csubtypep x-type (specifier-type '(complex float)))
3536 (csubtypep y-type (specifier-type '(complex float))))
3537 #!+complex-float-vops
3538 (and (csubtypep x-type (specifier-type '(or single-float (complex single-float))))
3539 (csubtypep y-type (specifier-type '(or single-float (complex single-float)))))
3540 #!+complex-float-vops
3541 (and (csubtypep x-type (specifier-type '(or double-float (complex double-float))))
3542 (csubtypep y-type (specifier-type '(or double-float (complex double-float))))))
3543 ;; They are both floats. Leave as = so that -0.0 is
3544 ;; handled correctly.
3545 (give-up-ir1-transform))
3546 ((or (and (csubtypep x-type (specifier-type 'rational))
3547 (csubtypep y-type (specifier-type 'rational)))
3548 (and (csubtypep x-type
3549 (specifier-type '(complex rational)))
3551 (specifier-type '(complex rational)))))
3552 ;; They are both rationals and complexp is the same.
3556 (give-up-ir1-transform
3557 "The operands might not be the same type.")))))
3559 (defun maybe-float-lvar-p (lvar)
3560 (neq *empty-type* (type-intersection (specifier-type 'float)
3563 (flet ((maybe-invert (node op inverted x y)
3564 ;; Don't invert if either argument can be a float (NaNs)
3566 ((or (maybe-float-lvar-p x) (maybe-float-lvar-p y))
3567 (delay-ir1-transform node :constraint)
3568 `(or (,op x y) (= x y)))
3570 `(if (,inverted x y) nil t)))))
3571 (deftransform >= ((x y) (number number) * :node node)
3572 "invert or open code"
3573 (maybe-invert node '> '< x y))
3574 (deftransform <= ((x y) (number number) * :node node)
3575 "invert or open code"
3576 (maybe-invert node '< '> x y)))
3578 ;;; See whether we can statically determine (< X Y) using type
3579 ;;; information. If X's high bound is < Y's low, then X < Y.
3580 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
3581 ;;; NIL). If not, at least make sure any constant arg is second.
3582 (macrolet ((def (name inverse reflexive-p surely-true surely-false)
3583 `(deftransform ,name ((x y))
3584 "optimize using intervals"
3585 (if (and (same-leaf-ref-p x y)
3586 ;; For non-reflexive functions we don't need
3587 ;; to worry about NaNs: (non-ref-op NaN NaN) => false,
3588 ;; but with reflexive ones we don't know...
3590 '((and (not (maybe-float-lvar-p x))
3591 (not (maybe-float-lvar-p y))))))
3593 (let ((ix (or (type-approximate-interval (lvar-type x))
3594 (give-up-ir1-transform)))
3595 (iy (or (type-approximate-interval (lvar-type y))
3596 (give-up-ir1-transform))))
3601 ((and (constant-lvar-p x)
3602 (not (constant-lvar-p y)))
3605 (give-up-ir1-transform))))))))
3606 (def = = t (interval-= ix iy) (interval-/= ix iy))
3607 (def /= /= nil (interval-/= ix iy) (interval-= ix iy))
3608 (def < > nil (interval-< ix iy) (interval->= ix iy))
3609 (def > < nil (interval-< iy ix) (interval->= iy ix))
3610 (def <= >= t (interval->= iy ix) (interval-< iy ix))
3611 (def >= <= t (interval->= ix iy) (interval-< ix iy)))
3613 (defun ir1-transform-char< (x y first second inverse)
3615 ((same-leaf-ref-p x y) nil)
3616 ;; If we had interval representation of character types, as we
3617 ;; might eventually have to to support 2^21 characters, then here
3618 ;; we could do some compile-time computation as in transforms for
3619 ;; < above. -- CSR, 2003-07-01
3620 ((and (constant-lvar-p first)
3621 (not (constant-lvar-p second)))
3623 (t (give-up-ir1-transform))))
3625 (deftransform char< ((x y) (character character) *)
3626 (ir1-transform-char< x y x y 'char>))
3628 (deftransform char> ((x y) (character character) *)
3629 (ir1-transform-char< y x x y 'char<))
3631 ;;;; converting N-arg comparisons
3633 ;;;; We convert calls to N-arg comparison functions such as < into
3634 ;;;; two-arg calls. This transformation is enabled for all such
3635 ;;;; comparisons in this file. If any of these predicates are not
3636 ;;;; open-coded, then the transformation should be removed at some
3637 ;;;; point to avoid pessimization.
3639 ;;; This function is used for source transformation of N-arg
3640 ;;; comparison functions other than inequality. We deal both with
3641 ;;; converting to two-arg calls and inverting the sense of the test,
3642 ;;; if necessary. If the call has two args, then we pass or return a
3643 ;;; negated test as appropriate. If it is a degenerate one-arg call,
3644 ;;; then we transform to code that returns true. Otherwise, we bind
3645 ;;; all the arguments and expand into a bunch of IFs.
3646 (defun multi-compare (predicate args not-p type &optional force-two-arg-p)
3647 (let ((nargs (length args)))
3648 (cond ((< nargs 1) (values nil t))
3649 ((= nargs 1) `(progn (the ,type ,@args) t))
3652 `(if (,predicate ,(first args) ,(second args)) nil t)
3654 `(,predicate ,(first args) ,(second args))
3657 (do* ((i (1- nargs) (1- i))
3659 (current (gensym) (gensym))
3660 (vars (list current) (cons current vars))
3662 `(if (,predicate ,current ,last)
3664 `(if (,predicate ,current ,last)
3667 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3670 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
3671 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
3672 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
3673 ;;; We cannot do the inversion for >= and <= here, since both
3674 ;;; (< NaN X) and (> NaN X)
3675 ;;; are false, and we don't have type-inforation available yet. The
3676 ;;; deftransforms for two-argument versions of >= and <= takes care of
3677 ;;; the inversion to > and < when possible.
3678 (define-source-transform <= (&rest args) (multi-compare '<= args nil 'real))
3679 (define-source-transform >= (&rest args) (multi-compare '>= args nil 'real))
3681 (define-source-transform char= (&rest args) (multi-compare 'char= args nil
3683 (define-source-transform char< (&rest args) (multi-compare 'char< args nil
3685 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
3687 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
3689 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
3692 (define-source-transform char-equal (&rest args)
3693 (multi-compare 'sb!impl::two-arg-char-equal args nil 'character t))
3694 (define-source-transform char-lessp (&rest args)
3695 (multi-compare 'sb!impl::two-arg-char-lessp args nil 'character t))
3696 (define-source-transform char-greaterp (&rest args)
3697 (multi-compare 'sb!impl::two-arg-char-greaterp args nil 'character t))
3698 (define-source-transform char-not-greaterp (&rest args)
3699 (multi-compare 'sb!impl::two-arg-char-greaterp args t 'character t))
3700 (define-source-transform char-not-lessp (&rest args)
3701 (multi-compare 'sb!impl::two-arg-char-lessp args t 'character t))
3703 ;;; This function does source transformation of N-arg inequality
3704 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
3705 ;;; arg cases. If there are more than two args, then we expand into
3706 ;;; the appropriate n^2 comparisons only when speed is important.
3707 (declaim (ftype (function (symbol list t) *) multi-not-equal))
3708 (defun multi-not-equal (predicate args type)
3709 (let ((nargs (length args)))
3710 (cond ((< nargs 1) (values nil t))
3711 ((= nargs 1) `(progn (the ,type ,@args) t))
3713 `(if (,predicate ,(first args) ,(second args)) nil t))
3714 ((not (policy *lexenv*
3715 (and (>= speed space)
3716 (>= speed compilation-speed))))
3719 (let ((vars (make-gensym-list nargs)))
3720 (do ((var vars next)
3721 (next (cdr vars) (cdr next))
3724 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3726 (let ((v1 (first var)))
3728 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
3730 (define-source-transform /= (&rest args)
3731 (multi-not-equal '= args 'number))
3732 (define-source-transform char/= (&rest args)
3733 (multi-not-equal 'char= args 'character))
3734 (define-source-transform char-not-equal (&rest args)
3735 (multi-not-equal 'char-equal args 'character))
3737 ;;; Expand MAX and MIN into the obvious comparisons.
3738 (define-source-transform max (arg0 &rest rest)
3739 (once-only ((arg0 arg0))
3741 `(values (the real ,arg0))
3742 `(let ((maxrest (max ,@rest)))
3743 (if (>= ,arg0 maxrest) ,arg0 maxrest)))))
3744 (define-source-transform min (arg0 &rest rest)
3745 (once-only ((arg0 arg0))
3747 `(values (the real ,arg0))
3748 `(let ((minrest (min ,@rest)))
3749 (if (<= ,arg0 minrest) ,arg0 minrest)))))
3751 ;;;; converting N-arg arithmetic functions
3753 ;;;; N-arg arithmetic and logic functions are associated into two-arg
3754 ;;;; versions, and degenerate cases are flushed.
3756 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
3757 (declaim (ftype (function (symbol t list) list) associate-args))
3758 (defun associate-args (function first-arg more-args)
3759 (let ((next (rest more-args))
3760 (arg (first more-args)))
3762 `(,function ,first-arg ,arg)
3763 (associate-args function `(,function ,first-arg ,arg) next))))
3765 ;;; Do source transformations for transitive functions such as +.
3766 ;;; One-arg cases are replaced with the arg and zero arg cases with
3767 ;;; the identity. ONE-ARG-RESULT-TYPE is, if non-NIL, the type to
3768 ;;; ensure (with THE) that the argument in one-argument calls is.
3769 (defun source-transform-transitive (fun args identity
3770 &optional one-arg-result-type)
3771 (declare (symbol fun) (list args))
3774 (1 (if one-arg-result-type
3775 `(values (the ,one-arg-result-type ,(first args)))
3776 `(values ,(first args))))
3779 (associate-args fun (first args) (rest args)))))
3781 (define-source-transform + (&rest args)
3782 (source-transform-transitive '+ args 0 'number))
3783 (define-source-transform * (&rest args)
3784 (source-transform-transitive '* args 1 'number))
3785 (define-source-transform logior (&rest args)
3786 (source-transform-transitive 'logior args 0 'integer))
3787 (define-source-transform logxor (&rest args)
3788 (source-transform-transitive 'logxor args 0 'integer))
3789 (define-source-transform logand (&rest args)
3790 (source-transform-transitive 'logand args -1 'integer))
3791 (define-source-transform logeqv (&rest args)
3792 (source-transform-transitive 'logeqv args -1 'integer))
3794 ;;; Note: we can't use SOURCE-TRANSFORM-TRANSITIVE for GCD and LCM
3795 ;;; because when they are given one argument, they return its absolute
3798 (define-source-transform gcd (&rest args)
3801 (1 `(abs (the integer ,(first args))))
3803 (t (associate-args 'gcd (first args) (rest args)))))
3805 (define-source-transform lcm (&rest args)
3808 (1 `(abs (the integer ,(first args))))
3810 (t (associate-args 'lcm (first args) (rest args)))))
3812 ;;; Do source transformations for intransitive n-arg functions such as
3813 ;;; /. With one arg, we form the inverse. With two args we pass.
3814 ;;; Otherwise we associate into two-arg calls.
3815 (declaim (ftype (function (symbol list t)
3816 (values list &optional (member nil t)))
3817 source-transform-intransitive))
3818 (defun source-transform-intransitive (function args inverse)
3820 ((0 2) (values nil t))
3821 (1 `(,@inverse ,(first args)))
3822 (t (associate-args function (first args) (rest args)))))
3824 (define-source-transform - (&rest args)
3825 (source-transform-intransitive '- args '(%negate)))
3826 (define-source-transform / (&rest args)
3827 (source-transform-intransitive '/ args '(/ 1)))
3829 ;;;; transforming APPLY
3831 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
3832 ;;; only needs to understand one kind of variable-argument call. It is
3833 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
3834 (define-source-transform apply (fun arg &rest more-args)
3835 (let ((args (cons arg more-args)))
3836 `(multiple-value-call ,fun
3837 ,@(mapcar (lambda (x)
3840 (values-list ,(car (last args))))))
3842 ;;;; transforming FORMAT
3844 ;;;; If the control string is a compile-time constant, then replace it
3845 ;;;; with a use of the FORMATTER macro so that the control string is
3846 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
3847 ;;;; or T and the control string is a function (i.e. FORMATTER), then
3848 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
3850 ;;; for compile-time argument count checking.
3852 ;;; FIXME II: In some cases, type information could be correlated; for
3853 ;;; instance, ~{ ... ~} requires a list argument, so if the lvar-type
3854 ;;; of a corresponding argument is known and does not intersect the
3855 ;;; list type, a warning could be signalled.
3856 (defun check-format-args (string args fun)
3857 (declare (type string string))
3858 (unless (typep string 'simple-string)
3859 (setq string (coerce string 'simple-string)))
3860 (multiple-value-bind (min max)
3861 (handler-case (sb!format:%compiler-walk-format-string string args)
3862 (sb!format:format-error (c)
3863 (compiler-warn "~A" c)))
3865 (let ((nargs (length args)))
3868 (warn 'format-too-few-args-warning
3870 "Too few arguments (~D) to ~S ~S: requires at least ~D."
3871 :format-arguments (list nargs fun string min)))
3873 (warn 'format-too-many-args-warning
3875 "Too many arguments (~D) to ~S ~S: uses at most ~D."
3876 :format-arguments (list nargs fun string max))))))))
3878 (defoptimizer (format optimizer) ((dest control &rest args))
3879 (when (constant-lvar-p control)
3880 (let ((x (lvar-value control)))
3882 (check-format-args x args 'format)))))
3884 ;;; We disable this transform in the cross-compiler to save memory in
3885 ;;; the target image; most of the uses of FORMAT in the compiler are for
3886 ;;; error messages, and those don't need to be particularly fast.
3888 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
3889 :policy (>= speed space))
3890 (unless (constant-lvar-p control)
3891 (give-up-ir1-transform "The control string is not a constant."))
3892 (let ((arg-names (make-gensym-list (length args))))
3893 `(lambda (dest control ,@arg-names)
3894 (declare (ignore control))
3895 (format dest (formatter ,(lvar-value control)) ,@arg-names))))
3897 (deftransform format ((stream control &rest args) (stream function &rest t))
3898 (let ((arg-names (make-gensym-list (length args))))
3899 `(lambda (stream control ,@arg-names)
3900 (funcall control stream ,@arg-names)
3903 (deftransform format ((tee control &rest args) ((member t) function &rest t))
3904 (let ((arg-names (make-gensym-list (length args))))
3905 `(lambda (tee control ,@arg-names)
3906 (declare (ignore tee))
3907 (funcall control *standard-output* ,@arg-names)
3910 (deftransform pathname ((pathspec) (pathname) *)
3913 (deftransform pathname ((pathspec) (string) *)
3914 '(values (parse-namestring pathspec)))
3918 `(defoptimizer (,name optimizer) ((control &rest args))
3919 (when (constant-lvar-p control)
3920 (let ((x (lvar-value control)))
3922 (check-format-args x args ',name)))))))
3925 #+sb-xc-host ; Only we should be using these
3928 (def compiler-error)
3930 (def compiler-style-warn)
3931 (def compiler-notify)
3932 (def maybe-compiler-notify)
3935 (defoptimizer (cerror optimizer) ((report control &rest args))
3936 (when (and (constant-lvar-p control)
3937 (constant-lvar-p report))
3938 (let ((x (lvar-value control))
3939 (y (lvar-value report)))
3940 (when (and (stringp x) (stringp y))
3941 (multiple-value-bind (min1 max1)
3943 (sb!format:%compiler-walk-format-string x args)
3944 (sb!format:format-error (c)
3945 (compiler-warn "~A" c)))
3947 (multiple-value-bind (min2 max2)
3949 (sb!format:%compiler-walk-format-string y args)
3950 (sb!format:format-error (c)
3951 (compiler-warn "~A" c)))
3953 (let ((nargs (length args)))
3955 ((< nargs (min min1 min2))
3956 (warn 'format-too-few-args-warning
3958 "Too few arguments (~D) to ~S ~S ~S: ~
3959 requires at least ~D."
3961 (list nargs 'cerror y x (min min1 min2))))
3962 ((> nargs (max max1 max2))
3963 (warn 'format-too-many-args-warning
3965 "Too many arguments (~D) to ~S ~S ~S: ~
3968 (list nargs 'cerror y x (max max1 max2))))))))))))))
3970 (defoptimizer (coerce derive-type) ((value type) node)
3972 ((constant-lvar-p type)
3973 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
3974 ;; but dealing with the niggle that complex canonicalization gets
3975 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
3977 (let* ((specifier (lvar-value type))
3978 (result-typeoid (careful-specifier-type specifier)))
3980 ((null result-typeoid) nil)
3981 ((csubtypep result-typeoid (specifier-type 'number))
3982 ;; the difficult case: we have to cope with ANSI 12.1.5.3
3983 ;; Rule of Canonical Representation for Complex Rationals,
3984 ;; which is a truly nasty delivery to field.
3986 ((csubtypep result-typeoid (specifier-type 'real))
3987 ;; cleverness required here: it would be nice to deduce
3988 ;; that something of type (INTEGER 2 3) coerced to type
3989 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
3990 ;; FLOAT gets its own clause because it's implemented as
3991 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
3994 ((and (numeric-type-p result-typeoid)
3995 (eq (numeric-type-complexp result-typeoid) :real))
3996 ;; FIXME: is this clause (a) necessary or (b) useful?
3998 ((or (csubtypep result-typeoid
3999 (specifier-type '(complex single-float)))
4000 (csubtypep result-typeoid
4001 (specifier-type '(complex double-float)))
4003 (csubtypep result-typeoid
4004 (specifier-type '(complex long-float))))
4005 ;; float complex types are never canonicalized.
4008 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
4009 ;; probably just a COMPLEX or equivalent. So, in that
4010 ;; case, we will return a complex or an object of the
4011 ;; provided type if it's rational:
4012 (type-union result-typeoid
4013 (type-intersection (lvar-type value)
4014 (specifier-type 'rational))))))
4015 ((and (policy node (zerop safety))
4016 (csubtypep result-typeoid (specifier-type '(array * (*)))))
4017 ;; At zero safety the deftransform for COERCE can elide dimension
4018 ;; checks for the things like (COERCE X '(SIMPLE-VECTOR 5)) -- so we
4019 ;; need to simplify the type to drop the dimension information.
4020 (let ((vtype (simplify-vector-type result-typeoid)))
4022 (specifier-type vtype)
4027 ;; OK, the result-type argument isn't constant. However, there
4028 ;; are common uses where we can still do better than just
4029 ;; *UNIVERSAL-TYPE*: e.g. (COERCE X (ARRAY-ELEMENT-TYPE Y)),
4030 ;; where Y is of a known type. See messages on cmucl-imp
4031 ;; 2001-02-14 and sbcl-devel 2002-12-12. We only worry here
4032 ;; about types that can be returned by (ARRAY-ELEMENT-TYPE Y), on
4033 ;; the basis that it's unlikely that other uses are both
4034 ;; time-critical and get to this branch of the COND (non-constant
4035 ;; second argument to COERCE). -- CSR, 2002-12-16
4036 (let ((value-type (lvar-type value))
4037 (type-type (lvar-type type)))
4039 ((good-cons-type-p (cons-type)
4040 ;; Make sure the cons-type we're looking at is something
4041 ;; we're prepared to handle which is basically something
4042 ;; that array-element-type can return.
4043 (or (and (member-type-p cons-type)
4044 (eql 1 (member-type-size cons-type))
4045 (null (first (member-type-members cons-type))))
4046 (let ((car-type (cons-type-car-type cons-type)))
4047 (and (member-type-p car-type)
4048 (eql 1 (member-type-members car-type))
4049 (let ((elt (first (member-type-members car-type))))
4053 (numberp (first elt)))))
4054 (good-cons-type-p (cons-type-cdr-type cons-type))))))
4055 (unconsify-type (good-cons-type)
4056 ;; Convert the "printed" respresentation of a cons
4057 ;; specifier into a type specifier. That is, the
4058 ;; specifier (CONS (EQL SIGNED-BYTE) (CONS (EQL 16)
4059 ;; NULL)) is converted to (SIGNED-BYTE 16).
4060 (cond ((or (null good-cons-type)
4061 (eq good-cons-type 'null))
4063 ((and (eq (first good-cons-type) 'cons)
4064 (eq (first (second good-cons-type)) 'member))
4065 `(,(second (second good-cons-type))
4066 ,@(unconsify-type (caddr good-cons-type))))))
4067 (coerceable-p (part)
4068 ;; Can the value be coerced to the given type? Coerce is
4069 ;; complicated, so we don't handle every possible case
4070 ;; here---just the most common and easiest cases:
4072 ;; * Any REAL can be coerced to a FLOAT type.
4073 ;; * Any NUMBER can be coerced to a (COMPLEX
4074 ;; SINGLE/DOUBLE-FLOAT).
4076 ;; FIXME I: we should also be able to deal with characters
4079 ;; FIXME II: I'm not sure that anything is necessary
4080 ;; here, at least while COMPLEX is not a specialized
4081 ;; array element type in the system. Reasoning: if
4082 ;; something cannot be coerced to the requested type, an
4083 ;; error will be raised (and so any downstream compiled
4084 ;; code on the assumption of the returned type is
4085 ;; unreachable). If something can, then it will be of
4086 ;; the requested type, because (by assumption) COMPLEX
4087 ;; (and other difficult types like (COMPLEX INTEGER)
4088 ;; aren't specialized types.
4089 (let ((coerced-type (careful-specifier-type part)))
4091 (or (and (csubtypep coerced-type (specifier-type 'float))
4092 (csubtypep value-type (specifier-type 'real)))
4093 (and (csubtypep coerced-type
4094 (specifier-type `(or (complex single-float)
4095 (complex double-float))))
4096 (csubtypep value-type (specifier-type 'number)))))))
4097 (process-types (type)
4098 ;; FIXME: This needs some work because we should be able
4099 ;; to derive the resulting type better than just the
4100 ;; type arg of coerce. That is, if X is (INTEGER 10
4101 ;; 20), then (COERCE X 'DOUBLE-FLOAT) should say
4102 ;; (DOUBLE-FLOAT 10d0 20d0) instead of just
4104 (cond ((member-type-p type)
4107 (mapc-member-type-members
4109 (if (coerceable-p member)
4110 (push member members)
4111 (return-from punt *universal-type*)))
4113 (specifier-type `(or ,@members)))))
4114 ((and (cons-type-p type)
4115 (good-cons-type-p type))
4116 (let ((c-type (unconsify-type (type-specifier type))))
4117 (if (coerceable-p c-type)
4118 (specifier-type c-type)
4121 *universal-type*))))
4122 (cond ((union-type-p type-type)
4123 (apply #'type-union (mapcar #'process-types
4124 (union-type-types type-type))))
4125 ((or (member-type-p type-type)
4126 (cons-type-p type-type))
4127 (process-types type-type))
4129 *universal-type*)))))))
4131 (defoptimizer (compile derive-type) ((nameoid function))
4132 (when (csubtypep (lvar-type nameoid)
4133 (specifier-type 'null))
4134 (values-specifier-type '(values function boolean boolean))))
4136 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
4137 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
4138 ;;; optimizer, above).
4139 (defoptimizer (array-element-type derive-type) ((array))
4140 (let ((array-type (lvar-type array)))
4141 (labels ((consify (list)
4144 `(cons (eql ,(car list)) ,(consify (rest list)))))
4145 (get-element-type (a)
4147 (type-specifier (array-type-specialized-element-type a))))
4148 (cond ((eq element-type '*)
4149 (specifier-type 'type-specifier))
4150 ((symbolp element-type)
4151 (make-member-type :members (list element-type)))
4152 ((consp element-type)
4153 (specifier-type (consify element-type)))
4155 (error "can't understand type ~S~%" element-type))))))
4156 (labels ((recurse (type)
4157 (cond ((array-type-p type)
4158 (get-element-type type))
4159 ((union-type-p type)
4161 (mapcar #'recurse (union-type-types type))))
4163 *universal-type*))))
4164 (recurse array-type)))))
4166 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
4167 ;; Like CMU CL, we use HEAPSORT. However, other than that, this code
4168 ;; isn't really related to the CMU CL code, since instead of trying
4169 ;; to generalize the CMU CL code to allow START and END values, this
4170 ;; code has been written from scratch following Chapter 7 of
4171 ;; _Introduction to Algorithms_ by Corman, Rivest, and Shamir.
4172 `(macrolet ((%index (x) `(truly-the index ,x))
4173 (%parent (i) `(ash ,i -1))
4174 (%left (i) `(%index (ash ,i 1)))
4175 (%right (i) `(%index (1+ (ash ,i 1))))
4178 (left (%left i) (%left i)))
4179 ((> left current-heap-size))
4180 (declare (type index i left))
4181 (let* ((i-elt (%elt i))
4182 (i-key (funcall keyfun i-elt))
4183 (left-elt (%elt left))
4184 (left-key (funcall keyfun left-elt)))
4185 (multiple-value-bind (large large-elt large-key)
4186 (if (funcall ,',predicate i-key left-key)
4187 (values left left-elt left-key)
4188 (values i i-elt i-key))
4189 (let ((right (%right i)))
4190 (multiple-value-bind (largest largest-elt)
4191 (if (> right current-heap-size)
4192 (values large large-elt)
4193 (let* ((right-elt (%elt right))
4194 (right-key (funcall keyfun right-elt)))
4195 (if (funcall ,',predicate large-key right-key)
4196 (values right right-elt)
4197 (values large large-elt))))
4198 (cond ((= largest i)
4201 (setf (%elt i) largest-elt
4202 (%elt largest) i-elt
4204 (%sort-vector (keyfun &optional (vtype 'vector))
4205 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had
4206 ;; trouble getting type inference to
4207 ;; propagate all the way through this
4208 ;; tangled mess of inlining. The TRULY-THE
4209 ;; here works around that. -- WHN
4211 `(aref (truly-the ,',vtype ,',',vector)
4212 (%index (+ (%index ,i) start-1)))))
4213 (let (;; Heaps prefer 1-based addressing.
4214 (start-1 (1- ,',start))
4215 (current-heap-size (- ,',end ,',start))
4217 (declare (type (integer -1 #.(1- sb!xc:most-positive-fixnum))
4219 (declare (type index current-heap-size))
4220 (declare (type function keyfun))
4221 (loop for i of-type index
4222 from (ash current-heap-size -1) downto 1 do
4225 (when (< current-heap-size 2)
4227 (rotatef (%elt 1) (%elt current-heap-size))
4228 (decf current-heap-size)
4230 (if (typep ,vector 'simple-vector)
4231 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
4232 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
4234 ;; Special-casing the KEY=NIL case lets us avoid some
4236 (%sort-vector #'identity simple-vector)
4237 (%sort-vector ,key simple-vector))
4238 ;; It's hard to anticipate many speed-critical applications for
4239 ;; sorting vector types other than (VECTOR T), so we just lump
4240 ;; them all together in one slow dynamically typed mess.
4242 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
4243 (%sort-vector (or ,key #'identity))))))
4245 ;;;; debuggers' little helpers
4247 ;;; for debugging when transforms are behaving mysteriously,
4248 ;;; e.g. when debugging a problem with an ASH transform
4249 ;;; (defun foo (&optional s)
4250 ;;; (sb-c::/report-lvar s "S outside WHEN")
4251 ;;; (when (and (integerp s) (> s 3))
4252 ;;; (sb-c::/report-lvar s "S inside WHEN")
4253 ;;; (let ((bound (ash 1 (1- s))))
4254 ;;; (sb-c::/report-lvar bound "BOUND")
4255 ;;; (let ((x (- bound))
4257 ;;; (sb-c::/report-lvar x "X")
4258 ;;; (sb-c::/report-lvar x "Y"))
4259 ;;; `(integer ,(- bound) ,(1- bound)))))
4260 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
4261 ;;; and the function doesn't do anything at all.)
4264 (defknown /report-lvar (t t) null)
4265 (deftransform /report-lvar ((x message) (t t))
4266 (format t "~%/in /REPORT-LVAR~%")
4267 (format t "/(LVAR-TYPE X)=~S~%" (lvar-type x))
4268 (when (constant-lvar-p x)
4269 (format t "/(LVAR-VALUE X)=~S~%" (lvar-value x)))
4270 (format t "/MESSAGE=~S~%" (lvar-value message))
4271 (give-up-ir1-transform "not a real transform"))
4272 (defun /report-lvar (x message)
4273 (declare (ignore x message))))
4276 ;;;; Transforms for internal compiler utilities
4278 ;;; If QUALITY-NAME is constant and a valid name, don't bother
4279 ;;; checking that it's still valid at run-time.
4280 (deftransform policy-quality ((policy quality-name)
4282 (unless (and (constant-lvar-p quality-name)
4283 (policy-quality-name-p (lvar-value quality-name)))
4284 (give-up-ir1-transform))
4285 '(%policy-quality policy quality-name))