Fix comment about *code-coverage-info*.
[sbcl.git] / src / compiler / srctran.lisp
blob97a23b0335a421b4575e9ed3effda264124bf847
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
6 ;;;; more information.
7 ;;;;
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.
14 (in-package "SB!C")
16 ;;; We turn IDENTITY into PROG1 so that it is obvious that it just
17 ;;; returns the first value of its argument. Ditto for VALUES with one
18 ;;; arg.
19 (define-source-transform identity (x) `(prog1 ,x))
20 (define-source-transform values (x) `(prog1 ,x))
22 ;;; CONSTANTLY is pretty much never worth transforming, but it's good to get the type.
23 (defoptimizer (constantly derive-type) ((value))
24 (specifier-type
25 `(function (&rest t) (values ,(type-specifier (lvar-type value)) &optional))))
27 ;;; If the function has a known number of arguments, then return a
28 ;;; lambda with the appropriate fixed number of args. If the
29 ;;; destination is a FUNCALL, then do the &REST APPLY thing, and let
30 ;;; MV optimization figure things out.
31 (deftransform complement ((fun) * * :node node)
32 "open code"
33 (multiple-value-bind (min max)
34 (fun-type-nargs (lvar-type fun))
35 (cond
36 ((and min (eql min max))
37 (let ((dums (make-gensym-list min)))
38 `#'(lambda ,dums (not (funcall fun ,@dums)))))
39 ((awhen (node-lvar node)
40 (let ((dest (lvar-dest it)))
41 (and (combination-p dest)
42 (eq (combination-fun dest) it))))
43 '#'(lambda (&rest args)
44 (not (apply fun args))))
46 (give-up-ir1-transform
47 "The function doesn't have a fixed argument count.")))))
49 ;;;; SYMBOL-VALUE &co
50 (defun derive-symbol-value-type (lvar node)
51 (if (constant-lvar-p lvar)
52 (let* ((sym (lvar-value lvar))
53 (var (maybe-find-free-var sym))
54 (local-type (when var
55 (let ((*lexenv* (node-lexenv node)))
56 (lexenv-find var type-restrictions))))
57 (global-type (info :variable :type sym)))
58 (if local-type
59 (type-intersection local-type global-type)
60 global-type))
61 *universal-type*))
63 (defoptimizer (symbol-value derive-type) ((symbol) node)
64 (derive-symbol-value-type symbol node))
66 (defoptimizer (symbol-global-value derive-type) ((symbol) node)
67 (derive-symbol-value-type symbol node))
69 ;;;; list hackery
71 ;;; Translate CxR into CAR/CDR combos.
72 (defun source-transform-cxr (form env)
73 (declare (ignore env))
74 (if (not (singleton-p (cdr form)))
75 (values nil t)
76 (let* ((name (car form))
77 (string (symbol-name
78 (etypecase name
79 (symbol name)
80 (leaf (leaf-source-name name))))))
81 (do ((i (- (length string) 2) (1- i))
82 (res (cadr form)
83 `(,(ecase (char string i)
84 (#\A 'car)
85 (#\D 'cdr))
86 ,res)))
87 ((zerop i) res)))))
89 ;;; Make source transforms to turn CxR forms into combinations of CAR
90 ;;; and CDR. ANSI specifies that everything up to 4 A/D operations is
91 ;;; defined.
92 ;;; Don't transform CAD*R, they are treated specially for &more args
93 ;;; optimizations
95 (/show0 "about to set CxR source transforms")
96 (loop for i of-type index from 2 upto 4 do
97 ;; Iterate over BUF = all names CxR where x = an I-element
98 ;; string of #\A or #\D characters.
99 (let ((buf (make-string (+ 2 i))))
100 (setf (aref buf 0) #\C
101 (aref buf (1+ i)) #\R)
102 (dotimes (j (ash 2 i))
103 (declare (type index j))
104 (dotimes (k i)
105 (declare (type index k))
106 (setf (aref buf (1+ k))
107 (if (logbitp k j) #\A #\D)))
108 (unless (member buf '("CADR" "CADDR" "CADDDR")
109 :test #'equal)
110 (setf (info :function :source-transform (intern buf))
111 #'source-transform-cxr)))))
112 (/show0 "done setting CxR source transforms")
114 ;;; Turn FIRST..FOURTH and REST into the obvious synonym, assuming
115 ;;; whatever is right for them is right for us. FIFTH..TENTH turn into
116 ;;; Nth, which can be expanded into a CAR/CDR later on if policy
117 ;;; favors it.
118 (define-source-transform rest (x) `(cdr ,x))
119 (define-source-transform first (x) `(car ,x))
120 (define-source-transform second (x) `(cadr ,x))
121 (define-source-transform third (x) `(caddr ,x))
122 (define-source-transform fourth (x) `(cadddr ,x))
123 (define-source-transform fifth (x) `(nth 4 ,x))
124 (define-source-transform sixth (x) `(nth 5 ,x))
125 (define-source-transform seventh (x) `(nth 6 ,x))
126 (define-source-transform eighth (x) `(nth 7 ,x))
127 (define-source-transform ninth (x) `(nth 8 ,x))
128 (define-source-transform tenth (x) `(nth 9 ,x))
130 ;;; LIST with one arg is an extremely common operation (at least inside
131 ;;; SBCL itself); translate it to CONS to take advantage of common
132 ;;; allocation routines.
133 (define-source-transform list (&rest args)
134 (case (length args)
135 (1 `(cons ,(first args) nil))
136 (t (values nil t))))
138 (defoptimizer (list derive-type) ((&rest args))
139 (if args
140 (specifier-type 'cons)
141 (specifier-type 'null)))
143 ;;; And similarly for LIST*.
144 (define-source-transform list* (arg &rest others)
145 (cond ((not others) arg)
146 ((not (cdr others)) `(cons ,arg ,(car others)))
147 (t (values nil t))))
149 (defoptimizer (list* derive-type) ((arg &rest args))
150 (if args
151 (specifier-type 'cons)
152 (lvar-type arg)))
154 (define-source-transform make-list (length &rest rest)
155 (if (or (null rest)
156 ;; Use of &KEY in source xforms doesn't have all the usual semantics.
157 ;; It's better to hand-roll it - cf. transforms for WRITE[-TO-STRING].
158 (typep rest '(cons (eql :initial-element) (cons t null))))
159 ;; Something fishy here- If THE is removed, OPERAND-RESTRICTION-OK
160 ;; returns NIL because type inference on MAKE-LIST never happens.
161 ;; But the fndb entry for %MAKE-LIST is right, so I'm slightly bewildered.
162 `(%make-list (the (integer 0 (,(1- sb!xc:array-dimension-limit))) ,length)
163 ,(second rest))
164 (values nil t))) ; give up
166 (deftransform %make-list ((length item) ((constant-arg (eql 0)) t)) nil)
168 (define-source-transform append (&rest lists)
169 (case (length lists)
170 (0 nil)
171 (1 (car lists))
172 (2 `(sb!impl::append2 ,@lists))
173 (t (values nil t))))
175 (define-source-transform nconc (&rest lists)
176 (case (length lists)
177 (0 ())
178 (1 (car lists))
179 (t (values nil t))))
181 ;;; (append nil nil nil fixnum) => fixnum
182 ;;; (append x x cons x x) => cons
183 ;;; (append x x x x list) => list
184 ;;; (append x x x x sequence) => sequence
185 ;;; (append fixnum x ...) => nil
186 (defun derive-append-type (args)
187 (when (null args)
188 (return-from derive-append-type (specifier-type 'null)))
189 (let* ((cons-type (specifier-type 'cons))
190 (null-type (specifier-type 'null))
191 (list-type (specifier-type 'list))
192 (last (lvar-type (car (last args)))))
193 ;; Derive the actual return type, assuming that all but the last
194 ;; arguments are LISTs (otherwise, APPEND/NCONC doesn't return).
195 (loop with all-nil = t ; all but the last args are NIL?
196 with some-cons = nil ; some args are conses?
197 for (arg next) on args
198 for lvar-type = (type-approx-intersection2 (lvar-type arg)
199 list-type)
200 while next
201 do (multiple-value-bind (typep definitely)
202 (ctypep nil lvar-type)
203 (cond ((type= lvar-type *empty-type*)
204 ;; type mismatch! insert an inline check that'll cause
205 ;; compile-time warnings.
206 (assert-lvar-type arg list-type
207 (lexenv-policy *lexenv*)))
208 (some-cons) ; we know result's a cons -- nothing to do
209 ((and (not typep) definitely) ; can't be NIL
210 (setf some-cons t)) ; must be a CONS
211 (all-nil
212 (setf all-nil (csubtypep lvar-type null-type)))))
213 finally
214 ;; if some of the previous arguments are CONSes so is the result;
215 ;; if all the previous values are NIL, we're a fancy identity;
216 ;; otherwise, could be either
217 (return (cond (some-cons cons-type)
218 (all-nil last)
219 (t (type-union last cons-type)))))))
221 (defoptimizer (append derive-type) ((&rest args))
222 (derive-append-type args))
224 (defoptimizer (sb!impl::append2 derive-type) ((&rest args))
225 (derive-append-type args))
227 (defoptimizer (nconc derive-type) ((&rest args))
228 (derive-append-type args))
230 ;;; Translate RPLACx to LET and SETF.
231 (define-source-transform rplaca (x y)
232 (once-only ((n-x x))
233 `(progn
234 (setf (car ,n-x) ,y)
235 ,n-x)))
236 (define-source-transform rplacd (x y)
237 (once-only ((n-x x))
238 `(progn
239 (setf (cdr ,n-x) ,y)
240 ,n-x)))
242 (deftransform last ((list &optional n) (t &optional t))
243 (let ((c (constant-lvar-p n)))
244 (cond ((or (not n)
245 (and c (eql 1 (lvar-value n))))
246 '(%last1 list))
247 ((and c (eql 0 (lvar-value n)))
248 '(%last0 list))
250 (let ((type (lvar-type n)))
251 (cond ((csubtypep type (specifier-type 'fixnum))
252 '(%lastn/fixnum list n))
253 ((csubtypep type (specifier-type 'bignum))
254 '(%lastn/bignum list n))
256 (give-up-ir1-transform "second argument type too vague"))))))))
258 (define-source-transform gethash (&rest args)
259 (case (length args)
260 (2 `(sb!impl::gethash3 ,@args nil))
261 (3 `(sb!impl::gethash3 ,@args))
262 (t (values nil t))))
263 (define-source-transform get (&rest args)
264 (case (length args)
265 (2 `(sb!impl::get3 ,@args nil))
266 (3 `(sb!impl::get3 ,@args))
267 (t (values nil t))))
269 (defvar *default-nthcdr-open-code-limit* 6)
270 (defvar *extreme-nthcdr-open-code-limit* 20)
272 (deftransform nthcdr ((n l) (unsigned-byte t) * :node node)
273 "convert NTHCDR to CAxxR"
274 (unless (constant-lvar-p n)
275 (give-up-ir1-transform))
276 (let ((n (lvar-value n)))
277 (when (> n
278 (if (policy node (and (= speed 3) (= space 0)))
279 *extreme-nthcdr-open-code-limit*
280 *default-nthcdr-open-code-limit*))
281 (give-up-ir1-transform))
283 (labels ((frob (n)
284 (if (zerop n)
286 `(cdr ,(frob (1- n))))))
287 (frob n))))
289 ;;;; arithmetic and numerology
291 (define-source-transform plusp (x) `(> ,x 0))
292 (define-source-transform minusp (x) `(< ,x 0))
293 (define-source-transform zerop (x) `(= ,x 0))
295 (define-source-transform 1+ (x) `(+ ,x 1))
296 (define-source-transform 1- (x) `(- ,x 1))
298 (define-source-transform oddp (x) `(logtest ,x 1))
299 (define-source-transform evenp (x) `(not (logtest ,x 1)))
301 ;;; Note that all the integer division functions are available for
302 ;;; inline expansion.
304 (macrolet ((deffrob (fun)
305 `(define-source-transform ,fun (x &optional (y nil y-p))
306 (declare (ignore y))
307 (if y-p
308 (values nil t)
309 `(,',fun ,x 1)))))
310 (deffrob truncate)
311 (deffrob round)
312 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
313 (deffrob floor)
314 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
315 (deffrob ceiling))
317 ;;; This used to be a source transform (hence the lack of restrictions
318 ;;; on the argument types), but we make it a regular transform so that
319 ;;; the VM has a chance to see the bare LOGTEST and potentiall choose
320 ;;; to implement it differently. --njf, 06-02-2006
322 ;;; Other transforms may be useful even with direct LOGTEST VOPs; let
323 ;;; them fire (including the type-directed constant folding below), but
324 ;;; disable the inlining rewrite in such cases. -- PK, 2013-05-20
325 (deftransform logtest ((x y) * * :node node)
326 (let ((type (two-arg-derive-type x y
327 #'logand-derive-type-aux
328 #'logand)))
329 (multiple-value-bind (typep definitely)
330 (ctypep 0 type)
331 (cond ((and (not typep) definitely)
333 ((type= type (specifier-type '(eql 0)))
334 nil)
335 ((neq :default (combination-implementation-style node))
336 (give-up-ir1-transform))
338 `(not (zerop (logand x y))))))))
340 (deftransform logbitp
341 ((index integer) (unsigned-byte (or (signed-byte #.sb!vm:n-word-bits)
342 (unsigned-byte #.sb!vm:n-word-bits))))
343 (flet ((general-case ()
344 `(if (>= index #.sb!vm:n-word-bits)
345 (minusp integer)
346 (not (zerop (logand integer (ash 1 index)))))))
347 (if (constant-lvar-p integer)
348 (let ((val (lvar-value integer)))
349 (cond ((eql val 0) nil)
350 ((eql val -1) t)
351 (t (general-case))))
352 (general-case))))
354 (define-source-transform byte (size position)
355 `(cons ,size ,position))
356 (define-source-transform byte-size (spec) `(car ,spec))
357 (define-source-transform byte-position (spec) `(cdr ,spec))
358 (define-source-transform ldb-test (bytespec integer)
359 `(not (zerop (mask-field ,bytespec ,integer))))
361 ;;; With the ratio and complex accessors, we pick off the "identity"
362 ;;; case, and use a primitive to handle the cell access case.
363 (define-source-transform numerator (num)
364 (once-only ((n-num `(the rational ,num)))
365 `(if (ratiop ,n-num)
366 (%numerator ,n-num)
367 ,n-num)))
368 (define-source-transform denominator (num)
369 (once-only ((n-num `(the rational ,num)))
370 `(if (ratiop ,n-num)
371 (%denominator ,n-num)
372 1)))
374 ;;;; interval arithmetic for computing bounds
375 ;;;;
376 ;;;; This is a set of routines for operating on intervals. It
377 ;;;; implements a simple interval arithmetic package. Although SBCL
378 ;;;; has an interval type in NUMERIC-TYPE, we choose to use our own
379 ;;;; for two reasons:
380 ;;;;
381 ;;;; 1. This package is simpler than NUMERIC-TYPE.
382 ;;;;
383 ;;;; 2. It makes debugging much easier because you can just strip
384 ;;;; out these routines and test them independently of SBCL. (This is a
385 ;;;; big win!)
386 ;;;;
387 ;;;; One disadvantage is a probable increase in consing because we
388 ;;;; have to create these new interval structures even though
389 ;;;; numeric-type has everything we want to know. Reason 2 wins for
390 ;;;; now.
392 ;;; Support operations that mimic real arithmetic comparison
393 ;;; operators, but imposing a total order on the floating points such
394 ;;; that negative zeros are strictly less than positive zeros.
395 (macrolet ((def (name op)
396 `(defun ,name (x y)
397 (declare (real x y))
398 (if (and (floatp x) (floatp y) (zerop x) (zerop y))
399 (,op (float-sign x) (float-sign y))
400 (,op x y)))))
401 (def signed-zero->= >=)
402 (def signed-zero-> >)
403 (def signed-zero-= =)
404 (def signed-zero-< <)
405 (def signed-zero-<= <=))
407 (defun make-interval (&key low high)
408 (labels ((normalize-bound (val)
409 (cond #-sb-xc-host
410 ((and (floatp val)
411 (float-infinity-p val))
412 ;; Handle infinities.
413 nil)
414 ((or (numberp val)
415 (eq val nil))
416 ;; Handle any closed bounds.
417 val)
418 ((listp val)
419 ;; We have an open bound. Normalize the numeric
420 ;; bound. If the normalized bound is still a number
421 ;; (not nil), keep the bound open. Otherwise, the
422 ;; bound is really unbounded, so drop the openness.
423 (let ((new-val (normalize-bound (first val))))
424 (when new-val
425 ;; The bound exists, so keep it open still.
426 (list new-val))))
428 (error "unknown bound type in MAKE-INTERVAL")))))
429 (%make-interval (normalize-bound low)
430 (normalize-bound high))))
432 ;;; Apply the function F to a bound X. If X is an open bound and the
433 ;;; function is declared strictly monotonic, then the result will be
434 ;;; open. IF X is NIL, the result is NIL.
435 (defun bound-func (f x strict)
436 (declare (type function f))
437 (and x
438 (handler-case
439 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
440 ;; With these traps masked, we might get things like infinity
441 ;; or negative infinity returned. Check for this and return
442 ;; NIL to indicate unbounded.
443 (let ((y (funcall f (type-bound-number x))))
444 (if (and (floatp y)
445 (float-infinity-p y))
447 (set-bound y (and strict (consp x))))))
448 ;; Some numerical operations will signal SIMPLE-TYPE-ERROR, e.g.
449 ;; in the course of converting a bignum to a float. Default to
450 ;; NIL in that case.
451 (simple-type-error ()))))
453 (defun safe-double-coercion-p (x)
454 (or (typep x 'double-float)
455 (<= most-negative-double-float x most-positive-double-float)))
457 (defun safe-single-coercion-p (x)
458 (or (typep x 'single-float)
459 (and
460 ;; Fix for bug 420, and related issues: during type derivation we often
461 ;; end up deriving types for both
463 ;; (some-op <int> <single>)
464 ;; and
465 ;; (some-op (coerce <int> 'single-float) <single>)
467 ;; or other equivalent transformed forms. The problem with this
468 ;; is that on x86 (+ <int> <single>) is on the machine level
469 ;; equivalent of
471 ;; (coerce (+ (coerce <int> 'double-float)
472 ;; (coerce <single> 'double-float))
473 ;; 'single-float)
475 ;; so if the result of (coerce <int> 'single-float) is not exact, the
476 ;; derived types for the transformed forms will have an empty
477 ;; intersection -- which in turn means that the compiler will conclude
478 ;; that the call never returns, and all hell breaks lose when it *does*
479 ;; return at runtime. (This affects not just +, but other operators are
480 ;; well.)
482 ;; See also: SAFE-CTYPE-FOR-SINGLE-COERCION-P
484 ;; FIXME: If we ever add SSE-support for x86, this conditional needs to
485 ;; change.
486 #!+x86
487 (not (typep x `(or (integer * (,most-negative-exactly-single-float-fixnum))
488 (integer (,most-positive-exactly-single-float-fixnum) *))))
489 (<= most-negative-single-float x most-positive-single-float))))
491 ;;; Apply a binary operator OP to two bounds X and Y. The result is
492 ;;; NIL if either is NIL. Otherwise bound is computed and the result
493 ;;; is open if either X or Y is open.
495 ;;; FIXME: only used in this file, not needed in target runtime
497 ;;; ANSI contaigon specifies coercion to floating point if one of the
498 ;;; arguments is floating point. Here we should check to be sure that
499 ;;; the other argument is within the bounds of that floating point
500 ;;; type.
502 (defmacro safely-binop (op x y)
503 `(cond
504 ((typep ,x 'double-float)
505 (when (safe-double-coercion-p ,y)
506 (,op ,x ,y)))
507 ((typep ,y 'double-float)
508 (when (safe-double-coercion-p ,x)
509 (,op ,x ,y)))
510 ((typep ,x 'single-float)
511 (when (safe-single-coercion-p ,y)
512 (,op ,x ,y)))
513 ((typep ,y 'single-float)
514 (when (safe-single-coercion-p ,x)
515 (,op ,x ,y)))
516 (t (,op ,x ,y))))
518 (defmacro bound-binop (op x y)
519 (with-unique-names (xb yb res)
520 `(and ,x ,y
521 (with-float-traps-masked (:underflow :overflow :inexact :divide-by-zero)
522 (let* ((,xb (type-bound-number ,x))
523 (,yb (type-bound-number ,y))
524 (,res (safely-binop ,op ,xb ,yb)))
525 (set-bound ,res
526 (and (or (consp ,x) (consp ,y))
527 ;; Open bounds can very easily be messed up
528 ;; by FP rounding, so take care here.
529 ,(case op
531 ;; Multiplying a greater-than-zero with
532 ;; less than one can round to zero.
533 `(or (not (fp-zero-p ,res))
534 (cond ((and (consp ,x) (fp-zero-p ,xb))
535 (>= (abs ,yb) 1))
536 ((and (consp ,y) (fp-zero-p ,yb))
537 (>= (abs ,xb) 1)))))
539 ;; Dividing a greater-than-zero with
540 ;; greater than one can round to zero.
541 `(or (not (fp-zero-p ,res))
542 (cond ((and (consp ,x) (fp-zero-p ,xb))
543 (<= (abs ,yb) 1))
544 ((and (consp ,y) (fp-zero-p ,yb))
545 (<= (abs ,xb) 1)))))
546 ((+ -)
547 ;; Adding or subtracting greater-than-zero
548 ;; can end up with identity.
549 `(and (not (fp-zero-p ,xb))
550 (not (fp-zero-p ,yb))))))))))))
552 (defun coercion-loses-precision-p (val type)
553 (typecase val
554 (single-float)
555 (double-float (subtypep type 'single-float))
556 (rational (subtypep type 'float))
557 (t (bug "Unexpected arguments to bounds coercion: ~S ~S" val type))))
559 (defun coerce-for-bound (val type)
560 (if (consp val)
561 (let ((xbound (coerce-for-bound (car val) type)))
562 (if (coercion-loses-precision-p (car val) type)
563 xbound
564 (list xbound)))
565 (cond
566 ((subtypep type 'double-float)
567 (if (<= most-negative-double-float val most-positive-double-float)
568 (coerce val type)))
569 ((or (subtypep type 'single-float) (subtypep type 'float))
570 ;; coerce to float returns a single-float
571 (if (<= most-negative-single-float val most-positive-single-float)
572 (coerce val type)))
573 (t (coerce val type)))))
575 (defun coerce-and-truncate-floats (val type)
576 (when val
577 (if (consp val)
578 (let ((xbound (coerce-for-bound (car val) type)))
579 (if (coercion-loses-precision-p (car val) type)
580 xbound
581 (list xbound)))
582 (cond
583 ((subtypep type 'double-float)
584 (if (<= most-negative-double-float val most-positive-double-float)
585 (coerce val type)
586 (if (< val most-negative-double-float)
587 most-negative-double-float most-positive-double-float)))
588 ((or (subtypep type 'single-float) (subtypep type 'float))
589 ;; coerce to float returns a single-float
590 (if (<= most-negative-single-float val most-positive-single-float)
591 (coerce val type)
592 (if (< val most-negative-single-float)
593 most-negative-single-float most-positive-single-float)))
594 (t (coerce val type))))))
596 ;;; Convert a numeric-type object to an interval object.
597 (defun numeric-type->interval (x)
598 (declare (type numeric-type x))
599 (make-interval :low (numeric-type-low x)
600 :high (numeric-type-high x)))
602 (defun type-approximate-interval (type)
603 (declare (type ctype type))
604 (let ((types (prepare-arg-for-derive-type type))
605 (result nil))
606 (dolist (type types)
607 (let ((type (if (member-type-p type)
608 (convert-member-type type)
609 type)))
610 (unless (numeric-type-p type)
611 (return-from type-approximate-interval nil))
612 (let ((interval (numeric-type->interval type)))
613 (setq result
614 (if result
615 (interval-approximate-union result interval)
616 interval)))))
617 result))
619 (defun copy-interval-limit (limit)
620 (if (numberp limit)
621 limit
622 (copy-list limit)))
624 (defun copy-interval (x)
625 (declare (type interval x))
626 (make-interval :low (copy-interval-limit (interval-low x))
627 :high (copy-interval-limit (interval-high x))))
629 ;;; Given a point P contained in the interval X, split X into two
630 ;;; intervals at the point P. If CLOSE-LOWER is T, then the left
631 ;;; interval contains P. If CLOSE-UPPER is T, the right interval
632 ;;; contains P. You can specify both to be T or NIL.
633 (defun interval-split (p x &optional close-lower close-upper)
634 (declare (type number p)
635 (type interval x))
636 (list (make-interval :low (copy-interval-limit (interval-low x))
637 :high (if close-lower p (list p)))
638 (make-interval :low (if close-upper (list p) p)
639 :high (copy-interval-limit (interval-high x)))))
641 ;;; Return the closure of the interval. That is, convert open bounds
642 ;;; to closed bounds.
643 (defun interval-closure (x)
644 (declare (type interval x))
645 (make-interval :low (type-bound-number (interval-low x))
646 :high (type-bound-number (interval-high x))))
648 ;;; For an interval X, if X >= POINT, return '+. If X <= POINT, return
649 ;;; '-. Otherwise return NIL.
650 (defun interval-range-info (x &optional (point 0))
651 (declare (type interval x))
652 (let ((lo (interval-low x))
653 (hi (interval-high x)))
654 (cond ((and lo (signed-zero->= (type-bound-number lo) point))
656 ((and hi (signed-zero->= point (type-bound-number hi)))
659 nil))))
661 ;;; Test to see whether the interval X is bounded. HOW determines the
662 ;;; test, and should be either ABOVE, BELOW, or BOTH.
663 (defun interval-bounded-p (x how)
664 (declare (type interval x))
665 (ecase how
666 (above
667 (interval-high x))
668 (below
669 (interval-low x))
670 (both
671 (and (interval-low x) (interval-high x)))))
673 ;;; See whether the interval X contains the number P, taking into
674 ;;; account that the interval might not be closed.
675 (defun interval-contains-p (p x)
676 (declare (type number p)
677 (type interval x))
678 ;; Does the interval X contain the number P? This would be a lot
679 ;; easier if all intervals were closed!
680 (let ((lo (interval-low x))
681 (hi (interval-high x)))
682 (cond ((and lo hi)
683 ;; The interval is bounded
684 (if (and (signed-zero-<= (type-bound-number lo) p)
685 (signed-zero-<= p (type-bound-number hi)))
686 ;; P is definitely in the closure of the interval.
687 ;; We just need to check the end points now.
688 (cond ((signed-zero-= p (type-bound-number lo))
689 (numberp lo))
690 ((signed-zero-= p (type-bound-number hi))
691 (numberp hi))
692 (t t))
693 nil))
695 ;; Interval with upper bound
696 (if (signed-zero-< p (type-bound-number hi))
698 (and (numberp hi) (signed-zero-= p hi))))
700 ;; Interval with lower bound
701 (if (signed-zero-> p (type-bound-number lo))
703 (and (numberp lo) (signed-zero-= p lo))))
705 ;; Interval with no bounds
706 t))))
708 ;;; Determine whether two intervals X and Y intersect. Return T if so.
709 ;;; If CLOSED-INTERVALS-P is T, the treat the intervals as if they
710 ;;; were closed. Otherwise the intervals are treated as they are.
712 ;;; Thus if X = [0, 1) and Y = (1, 2), then they do not intersect
713 ;;; because no element in X is in Y. However, if CLOSED-INTERVALS-P
714 ;;; is T, then they do intersect because we use the closure of X = [0,
715 ;;; 1] and Y = [1, 2] to determine intersection.
716 (defun interval-intersect-p (x y &optional closed-intervals-p)
717 (declare (type interval x y))
718 (and (interval-intersection/difference (if closed-intervals-p
719 (interval-closure x)
721 (if closed-intervals-p
722 (interval-closure y)
726 ;;; Are the two intervals adjacent? That is, is there a number
727 ;;; between the two intervals that is not an element of either
728 ;;; interval? If so, they are not adjacent. For example [0, 1) and
729 ;;; [1, 2] are adjacent but [0, 1) and (1, 2] are not because 1 lies
730 ;;; between both intervals.
731 (defun interval-adjacent-p (x y)
732 (declare (type interval x y))
733 (flet ((adjacent (lo hi)
734 ;; Check to see whether lo and hi are adjacent. If either is
735 ;; nil, they can't be adjacent.
736 (when (and lo hi (= (type-bound-number lo) (type-bound-number hi)))
737 ;; The bounds are equal. They are adjacent if one of
738 ;; them is closed (a number). If both are open (consp),
739 ;; then there is a number that lies between them.
740 (or (numberp lo) (numberp hi)))))
741 (or (adjacent (interval-low y) (interval-high x))
742 (adjacent (interval-low x) (interval-high y)))))
744 ;;; Compute the intersection and difference between two intervals.
745 ;;; Two values are returned: the intersection and the difference.
747 ;;; Let the two intervals be X and Y, and let I and D be the two
748 ;;; values returned by this function. Then I = X intersect Y. If I
749 ;;; is NIL (the empty set), then D is X union Y, represented as the
750 ;;; list of X and Y. If I is not the empty set, then D is (X union Y)
751 ;;; - I, which is a list of two intervals.
753 ;;; For example, let X = [1,5] and Y = [-1,3). Then I = [1,3) and D =
754 ;;; [-1,1) union [3,5], which is returned as a list of two intervals.
755 (defun interval-intersection/difference (x y)
756 (declare (type interval x y))
757 (let ((x-lo (interval-low x))
758 (x-hi (interval-high x))
759 (y-lo (interval-low y))
760 (y-hi (interval-high y)))
761 (labels
762 ((opposite-bound (p)
763 ;; If p is an open bound, make it closed. If p is a closed
764 ;; bound, make it open.
765 (if (listp p)
766 (first p)
767 (list p)))
768 (test-number (p int bound)
769 ;; Test whether P is in the interval.
770 (let ((pn (type-bound-number p)))
771 (when (interval-contains-p pn (interval-closure int))
772 ;; Check for endpoints.
773 (let* ((lo (interval-low int))
774 (hi (interval-high int))
775 (lon (type-bound-number lo))
776 (hin (type-bound-number hi)))
777 (cond
778 ;; Interval may be a point.
779 ((and lon hin (= lon hin pn))
780 (and (numberp p) (numberp lo) (numberp hi)))
781 ;; Point matches the low end.
782 ;; [P] [P,?} => TRUE [P] (P,?} => FALSE
783 ;; (P [P,?} => TRUE P) [P,?} => FALSE
784 ;; (P (P,?} => TRUE P) (P,?} => FALSE
785 ((and lon (= pn lon))
786 (or (and (numberp p) (numberp lo))
787 (and (consp p) (eq :low bound))))
788 ;; [P] {?,P] => TRUE [P] {?,P) => FALSE
789 ;; P) {?,P] => TRUE (P {?,P] => FALSE
790 ;; P) {?,P) => TRUE (P {?,P) => FALSE
791 ((and hin (= pn hin))
792 (or (and (numberp p) (numberp hi))
793 (and (consp p) (eq :high bound))))
794 ;; Not an endpoint, all is well.
796 t))))))
797 (test-lower-bound (p int)
798 ;; P is a lower bound of an interval.
799 (if p
800 (test-number p int :low)
801 (not (interval-bounded-p int 'below))))
802 (test-upper-bound (p int)
803 ;; P is an upper bound of an interval.
804 (if p
805 (test-number p int :high)
806 (not (interval-bounded-p int 'above)))))
807 (let ((x-lo-in-y (test-lower-bound x-lo y))
808 (x-hi-in-y (test-upper-bound x-hi y))
809 (y-lo-in-x (test-lower-bound y-lo x))
810 (y-hi-in-x (test-upper-bound y-hi x)))
811 (cond ((or x-lo-in-y x-hi-in-y y-lo-in-x y-hi-in-x)
812 ;; Intervals intersect. Let's compute the intersection
813 ;; and the difference.
814 (multiple-value-bind (lo left-lo left-hi)
815 (cond (x-lo-in-y (values x-lo y-lo (opposite-bound x-lo)))
816 (y-lo-in-x (values y-lo x-lo (opposite-bound y-lo))))
817 (multiple-value-bind (hi right-lo right-hi)
818 (cond (x-hi-in-y
819 (values x-hi (opposite-bound x-hi) y-hi))
820 (y-hi-in-x
821 (values y-hi (opposite-bound y-hi) x-hi)))
822 (values (make-interval :low lo :high hi)
823 (list (make-interval :low left-lo
824 :high left-hi)
825 (make-interval :low right-lo
826 :high right-hi))))))
828 (values nil (list x y))))))))
830 ;;; If intervals X and Y intersect, return a new interval that is the
831 ;;; union of the two. If they do not intersect, return NIL.
832 (defun interval-merge-pair (x y)
833 (declare (type interval x y))
834 ;; If x and y intersect or are adjacent, create the union.
835 ;; Otherwise return nil
836 (when (or (interval-intersect-p x y)
837 (interval-adjacent-p x y))
838 (flet ((select-bound (x1 x2 min-op max-op)
839 (let ((x1-val (type-bound-number x1))
840 (x2-val (type-bound-number x2)))
841 (cond ((and x1 x2)
842 ;; Both bounds are finite. Select the right one.
843 (cond ((funcall min-op x1-val x2-val)
844 ;; x1 is definitely better.
846 ((funcall max-op x1-val x2-val)
847 ;; x2 is definitely better.
850 ;; Bounds are equal. Select either
851 ;; value and make it open only if
852 ;; both were open.
853 (set-bound x1-val (and (consp x1) (consp x2))))))
855 ;; At least one bound is not finite. The
856 ;; non-finite bound always wins.
857 nil)))))
858 (let* ((x-lo (copy-interval-limit (interval-low x)))
859 (x-hi (copy-interval-limit (interval-high x)))
860 (y-lo (copy-interval-limit (interval-low y)))
861 (y-hi (copy-interval-limit (interval-high y))))
862 (make-interval :low (select-bound x-lo y-lo #'< #'>)
863 :high (select-bound x-hi y-hi #'> #'<))))))
865 ;;; return the minimal interval, containing X and Y
866 (defun interval-approximate-union (x y)
867 (cond ((interval-merge-pair x y))
868 ((interval-< x y)
869 (make-interval :low (copy-interval-limit (interval-low x))
870 :high (copy-interval-limit (interval-high y))))
872 (make-interval :low (copy-interval-limit (interval-low y))
873 :high (copy-interval-limit (interval-high x))))))
875 ;;; basic arithmetic operations on intervals. We probably should do
876 ;;; true interval arithmetic here, but it's complicated because we
877 ;;; have float and integer types and bounds can be open or closed.
879 ;;; the negative of an interval
880 (defun interval-neg (x)
881 (declare (type interval x))
882 (make-interval :low (bound-func #'- (interval-high x) t)
883 :high (bound-func #'- (interval-low x) t)))
885 ;;; Add two intervals.
886 (defun interval-add (x y)
887 (declare (type interval x y))
888 (make-interval :low (bound-binop + (interval-low x) (interval-low y))
889 :high (bound-binop + (interval-high x) (interval-high y))))
891 ;;; Subtract two intervals.
892 (defun interval-sub (x y)
893 (declare (type interval x y))
894 (make-interval :low (bound-binop - (interval-low x) (interval-high y))
895 :high (bound-binop - (interval-high x) (interval-low y))))
897 ;;; Multiply two intervals.
898 (defun interval-mul (x y)
899 (declare (type interval x y))
900 (flet ((bound-mul (x y)
901 (cond ((or (null x) (null y))
902 ;; Multiply by infinity is infinity
903 nil)
904 ((or (and (numberp x) (zerop x))
905 (and (numberp y) (zerop y)))
906 ;; Multiply by closed zero is special. The result
907 ;; is always a closed bound. But don't replace this
908 ;; with zero; we want the multiplication to produce
909 ;; the correct signed zero, if needed. Use SIGNUM
910 ;; to avoid trying to multiply huge bignums with 0.0.
911 (* (signum (type-bound-number x)) (signum (type-bound-number y))))
912 ((or (and (floatp x) (float-infinity-p x))
913 (and (floatp y) (float-infinity-p y)))
914 ;; Infinity times anything is infinity
915 nil)
917 ;; General multiply. The result is open if either is open.
918 (bound-binop * x y)))))
919 (let ((x-range (interval-range-info x))
920 (y-range (interval-range-info y)))
921 (cond ((null x-range)
922 ;; Split x into two and multiply each separately
923 (destructuring-bind (x- x+) (interval-split 0 x t t)
924 (interval-merge-pair (interval-mul x- y)
925 (interval-mul x+ y))))
926 ((null y-range)
927 ;; Split y into two and multiply each separately
928 (destructuring-bind (y- y+) (interval-split 0 y t t)
929 (interval-merge-pair (interval-mul x y-)
930 (interval-mul x y+))))
931 ((eq x-range '-)
932 (interval-neg (interval-mul (interval-neg x) y)))
933 ((eq y-range '-)
934 (interval-neg (interval-mul x (interval-neg y))))
935 ((and (eq x-range '+) (eq y-range '+))
936 ;; If we are here, X and Y are both positive.
937 (make-interval
938 :low (bound-mul (interval-low x) (interval-low y))
939 :high (bound-mul (interval-high x) (interval-high y))))
941 (bug "excluded case in INTERVAL-MUL"))))))
943 ;;; Divide two intervals.
944 (defun interval-div (top bot)
945 (declare (type interval top bot))
946 (flet ((bound-div (x y y-low-p)
947 ;; Compute x/y
948 (cond ((null y)
949 ;; Divide by infinity means result is 0. However,
950 ;; we need to watch out for the sign of the result,
951 ;; to correctly handle signed zeros. We also need
952 ;; to watch out for positive or negative infinity.
953 (if (floatp (type-bound-number x))
954 (if y-low-p
955 (- (float-sign (type-bound-number x) 0.0))
956 (float-sign (type-bound-number x) 0.0))
958 ((zerop (type-bound-number y))
959 ;; Divide by zero means result is infinity
960 nil)
962 (bound-binop / x y)))))
963 (let ((top-range (interval-range-info top))
964 (bot-range (interval-range-info bot)))
965 (cond ((null bot-range)
966 ;; The denominator contains zero, so anything goes!
967 (make-interval))
968 ((eq bot-range '-)
969 ;; Denominator is negative so flip the sign, compute the
970 ;; result, and flip it back.
971 (interval-neg (interval-div top (interval-neg bot))))
972 ((null top-range)
973 ;; Split top into two positive and negative parts, and
974 ;; divide each separately
975 (destructuring-bind (top- top+) (interval-split 0 top t t)
976 (or (interval-merge-pair (interval-div top- bot)
977 (interval-div top+ bot))
978 (make-interval))))
979 ((eq top-range '-)
980 ;; Top is negative so flip the sign, divide, and flip the
981 ;; sign of the result.
982 (interval-neg (interval-div (interval-neg top) bot)))
983 ((and (eq top-range '+) (eq bot-range '+))
984 ;; the easy case
985 (make-interval
986 :low (bound-div (interval-low top) (interval-high bot) t)
987 :high (bound-div (interval-high top) (interval-low bot) nil)))
989 (bug "excluded case in INTERVAL-DIV"))))))
991 ;;; Apply the function F to the interval X. If X = [a, b], then the
992 ;;; result is [f(a), f(b)]. It is up to the user to make sure the
993 ;;; result makes sense. It will if F is monotonic increasing (or, if
994 ;;; the interval is closed, non-decreasing).
996 ;;; (Actually most uses of INTERVAL-FUNC are coercions to float types,
997 ;;; which are not monotonic increasing, so default to calling
998 ;;; BOUND-FUNC with a non-strict argument).
999 (defun interval-func (f x &optional increasing)
1000 (declare (type function f)
1001 (type interval x))
1002 (let ((lo (bound-func f (interval-low x) increasing))
1003 (hi (bound-func f (interval-high x) increasing)))
1004 (make-interval :low lo :high hi)))
1006 ;;; Return T if X < Y. That is every number in the interval X is
1007 ;;; always less than any number in the interval Y.
1008 (defun interval-< (x y)
1009 (declare (type interval x y))
1010 ;; X < Y only if X is bounded above, Y is bounded below, and they
1011 ;; don't overlap.
1012 (when (and (interval-bounded-p x 'above)
1013 (interval-bounded-p y 'below))
1014 ;; Intervals are bounded in the appropriate way. Make sure they
1015 ;; don't overlap.
1016 (let ((left (interval-high x))
1017 (right (interval-low y)))
1018 (cond ((> (type-bound-number left)
1019 (type-bound-number right))
1020 ;; The intervals definitely overlap, so result is NIL.
1021 nil)
1022 ((< (type-bound-number left)
1023 (type-bound-number right))
1024 ;; The intervals definitely don't touch, so result is T.
1027 ;; Limits are equal. Check for open or closed bounds.
1028 ;; Don't overlap if one or the other are open.
1029 (or (consp left) (consp right)))))))
1031 ;;; Return T if X >= Y. That is, every number in the interval X is
1032 ;;; always greater than any number in the interval Y.
1033 (defun interval->= (x y)
1034 (declare (type interval x y))
1035 ;; X >= Y if lower bound of X >= upper bound of Y
1036 (when (and (interval-bounded-p x 'below)
1037 (interval-bounded-p y 'above))
1038 (>= (type-bound-number (interval-low x))
1039 (type-bound-number (interval-high y)))))
1041 ;;; Return T if X = Y.
1042 (defun interval-= (x y)
1043 (declare (type interval x y))
1044 (and (interval-bounded-p x 'both)
1045 (interval-bounded-p y 'both)
1046 (flet ((bound (v)
1047 (if (numberp v)
1049 ;; Open intervals cannot be =
1050 (return-from interval-= nil))))
1051 ;; Both intervals refer to the same point
1052 (= (bound (interval-high x)) (bound (interval-low x))
1053 (bound (interval-high y)) (bound (interval-low y))))))
1055 ;;; Return T if X /= Y
1056 (defun interval-/= (x y)
1057 (not (interval-intersect-p x y)))
1059 ;;; Return an interval that is the absolute value of X. Thus, if
1060 ;;; X = [-1 10], the result is [0, 10].
1061 (defun interval-abs (x)
1062 (declare (type interval x))
1063 (case (interval-range-info x)
1065 (copy-interval x))
1067 (interval-neg x))
1069 (destructuring-bind (x- x+) (interval-split 0 x t t)
1070 (interval-merge-pair (interval-neg x-) x+)))))
1072 ;;; Compute the square of an interval.
1073 (defun interval-sqr (x)
1074 (declare (type interval x))
1075 (interval-func (lambda (x) (* x x)) (interval-abs x)))
1077 ;;;; numeric DERIVE-TYPE methods
1079 ;;; a utility for defining derive-type methods of integer operations. If
1080 ;;; the types of both X and Y are integer types, then we compute a new
1081 ;;; integer type with bounds determined by FUN when applied to X and Y.
1082 ;;; Otherwise, we use NUMERIC-CONTAGION.
1083 (defun derive-integer-type-aux (x y fun)
1084 (declare (type function fun))
1085 (if (and (numeric-type-p x) (numeric-type-p y)
1086 (eq (numeric-type-class x) 'integer)
1087 (eq (numeric-type-class y) 'integer)
1088 (eq (numeric-type-complexp x) :real)
1089 (eq (numeric-type-complexp y) :real))
1090 (multiple-value-bind (low high) (funcall fun x y)
1091 (make-numeric-type :class 'integer
1092 :complexp :real
1093 :low low
1094 :high high))
1095 (numeric-contagion x y)))
1097 (defun derive-integer-type (x y fun)
1098 (declare (type lvar x y) (type function fun))
1099 (let ((x (lvar-type x))
1100 (y (lvar-type y)))
1101 (derive-integer-type-aux x y fun)))
1103 ;;; simple utility to flatten a list
1104 (defun flatten-list (x)
1105 (labels ((flatten-and-append (tree list)
1106 (cond ((null tree) list)
1107 ((atom tree) (cons tree list))
1108 (t (flatten-and-append
1109 (car tree) (flatten-and-append (cdr tree) list))))))
1110 (flatten-and-append x nil)))
1112 ;;; Take some type of lvar and massage it so that we get a list of the
1113 ;;; constituent types. If ARG is *EMPTY-TYPE*, return NIL to indicate
1114 ;;; failure.
1115 (defun prepare-arg-for-derive-type (arg)
1116 (flet ((listify (arg)
1117 (typecase arg
1118 (numeric-type
1119 (list arg))
1120 (union-type
1121 (union-type-types arg))
1123 (list arg)))))
1124 (unless (eq arg *empty-type*)
1125 ;; Make sure all args are some type of numeric-type. For member
1126 ;; types, convert the list of members into a union of equivalent
1127 ;; single-element member-type's.
1128 (let ((new-args nil))
1129 (dolist (arg (listify arg))
1130 (if (member-type-p arg)
1131 ;; Run down the list of members and convert to a list of
1132 ;; member types.
1133 (mapc-member-type-members
1134 (lambda (member)
1135 (push (if (numberp member) (make-eql-type member) *empty-type*)
1136 new-args))
1137 arg)
1138 (push arg new-args)))
1139 (unless (member *empty-type* new-args)
1140 new-args)))))
1142 ;;; Take a list of types and return a canonical type specifier,
1143 ;;; combining any MEMBER types together. If both positive and negative
1144 ;;; MEMBER types are present they are converted to a float type.
1145 ;;; XXX This would be far simpler if the type-union methods could handle
1146 ;;; member/number unions.
1148 ;;; If we're about to generate an overly complex union of numeric types, start
1149 ;;; collapse the ranges together.
1151 ;;; FIXME: The MEMBER canonicalization parts of MAKE-DERIVED-UNION-TYPE and
1152 ;;; entire CONVERT-MEMBER-TYPE probably belong in the kernel's type logic,
1153 ;;; invoked always, instead of in the compiler, invoked only during some type
1154 ;;; optimizations.
1155 (defvar *derived-numeric-union-complexity-limit* 6)
1157 (defun make-derived-union-type (type-list)
1158 (let ((xset (alloc-xset))
1159 (fp-zeroes '())
1160 (misc-types '())
1161 (numeric-type *empty-type*))
1162 (dolist (type type-list)
1163 (cond ((member-type-p type)
1164 (mapc-member-type-members
1165 (lambda (member)
1166 (if (fp-zero-p member)
1167 (unless (member member fp-zeroes)
1168 (pushnew member fp-zeroes))
1169 (add-to-xset member xset)))
1170 type))
1171 ((numeric-type-p type)
1172 (let ((*approximate-numeric-unions*
1173 (when (and (union-type-p numeric-type)
1174 (nthcdr *derived-numeric-union-complexity-limit*
1175 (union-type-types numeric-type)))
1176 t)))
1177 (setf numeric-type (type-union type numeric-type))))
1179 (push type misc-types))))
1180 (if (and (xset-empty-p xset) (not fp-zeroes))
1181 (apply #'type-union numeric-type misc-types)
1182 (apply #'type-union (make-member-type xset fp-zeroes)
1183 numeric-type misc-types))))
1185 ;;; Convert a member type with a single member to a numeric type.
1186 (defun convert-member-type (arg)
1187 (let* ((members (member-type-members arg))
1188 (member (first members))
1189 (member-type (type-of member)))
1190 (aver (not (rest members)))
1191 (specifier-type (cond ((typep member 'integer)
1192 `(integer ,member ,member))
1193 ((memq member-type '(short-float single-float
1194 double-float long-float))
1195 `(,member-type ,member ,member))
1197 member-type)))))
1199 ;;; This is used in defoptimizers for computing the resulting type of
1200 ;;; a function.
1202 ;;; Given the lvar ARG, derive the resulting type using the
1203 ;;; DERIVE-FUN. DERIVE-FUN takes exactly one argument which is some
1204 ;;; "atomic" lvar type like numeric-type or member-type (containing
1205 ;;; just one element). It should return the resulting type, which can
1206 ;;; be a list of types.
1208 ;;; For the case of member types, if a MEMBER-FUN is given it is
1209 ;;; called to compute the result otherwise the member type is first
1210 ;;; converted to a numeric type and the DERIVE-FUN is called.
1211 (defun one-arg-derive-type (arg derive-fun member-fun)
1212 (declare (type function derive-fun)
1213 (type (or null function) member-fun))
1214 (let ((arg-list (prepare-arg-for-derive-type (lvar-type arg))))
1215 (when arg-list
1216 (flet ((deriver (x)
1217 (typecase x
1218 (member-type
1219 (if member-fun
1220 (with-float-traps-masked
1221 (:underflow :overflow :divide-by-zero)
1222 (specifier-type
1223 `(eql ,(funcall member-fun
1224 (first (member-type-members x))))))
1225 ;; Otherwise convert to a numeric type.
1226 (funcall derive-fun (convert-member-type x))))
1227 (numeric-type
1228 (funcall derive-fun x))
1230 *universal-type*))))
1231 ;; Run down the list of args and derive the type of each one,
1232 ;; saving all of the results in a list.
1233 (let ((results nil))
1234 (dolist (arg arg-list)
1235 (let ((result (deriver arg)))
1236 (if (listp result)
1237 (setf results (append results result))
1238 (push result results))))
1239 (if (rest results)
1240 (make-derived-union-type results)
1241 (first results)))))))
1243 ;;; Same as ONE-ARG-DERIVE-TYPE, except we assume the function takes
1244 ;;; two arguments. DERIVE-FUN takes 3 args in this case: the two
1245 ;;; original args and a third which is T to indicate if the two args
1246 ;;; really represent the same lvar. This is useful for deriving the
1247 ;;; type of things like (* x x), which should always be positive. If
1248 ;;; we didn't do this, we wouldn't be able to tell.
1249 (defun two-arg-derive-type (arg1 arg2 derive-fun fun)
1250 (declare (type function derive-fun fun))
1251 (flet ((deriver (x y same-arg)
1252 (cond ((and (member-type-p x) (member-type-p y))
1253 (let* ((x (first (member-type-members x)))
1254 (y (first (member-type-members y)))
1255 (result (ignore-errors
1256 (with-float-traps-masked
1257 (:underflow :overflow :divide-by-zero
1258 :invalid)
1259 (funcall fun x y)))))
1260 (cond ((null result) *empty-type*)
1261 ((and (floatp result) (float-nan-p result))
1262 (make-numeric-type :class 'float
1263 :format (type-of result)
1264 :complexp :real))
1266 (specifier-type `(eql ,result))))))
1267 ((and (member-type-p x) (numeric-type-p y))
1268 (funcall derive-fun (convert-member-type x) y same-arg))
1269 ((and (numeric-type-p x) (member-type-p y))
1270 (funcall derive-fun x (convert-member-type y) same-arg))
1271 ((and (numeric-type-p x) (numeric-type-p y))
1272 (funcall derive-fun x y same-arg))
1274 *universal-type*))))
1275 (let ((same-arg (same-leaf-ref-p arg1 arg2))
1276 (a1 (prepare-arg-for-derive-type (lvar-type arg1)))
1277 (a2 (prepare-arg-for-derive-type (lvar-type arg2))))
1278 (when (and a1 a2)
1279 (let ((results nil))
1280 (if same-arg
1281 ;; Since the args are the same LVARs, just run down the
1282 ;; lists.
1283 (dolist (x a1)
1284 (let ((result (deriver x x same-arg)))
1285 (if (listp result)
1286 (setf results (append results result))
1287 (push result results))))
1288 ;; Try all pairwise combinations.
1289 (dolist (x a1)
1290 (dolist (y a2)
1291 (let ((result (or (deriver x y same-arg)
1292 (numeric-contagion x y))))
1293 (if (listp result)
1294 (setf results (append results result))
1295 (push result results))))))
1296 (if (rest results)
1297 (make-derived-union-type results)
1298 (first results)))))))
1300 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1301 (progn
1302 (defoptimizer (+ derive-type) ((x y))
1303 (derive-integer-type
1305 #'(lambda (x y)
1306 (flet ((frob (x y)
1307 (if (and x y)
1308 (+ x y)
1309 nil)))
1310 (values (frob (numeric-type-low x) (numeric-type-low y))
1311 (frob (numeric-type-high x) (numeric-type-high y)))))))
1313 (defoptimizer (- derive-type) ((x y))
1314 (derive-integer-type
1316 #'(lambda (x y)
1317 (flet ((frob (x y)
1318 (if (and x y)
1319 (- x y)
1320 nil)))
1321 (values (frob (numeric-type-low x) (numeric-type-high y))
1322 (frob (numeric-type-high x) (numeric-type-low y)))))))
1324 (defoptimizer (* derive-type) ((x y))
1325 (derive-integer-type
1327 #'(lambda (x y)
1328 (let ((x-low (numeric-type-low x))
1329 (x-high (numeric-type-high x))
1330 (y-low (numeric-type-low y))
1331 (y-high (numeric-type-high y)))
1332 (cond ((not (and x-low y-low))
1333 (values nil nil))
1334 ((or (minusp x-low) (minusp y-low))
1335 (if (and x-high y-high)
1336 (let ((max (* (max (abs x-low) (abs x-high))
1337 (max (abs y-low) (abs y-high)))))
1338 (values (- max) max))
1339 (values nil nil)))
1341 (values (* x-low y-low)
1342 (if (and x-high y-high)
1343 (* x-high y-high)
1344 nil))))))))
1346 (defoptimizer (/ derive-type) ((x y))
1347 (numeric-contagion (lvar-type x) (lvar-type y)))
1349 ) ; PROGN
1351 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1352 (progn
1353 (defun +-derive-type-aux (x y same-arg)
1354 (if (and (numeric-type-real-p x)
1355 (numeric-type-real-p y))
1356 (let ((result
1357 (if same-arg
1358 (let ((x-int (numeric-type->interval x)))
1359 (interval-add x-int x-int))
1360 (interval-add (numeric-type->interval x)
1361 (numeric-type->interval y))))
1362 (result-type (numeric-contagion x y)))
1363 ;; If the result type is a float, we need to be sure to coerce
1364 ;; the bounds into the correct type.
1365 (when (eq (numeric-type-class result-type) 'float)
1366 (setf result (interval-func
1367 #'(lambda (x)
1368 (coerce-for-bound x (or (numeric-type-format result-type)
1369 'float)))
1370 result)))
1371 (make-numeric-type
1372 :class (if (and (eq (numeric-type-class x) 'integer)
1373 (eq (numeric-type-class y) 'integer))
1374 ;; The sum of integers is always an integer.
1375 'integer
1376 (numeric-type-class result-type))
1377 :format (numeric-type-format result-type)
1378 :low (interval-low result)
1379 :high (interval-high result)))
1380 ;; general contagion
1381 (numeric-contagion x y)))
1383 (defoptimizer (+ derive-type) ((x y))
1384 (two-arg-derive-type x y #'+-derive-type-aux #'+))
1386 (defun --derive-type-aux (x y same-arg)
1387 (if (and (numeric-type-real-p x)
1388 (numeric-type-real-p y))
1389 (let ((result
1390 ;; (- X X) is always 0.
1391 (if same-arg
1392 (make-interval :low 0 :high 0)
1393 (interval-sub (numeric-type->interval x)
1394 (numeric-type->interval y))))
1395 (result-type (numeric-contagion x y)))
1396 ;; If the result type is a float, we need to be sure to coerce
1397 ;; the bounds into the correct type.
1398 (when (eq (numeric-type-class result-type) 'float)
1399 (setf result (interval-func
1400 #'(lambda (x)
1401 (coerce-for-bound x (or (numeric-type-format result-type)
1402 'float)))
1403 result)))
1404 (make-numeric-type
1405 :class (if (and (eq (numeric-type-class x) 'integer)
1406 (eq (numeric-type-class y) 'integer))
1407 ;; The difference of integers is always an integer.
1408 'integer
1409 (numeric-type-class result-type))
1410 :format (numeric-type-format result-type)
1411 :low (interval-low result)
1412 :high (interval-high result)))
1413 ;; general contagion
1414 (numeric-contagion x y)))
1416 (defoptimizer (- derive-type) ((x y))
1417 (two-arg-derive-type x y #'--derive-type-aux #'-))
1419 (defun *-derive-type-aux (x y same-arg)
1420 (if (and (numeric-type-real-p x)
1421 (numeric-type-real-p y))
1422 (let ((result
1423 ;; (* X X) is always positive, so take care to do it right.
1424 (if same-arg
1425 (interval-sqr (numeric-type->interval x))
1426 (interval-mul (numeric-type->interval x)
1427 (numeric-type->interval y))))
1428 (result-type (numeric-contagion x y)))
1429 ;; If the result type is a float, we need to be sure to coerce
1430 ;; the bounds into the correct type.
1431 (when (eq (numeric-type-class result-type) 'float)
1432 (setf result (interval-func
1433 #'(lambda (x)
1434 (coerce-for-bound x (or (numeric-type-format result-type)
1435 'float)))
1436 result)))
1437 (make-numeric-type
1438 :class (if (and (eq (numeric-type-class x) 'integer)
1439 (eq (numeric-type-class y) 'integer))
1440 ;; The product of integers is always an integer.
1441 'integer
1442 (numeric-type-class result-type))
1443 :format (numeric-type-format result-type)
1444 :low (interval-low result)
1445 :high (interval-high result)))
1446 (numeric-contagion x y)))
1448 (defoptimizer (* derive-type) ((x y))
1449 (two-arg-derive-type x y #'*-derive-type-aux #'*))
1451 (defun /-derive-type-aux (x y same-arg)
1452 (if (and (numeric-type-real-p x)
1453 (numeric-type-real-p y))
1454 (let ((result
1455 ;; (/ X X) is always 1, except if X can contain 0. In
1456 ;; that case, we shouldn't optimize the division away
1457 ;; because we want 0/0 to signal an error.
1458 (if (and same-arg
1459 (not (interval-contains-p
1460 0 (interval-closure (numeric-type->interval y)))))
1461 (make-interval :low 1 :high 1)
1462 (interval-div (numeric-type->interval x)
1463 (numeric-type->interval y))))
1464 (result-type (numeric-contagion x y)))
1465 ;; If the result type is a float, we need to be sure to coerce
1466 ;; the bounds into the correct type.
1467 (when (eq (numeric-type-class result-type) 'float)
1468 (setf result (interval-func
1469 #'(lambda (x)
1470 (coerce-for-bound x (or (numeric-type-format result-type)
1471 'float)))
1472 result)))
1473 (make-numeric-type :class (numeric-type-class result-type)
1474 :format (numeric-type-format result-type)
1475 :low (interval-low result)
1476 :high (interval-high result)))
1477 (numeric-contagion x y)))
1479 (defoptimizer (/ derive-type) ((x y))
1480 (two-arg-derive-type x y #'/-derive-type-aux #'/))
1482 ) ; PROGN
1484 (defun ash-derive-type-aux (n-type shift same-arg)
1485 (declare (ignore same-arg))
1486 ;; KLUDGE: All this ASH optimization is suppressed under CMU CL for
1487 ;; some bignum cases because as of version 2.4.6 for Debian and 18d,
1488 ;; CMU CL blows up on (ASH 1000000000 -100000000000) (i.e. ASH of
1489 ;; two bignums yielding zero) and it's hard to avoid that
1490 ;; calculation in here.
1491 #+(and cmu sb-xc-host)
1492 (when (and (or (typep (numeric-type-low n-type) 'bignum)
1493 (typep (numeric-type-high n-type) 'bignum))
1494 (or (typep (numeric-type-low shift) 'bignum)
1495 (typep (numeric-type-high shift) 'bignum)))
1496 (return-from ash-derive-type-aux *universal-type*))
1497 (flet ((ash-outer (n s)
1498 (when (and (fixnump s)
1499 (<= s 64)
1500 (> s sb!xc:most-negative-fixnum))
1501 (ash n s)))
1502 ;; KLUDGE: The bare 64's here should be related to
1503 ;; symbolic machine word size values somehow.
1505 (ash-inner (n s)
1506 (if (and (fixnump s)
1507 (> s sb!xc:most-negative-fixnum))
1508 (ash n (min s 64))
1509 (if (minusp n) -1 0))))
1510 (or (and (csubtypep n-type (specifier-type 'integer))
1511 (csubtypep shift (specifier-type 'integer))
1512 (let ((n-low (numeric-type-low n-type))
1513 (n-high (numeric-type-high n-type))
1514 (s-low (numeric-type-low shift))
1515 (s-high (numeric-type-high shift)))
1516 (make-numeric-type :class 'integer :complexp :real
1517 :low (when n-low
1518 (if (minusp n-low)
1519 (ash-outer n-low s-high)
1520 (ash-inner n-low s-low)))
1521 :high (when n-high
1522 (if (minusp n-high)
1523 (ash-inner n-high s-low)
1524 (ash-outer n-high s-high))))))
1525 *universal-type*)))
1527 (defoptimizer (ash derive-type) ((n shift))
1528 (two-arg-derive-type n shift #'ash-derive-type-aux #'ash))
1530 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1531 (macrolet ((frob (fun)
1532 `#'(lambda (type type2)
1533 (declare (ignore type2))
1534 (let ((lo (numeric-type-low type))
1535 (hi (numeric-type-high type)))
1536 (values (if hi (,fun hi) nil) (if lo (,fun lo) nil))))))
1538 (defoptimizer (%negate derive-type) ((num))
1539 (derive-integer-type num num (frob -))))
1541 (defun lognot-derive-type-aux (int)
1542 (derive-integer-type-aux int int
1543 (lambda (type type2)
1544 (declare (ignore type2))
1545 (let ((lo (numeric-type-low type))
1546 (hi (numeric-type-high type)))
1547 (values (if hi (lognot hi) nil)
1548 (if lo (lognot lo) nil)
1549 (numeric-type-class type)
1550 (numeric-type-format type))))))
1552 (defoptimizer (lognot derive-type) ((int))
1553 (lognot-derive-type-aux (lvar-type int)))
1555 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1556 (defoptimizer (%negate derive-type) ((num))
1557 (flet ((negate-bound (b)
1558 (and b
1559 (set-bound (- (type-bound-number b))
1560 (consp b)))))
1561 (one-arg-derive-type num
1562 (lambda (type)
1563 (modified-numeric-type
1564 type
1565 :low (negate-bound (numeric-type-high type))
1566 :high (negate-bound (numeric-type-low type))))
1567 #'-)))
1569 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1570 (defoptimizer (abs derive-type) ((num))
1571 (let ((type (lvar-type num)))
1572 (if (and (numeric-type-p type)
1573 (eq (numeric-type-class type) 'integer)
1574 (eq (numeric-type-complexp type) :real))
1575 (let ((lo (numeric-type-low type))
1576 (hi (numeric-type-high type)))
1577 (make-numeric-type :class 'integer :complexp :real
1578 :low (cond ((and hi (minusp hi))
1579 (abs hi))
1581 (max 0 lo))
1584 :high (if (and hi lo)
1585 (max (abs hi) (abs lo))
1586 nil)))
1587 (numeric-contagion type type))))
1589 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1590 (defun abs-derive-type-aux (type)
1591 (cond ((eq (numeric-type-complexp type) :complex)
1592 ;; The absolute value of a complex number is always a
1593 ;; non-negative float.
1594 (let* ((format (case (numeric-type-class type)
1595 ((integer rational) 'single-float)
1596 (t (numeric-type-format type))))
1597 (bound-format (or format 'float)))
1598 (make-numeric-type :class 'float
1599 :format format
1600 :complexp :real
1601 :low (coerce 0 bound-format)
1602 :high nil)))
1604 ;; The absolute value of a real number is a non-negative real
1605 ;; of the same type.
1606 (let* ((abs-bnd (interval-abs (numeric-type->interval type)))
1607 (class (numeric-type-class type))
1608 (format (numeric-type-format type))
1609 (bound-type (or format class 'real)))
1610 (make-numeric-type
1611 :class class
1612 :format format
1613 :complexp :real
1614 :low (coerce-and-truncate-floats (interval-low abs-bnd) bound-type)
1615 :high (coerce-and-truncate-floats
1616 (interval-high abs-bnd) bound-type))))))
1618 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1619 (defoptimizer (abs derive-type) ((num))
1620 (one-arg-derive-type num #'abs-derive-type-aux #'abs))
1622 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1623 (defoptimizer (truncate derive-type) ((number divisor))
1624 (let ((number-type (lvar-type number))
1625 (divisor-type (lvar-type divisor))
1626 (integer-type (specifier-type 'integer)))
1627 (if (and (numeric-type-p number-type)
1628 (csubtypep number-type integer-type)
1629 (numeric-type-p divisor-type)
1630 (csubtypep divisor-type integer-type))
1631 (let ((number-low (numeric-type-low number-type))
1632 (number-high (numeric-type-high number-type))
1633 (divisor-low (numeric-type-low divisor-type))
1634 (divisor-high (numeric-type-high divisor-type)))
1635 (values-specifier-type
1636 `(values ,(integer-truncate-derive-type number-low number-high
1637 divisor-low divisor-high)
1638 ,(integer-rem-derive-type number-low number-high
1639 divisor-low divisor-high))))
1640 *universal-type*)))
1642 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
1643 (progn
1645 (defun rem-result-type (number-type divisor-type)
1646 ;; Figure out what the remainder type is. The remainder is an
1647 ;; integer if both args are integers; a rational if both args are
1648 ;; rational; and a float otherwise.
1649 (cond ((and (csubtypep number-type (specifier-type 'integer))
1650 (csubtypep divisor-type (specifier-type 'integer)))
1651 'integer)
1652 ((and (csubtypep number-type (specifier-type 'rational))
1653 (csubtypep divisor-type (specifier-type 'rational)))
1654 'rational)
1655 ((and (csubtypep number-type (specifier-type 'float))
1656 (csubtypep divisor-type (specifier-type 'float)))
1657 ;; Both are floats so the result is also a float, of
1658 ;; the largest type.
1659 (or (float-format-max (numeric-type-format number-type)
1660 (numeric-type-format divisor-type))
1661 'float))
1662 ((and (csubtypep number-type (specifier-type 'float))
1663 (csubtypep divisor-type (specifier-type 'rational)))
1664 ;; One of the arguments is a float and the other is a
1665 ;; rational. The remainder is a float of the same
1666 ;; type.
1667 (or (numeric-type-format number-type) 'float))
1668 ((and (csubtypep divisor-type (specifier-type 'float))
1669 (csubtypep number-type (specifier-type 'rational)))
1670 ;; One of the arguments is a float and the other is a
1671 ;; rational. The remainder is a float of the same
1672 ;; type.
1673 (or (numeric-type-format divisor-type) 'float))
1675 ;; Some unhandled combination. This usually means both args
1676 ;; are REAL so the result is a REAL.
1677 'real)))
1679 (defun truncate-derive-type-quot (number-type divisor-type)
1680 (let* ((rem-type (rem-result-type number-type divisor-type))
1681 (number-interval (numeric-type->interval number-type))
1682 (divisor-interval (numeric-type->interval divisor-type)))
1683 ;;(declare (type (member '(integer rational float)) rem-type))
1684 ;; We have real numbers now.
1685 (cond ((eq rem-type 'integer)
1686 ;; Since the remainder type is INTEGER, both args are
1687 ;; INTEGERs.
1688 (let* ((res (integer-truncate-derive-type
1689 (interval-low number-interval)
1690 (interval-high number-interval)
1691 (interval-low divisor-interval)
1692 (interval-high divisor-interval))))
1693 (specifier-type (if (listp res) res 'integer))))
1695 (let ((quot (truncate-quotient-bound
1696 (interval-div number-interval
1697 divisor-interval))))
1698 (specifier-type `(integer ,(or (interval-low quot) '*)
1699 ,(or (interval-high quot) '*))))))))
1701 (defun truncate-derive-type-rem (number-type divisor-type)
1702 (let* ((rem-type (rem-result-type number-type divisor-type))
1703 (number-interval (numeric-type->interval number-type))
1704 (divisor-interval (numeric-type->interval divisor-type))
1705 (rem (truncate-rem-bound number-interval divisor-interval)))
1706 ;;(declare (type (member '(integer rational float)) rem-type))
1707 ;; We have real numbers now.
1708 (cond ((eq rem-type 'integer)
1709 ;; Since the remainder type is INTEGER, both args are
1710 ;; INTEGERs.
1711 (specifier-type `(,rem-type ,(or (interval-low rem) '*)
1712 ,(or (interval-high rem) '*))))
1714 (multiple-value-bind (class format)
1715 (ecase rem-type
1716 (integer
1717 (values 'integer nil))
1718 (rational
1719 (values 'rational nil))
1720 ((or single-float double-float #!+long-float long-float)
1721 (values 'float rem-type))
1722 (float
1723 (values 'float nil))
1724 (real
1725 (values nil nil)))
1726 (when (member rem-type '(float single-float double-float
1727 #!+long-float long-float))
1728 (setf rem (interval-func #'(lambda (x)
1729 (coerce-for-bound x rem-type))
1730 rem)))
1731 (make-numeric-type :class class
1732 :format format
1733 :low (interval-low rem)
1734 :high (interval-high rem)))))))
1736 (defun truncate-derive-type-quot-aux (num div same-arg)
1737 (declare (ignore same-arg))
1738 (if (and (numeric-type-real-p num)
1739 (numeric-type-real-p div))
1740 (truncate-derive-type-quot num div)
1741 *empty-type*))
1743 (defun truncate-derive-type-rem-aux (num div same-arg)
1744 (declare (ignore same-arg))
1745 (if (and (numeric-type-real-p num)
1746 (numeric-type-real-p div))
1747 (truncate-derive-type-rem num div)
1748 *empty-type*))
1750 (defoptimizer (truncate derive-type) ((number divisor))
1751 (let ((quot (two-arg-derive-type number divisor
1752 #'truncate-derive-type-quot-aux #'truncate))
1753 (rem (two-arg-derive-type number divisor
1754 #'truncate-derive-type-rem-aux #'rem)))
1755 (when (and quot rem)
1756 (make-values-type :required (list quot rem)))))
1758 (defun ftruncate-derive-type-quot (number-type divisor-type)
1759 ;; The bounds are the same as for truncate. However, the first
1760 ;; result is a float of some type. We need to determine what that
1761 ;; type is. Basically it's the more contagious of the two types.
1762 (let ((q-type (truncate-derive-type-quot number-type divisor-type))
1763 (res-type (numeric-contagion number-type divisor-type)))
1764 (make-numeric-type :class 'float
1765 :format (numeric-type-format res-type)
1766 :low (numeric-type-low q-type)
1767 :high (numeric-type-high q-type))))
1769 (defun ftruncate-derive-type-quot-aux (n d same-arg)
1770 (declare (ignore same-arg))
1771 (if (and (numeric-type-real-p n)
1772 (numeric-type-real-p d))
1773 (ftruncate-derive-type-quot n d)
1774 *empty-type*))
1776 (defoptimizer (ftruncate derive-type) ((number divisor))
1777 (let ((quot
1778 (two-arg-derive-type number divisor
1779 #'ftruncate-derive-type-quot-aux #'ftruncate))
1780 (rem (two-arg-derive-type number divisor
1781 #'truncate-derive-type-rem-aux #'rem)))
1782 (when (and quot rem)
1783 (make-values-type :required (list quot rem)))))
1785 (defun %unary-truncate-derive-type-aux (number)
1786 (truncate-derive-type-quot number (specifier-type '(integer 1 1))))
1788 (defoptimizer (%unary-truncate derive-type) ((number))
1789 (one-arg-derive-type number
1790 #'%unary-truncate-derive-type-aux
1791 #'%unary-truncate))
1793 (defoptimizer (%unary-truncate/single-float derive-type) ((number))
1794 (one-arg-derive-type number
1795 #'%unary-truncate-derive-type-aux
1796 #'%unary-truncate))
1798 (defoptimizer (%unary-truncate/double-float derive-type) ((number))
1799 (one-arg-derive-type number
1800 #'%unary-truncate-derive-type-aux
1801 #'%unary-truncate))
1803 (defoptimizer (%unary-ftruncate derive-type) ((number))
1804 (let ((divisor (specifier-type '(integer 1 1))))
1805 (one-arg-derive-type number
1806 #'(lambda (n)
1807 (ftruncate-derive-type-quot-aux n divisor nil))
1808 #'%unary-ftruncate)))
1810 (defoptimizer (%unary-round derive-type) ((number))
1811 (one-arg-derive-type number
1812 (lambda (n)
1813 (block nil
1814 (unless (numeric-type-real-p n)
1815 (return *empty-type*))
1816 (let* ((interval (numeric-type->interval n))
1817 (low (interval-low interval))
1818 (high (interval-high interval)))
1819 (when (consp low)
1820 (setf low (car low)))
1821 (when (consp high)
1822 (setf high (car high)))
1823 (specifier-type
1824 `(integer ,(if low
1825 (round low)
1827 ,(if high
1828 (round high)
1829 '*))))))
1830 #'%unary-round))
1832 ;;; Define optimizers for FLOOR and CEILING.
1833 (macrolet
1834 ((def (name q-name r-name)
1835 (let ((q-aux (symbolicate q-name "-AUX"))
1836 (r-aux (symbolicate r-name "-AUX")))
1837 `(progn
1838 ;; Compute type of quotient (first) result.
1839 (defun ,q-aux (number-type divisor-type)
1840 (let* ((number-interval
1841 (numeric-type->interval number-type))
1842 (divisor-interval
1843 (numeric-type->interval divisor-type))
1844 (quot (,q-name (interval-div number-interval
1845 divisor-interval))))
1846 (specifier-type `(integer ,(or (interval-low quot) '*)
1847 ,(or (interval-high quot) '*)))))
1848 ;; Compute type of remainder.
1849 (defun ,r-aux (number-type divisor-type)
1850 (let* ((divisor-interval
1851 (numeric-type->interval divisor-type))
1852 (rem (,r-name divisor-interval))
1853 (result-type (rem-result-type number-type divisor-type)))
1854 (multiple-value-bind (class format)
1855 (ecase result-type
1856 (integer
1857 (values 'integer nil))
1858 (rational
1859 (values 'rational nil))
1860 ((or single-float double-float #!+long-float long-float)
1861 (values 'float result-type))
1862 (float
1863 (values 'float nil))
1864 (real
1865 (values nil nil)))
1866 (when (member result-type '(float single-float double-float
1867 #!+long-float long-float))
1868 ;; Make sure that the limits on the interval have
1869 ;; the right type.
1870 (setf rem (interval-func (lambda (x)
1871 (coerce-for-bound x result-type))
1872 rem)))
1873 (make-numeric-type :class class
1874 :format format
1875 :low (interval-low rem)
1876 :high (interval-high rem)))))
1877 ;; the optimizer itself
1878 (defoptimizer (,name derive-type) ((number divisor))
1879 (flet ((derive-q (n d same-arg)
1880 (declare (ignore same-arg))
1881 (if (and (numeric-type-real-p n)
1882 (numeric-type-real-p d))
1883 (,q-aux n d)
1884 *empty-type*))
1885 (derive-r (n d same-arg)
1886 (declare (ignore same-arg))
1887 (if (and (numeric-type-real-p n)
1888 (numeric-type-real-p d))
1889 (,r-aux n d)
1890 *empty-type*)))
1891 (let ((quot (two-arg-derive-type
1892 number divisor #'derive-q #',name))
1893 (rem (two-arg-derive-type
1894 number divisor #'derive-r #'mod)))
1895 (when (and quot rem)
1896 (make-values-type :required (list quot rem))))))))))
1898 (def floor floor-quotient-bound floor-rem-bound)
1899 (def ceiling ceiling-quotient-bound ceiling-rem-bound))
1901 ;;; Define optimizers for FFLOOR and FCEILING
1902 (macrolet ((def (name q-name r-name)
1903 (let ((q-aux (symbolicate "F" q-name "-AUX"))
1904 (r-aux (symbolicate r-name "-AUX")))
1905 `(progn
1906 ;; Compute type of quotient (first) result.
1907 (defun ,q-aux (number-type divisor-type)
1908 (let* ((number-interval
1909 (numeric-type->interval number-type))
1910 (divisor-interval
1911 (numeric-type->interval divisor-type))
1912 (quot (,q-name (interval-div number-interval
1913 divisor-interval)))
1914 (res-type (numeric-contagion number-type
1915 divisor-type)))
1916 (make-numeric-type
1917 :class (numeric-type-class res-type)
1918 :format (numeric-type-format res-type)
1919 :low (interval-low quot)
1920 :high (interval-high quot))))
1922 (defoptimizer (,name derive-type) ((number divisor))
1923 (flet ((derive-q (n d same-arg)
1924 (declare (ignore same-arg))
1925 (if (and (numeric-type-real-p n)
1926 (numeric-type-real-p d))
1927 (,q-aux n d)
1928 *empty-type*))
1929 (derive-r (n d same-arg)
1930 (declare (ignore same-arg))
1931 (if (and (numeric-type-real-p n)
1932 (numeric-type-real-p d))
1933 (,r-aux n d)
1934 *empty-type*)))
1935 (let ((quot (two-arg-derive-type
1936 number divisor #'derive-q #',name))
1937 (rem (two-arg-derive-type
1938 number divisor #'derive-r #'mod)))
1939 (when (and quot rem)
1940 (make-values-type :required (list quot rem))))))))))
1942 (def ffloor floor-quotient-bound floor-rem-bound)
1943 (def fceiling ceiling-quotient-bound ceiling-rem-bound))
1945 ;;; functions to compute the bounds on the quotient and remainder for
1946 ;;; the FLOOR function
1947 (defun floor-quotient-bound (quot)
1948 ;; Take the floor of the quotient and then massage it into what we
1949 ;; need.
1950 (let ((lo (interval-low quot))
1951 (hi (interval-high quot)))
1952 ;; Take the floor of the lower bound. The result is always a
1953 ;; closed lower bound.
1954 (setf lo (if lo
1955 (floor (type-bound-number lo))
1956 nil))
1957 ;; For the upper bound, we need to be careful.
1958 (setf hi
1959 (cond ((consp hi)
1960 ;; An open bound. We need to be careful here because
1961 ;; the floor of '(10.0) is 9, but the floor of
1962 ;; 10.0 is 10.
1963 (multiple-value-bind (q r) (floor (first hi))
1964 (if (zerop r)
1965 (1- q)
1966 q)))
1968 ;; A closed bound, so the answer is obvious.
1969 (floor hi))
1971 hi)))
1972 (make-interval :low lo :high hi)))
1973 (defun floor-rem-bound (div)
1974 ;; The remainder depends only on the divisor. Try to get the
1975 ;; correct sign for the remainder if we can.
1976 (case (interval-range-info div)
1978 ;; The divisor is always positive.
1979 (let ((rem (interval-abs div)))
1980 (setf (interval-low rem) 0)
1981 (when (and (numberp (interval-high rem))
1982 (not (zerop (interval-high rem))))
1983 ;; The remainder never contains the upper bound. However,
1984 ;; watch out for the case where the high limit is zero!
1985 (setf (interval-high rem) (list (interval-high rem))))
1986 rem))
1988 ;; The divisor is always negative.
1989 (let ((rem (interval-neg (interval-abs div))))
1990 (setf (interval-high rem) 0)
1991 (when (numberp (interval-low rem))
1992 ;; The remainder never contains the lower bound.
1993 (setf (interval-low rem) (list (interval-low rem))))
1994 rem))
1995 (otherwise
1996 ;; The divisor can be positive or negative. All bets off. The
1997 ;; magnitude of remainder is the maximum value of the divisor.
1998 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
1999 ;; The bound never reaches the limit, so make the interval open.
2000 (make-interval :low (if limit
2001 (list (- limit))
2002 limit)
2003 :high (list limit))))))
2004 #| Test cases
2005 (floor-quotient-bound (make-interval :low 0.3 :high 10.3))
2006 => #S(INTERVAL :LOW 0 :HIGH 10)
2007 (floor-quotient-bound (make-interval :low 0.3 :high '(10.3)))
2008 => #S(INTERVAL :LOW 0 :HIGH 10)
2009 (floor-quotient-bound (make-interval :low 0.3 :high 10))
2010 => #S(INTERVAL :LOW 0 :HIGH 10)
2011 (floor-quotient-bound (make-interval :low 0.3 :high '(10)))
2012 => #S(INTERVAL :LOW 0 :HIGH 9)
2013 (floor-quotient-bound (make-interval :low '(0.3) :high 10.3))
2014 => #S(INTERVAL :LOW 0 :HIGH 10)
2015 (floor-quotient-bound (make-interval :low '(0.0) :high 10.3))
2016 => #S(INTERVAL :LOW 0 :HIGH 10)
2017 (floor-quotient-bound (make-interval :low '(-1.3) :high 10.3))
2018 => #S(INTERVAL :LOW -2 :HIGH 10)
2019 (floor-quotient-bound (make-interval :low '(-1.0) :high 10.3))
2020 => #S(INTERVAL :LOW -1 :HIGH 10)
2021 (floor-quotient-bound (make-interval :low -1.0 :high 10.3))
2022 => #S(INTERVAL :LOW -1 :HIGH 10)
2024 (floor-rem-bound (make-interval :low 0.3 :high 10.3))
2025 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2026 (floor-rem-bound (make-interval :low 0.3 :high '(10.3)))
2027 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2028 (floor-rem-bound (make-interval :low -10 :high -2.3))
2029 #S(INTERVAL :LOW (-10) :HIGH 0)
2030 (floor-rem-bound (make-interval :low 0.3 :high 10))
2031 => #S(INTERVAL :LOW 0 :HIGH '(10))
2032 (floor-rem-bound (make-interval :low '(-1.3) :high 10.3))
2033 => #S(INTERVAL :LOW '(-10.3) :HIGH '(10.3))
2034 (floor-rem-bound (make-interval :low '(-20.3) :high 10.3))
2035 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
2038 ;;; same functions for CEILING
2039 (defun ceiling-quotient-bound (quot)
2040 ;; Take the ceiling of the quotient and then massage it into what we
2041 ;; need.
2042 (let ((lo (interval-low quot))
2043 (hi (interval-high quot)))
2044 ;; Take the ceiling of the upper bound. The result is always a
2045 ;; closed upper bound.
2046 (setf hi (if hi
2047 (ceiling (type-bound-number hi))
2048 nil))
2049 ;; For the lower bound, we need to be careful.
2050 (setf lo
2051 (cond ((consp lo)
2052 ;; An open bound. We need to be careful here because
2053 ;; the ceiling of '(10.0) is 11, but the ceiling of
2054 ;; 10.0 is 10.
2055 (multiple-value-bind (q r) (ceiling (first lo))
2056 (if (zerop r)
2057 (1+ q)
2058 q)))
2060 ;; A closed bound, so the answer is obvious.
2061 (ceiling lo))
2063 lo)))
2064 (make-interval :low lo :high hi)))
2065 (defun ceiling-rem-bound (div)
2066 ;; The remainder depends only on the divisor. Try to get the
2067 ;; correct sign for the remainder if we can.
2068 (case (interval-range-info div)
2070 ;; Divisor is always positive. The remainder is negative.
2071 (let ((rem (interval-neg (interval-abs div))))
2072 (setf (interval-high rem) 0)
2073 (when (and (numberp (interval-low rem))
2074 (not (zerop (interval-low rem))))
2075 ;; The remainder never contains the upper bound. However,
2076 ;; watch out for the case when the upper bound is zero!
2077 (setf (interval-low rem) (list (interval-low rem))))
2078 rem))
2080 ;; Divisor is always negative. The remainder is positive
2081 (let ((rem (interval-abs div)))
2082 (setf (interval-low rem) 0)
2083 (when (numberp (interval-high rem))
2084 ;; The remainder never contains the lower bound.
2085 (setf (interval-high rem) (list (interval-high rem))))
2086 rem))
2087 (otherwise
2088 ;; The divisor can be positive or negative. All bets off. The
2089 ;; magnitude of remainder is the maximum value of the divisor.
2090 (let ((limit (type-bound-number (interval-high (interval-abs div)))))
2091 ;; The bound never reaches the limit, so make the interval open.
2092 (make-interval :low (if limit
2093 (list (- limit))
2094 limit)
2095 :high (list limit))))))
2097 #| Test cases
2098 (ceiling-quotient-bound (make-interval :low 0.3 :high 10.3))
2099 => #S(INTERVAL :LOW 1 :HIGH 11)
2100 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10.3)))
2101 => #S(INTERVAL :LOW 1 :HIGH 11)
2102 (ceiling-quotient-bound (make-interval :low 0.3 :high 10))
2103 => #S(INTERVAL :LOW 1 :HIGH 10)
2104 (ceiling-quotient-bound (make-interval :low 0.3 :high '(10)))
2105 => #S(INTERVAL :LOW 1 :HIGH 10)
2106 (ceiling-quotient-bound (make-interval :low '(0.3) :high 10.3))
2107 => #S(INTERVAL :LOW 1 :HIGH 11)
2108 (ceiling-quotient-bound (make-interval :low '(0.0) :high 10.3))
2109 => #S(INTERVAL :LOW 1 :HIGH 11)
2110 (ceiling-quotient-bound (make-interval :low '(-1.3) :high 10.3))
2111 => #S(INTERVAL :LOW -1 :HIGH 11)
2112 (ceiling-quotient-bound (make-interval :low '(-1.0) :high 10.3))
2113 => #S(INTERVAL :LOW 0 :HIGH 11)
2114 (ceiling-quotient-bound (make-interval :low -1.0 :high 10.3))
2115 => #S(INTERVAL :LOW -1 :HIGH 11)
2117 (ceiling-rem-bound (make-interval :low 0.3 :high 10.3))
2118 => #S(INTERVAL :LOW (-10.3) :HIGH 0)
2119 (ceiling-rem-bound (make-interval :low 0.3 :high '(10.3)))
2120 => #S(INTERVAL :LOW 0 :HIGH '(10.3))
2121 (ceiling-rem-bound (make-interval :low -10 :high -2.3))
2122 => #S(INTERVAL :LOW 0 :HIGH (10))
2123 (ceiling-rem-bound (make-interval :low 0.3 :high 10))
2124 => #S(INTERVAL :LOW (-10) :HIGH 0)
2125 (ceiling-rem-bound (make-interval :low '(-1.3) :high 10.3))
2126 => #S(INTERVAL :LOW (-10.3) :HIGH (10.3))
2127 (ceiling-rem-bound (make-interval :low '(-20.3) :high 10.3))
2128 => #S(INTERVAL :LOW (-20.3) :HIGH (20.3))
2131 (defun truncate-quotient-bound (quot)
2132 ;; For positive quotients, truncate is exactly like floor. For
2133 ;; negative quotients, truncate is exactly like ceiling. Otherwise,
2134 ;; it's the union of the two pieces.
2135 (case (interval-range-info quot)
2137 ;; just like FLOOR
2138 (floor-quotient-bound quot))
2140 ;; just like CEILING
2141 (ceiling-quotient-bound quot))
2142 (otherwise
2143 ;; Split the interval into positive and negative pieces, compute
2144 ;; the result for each piece and put them back together.
2145 (destructuring-bind (neg pos) (interval-split 0 quot t t)
2146 (interval-merge-pair (ceiling-quotient-bound neg)
2147 (floor-quotient-bound pos))))))
2149 (defun truncate-rem-bound (num div)
2150 ;; This is significantly more complicated than FLOOR or CEILING. We
2151 ;; need both the number and the divisor to determine the range. The
2152 ;; basic idea is to split the ranges of NUM and DEN into positive
2153 ;; and negative pieces and deal with each of the four possibilities
2154 ;; in turn.
2155 (case (interval-range-info num)
2157 (case (interval-range-info div)
2159 (floor-rem-bound div))
2161 (ceiling-rem-bound div))
2162 (otherwise
2163 (destructuring-bind (neg pos) (interval-split 0 div t t)
2164 (interval-merge-pair (truncate-rem-bound num neg)
2165 (truncate-rem-bound num pos))))))
2167 (case (interval-range-info div)
2169 (ceiling-rem-bound div))
2171 (floor-rem-bound div))
2172 (otherwise
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))))))
2176 (otherwise
2177 (destructuring-bind (neg pos) (interval-split 0 num t t)
2178 (interval-merge-pair (truncate-rem-bound neg div)
2179 (truncate-rem-bound pos div))))))
2180 ) ; PROGN
2182 ;;; Derive useful information about the range. Returns three values:
2183 ;;; - '+ if its positive, '- negative, or nil if it overlaps 0.
2184 ;;; - The abs of the minimal value (i.e. closest to 0) in the range.
2185 ;;; - The abs of the maximal value if there is one, or nil if it is
2186 ;;; unbounded.
2187 (defun numeric-range-info (low high)
2188 (cond ((and low (not (minusp low)))
2189 (values '+ low high))
2190 ((and high (not (plusp high)))
2191 (values '- (- high) (if low (- low) nil)))
2193 (values nil 0 (and low high (max (- low) high))))))
2195 (defun integer-truncate-derive-type
2196 (number-low number-high divisor-low divisor-high)
2197 ;; The result cannot be larger in magnitude than the number, but the
2198 ;; sign might change. If we can determine the sign of either the
2199 ;; number or the divisor, we can eliminate some of the cases.
2200 (multiple-value-bind (number-sign number-min number-max)
2201 (numeric-range-info number-low number-high)
2202 (multiple-value-bind (divisor-sign divisor-min divisor-max)
2203 (numeric-range-info divisor-low divisor-high)
2204 (when (and divisor-max (zerop divisor-max))
2205 ;; We've got a problem: guaranteed division by zero.
2206 (return-from integer-truncate-derive-type t))
2207 (when (zerop divisor-min)
2208 ;; We'll assume that they aren't going to divide by zero.
2209 (incf divisor-min))
2210 (cond ((and number-sign divisor-sign)
2211 ;; We know the sign of both.
2212 (if (eq number-sign divisor-sign)
2213 ;; Same sign, so the result will be positive.
2214 `(integer ,(if divisor-max
2215 (truncate number-min divisor-max)
2217 ,(if number-max
2218 (truncate number-max divisor-min)
2219 '*))
2220 ;; Different signs, the result will be negative.
2221 `(integer ,(if number-max
2222 (- (truncate number-max divisor-min))
2224 ,(if divisor-max
2225 (- (truncate number-min divisor-max))
2226 0))))
2227 ((eq divisor-sign '+)
2228 ;; The divisor is positive. Therefore, the number will just
2229 ;; become closer to zero.
2230 `(integer ,(if number-low
2231 (truncate number-low divisor-min)
2233 ,(if number-high
2234 (truncate number-high divisor-min)
2235 '*)))
2236 ((eq divisor-sign '-)
2237 ;; The divisor is negative. Therefore, the absolute value of
2238 ;; the number will become closer to zero, but the sign will also
2239 ;; change.
2240 `(integer ,(if number-high
2241 (- (truncate number-high divisor-min))
2243 ,(if number-low
2244 (- (truncate number-low divisor-min))
2245 '*)))
2246 ;; The divisor could be either positive or negative.
2247 (number-max
2248 ;; The number we are dividing has a bound. Divide that by the
2249 ;; smallest posible divisor.
2250 (let ((bound (truncate number-max divisor-min)))
2251 `(integer ,(- bound) ,bound)))
2253 ;; The number we are dividing is unbounded, so we can't tell
2254 ;; anything about the result.
2255 `integer)))))
2257 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2258 (defun integer-rem-derive-type
2259 (number-low number-high divisor-low divisor-high)
2260 (if (and divisor-low divisor-high)
2261 ;; We know the range of the divisor, and the remainder must be
2262 ;; smaller than the divisor. We can tell the sign of the
2263 ;; remainder if we know the sign of the number.
2264 (let ((divisor-max (1- (max (abs divisor-low) (abs divisor-high)))))
2265 `(integer ,(if (or (null number-low)
2266 (minusp number-low))
2267 (- divisor-max)
2269 ,(if (or (null number-high)
2270 (plusp number-high))
2271 divisor-max
2272 0)))
2273 ;; The divisor is potentially either very positive or very
2274 ;; negative. Therefore, the remainder is unbounded, but we might
2275 ;; be able to tell something about the sign from the number.
2276 `(integer ,(if (and number-low (not (minusp number-low)))
2277 ;; The number we are dividing is positive.
2278 ;; Therefore, the remainder must be positive.
2281 ,(if (and number-high (not (plusp number-high)))
2282 ;; The number we are dividing is negative.
2283 ;; Therefore, the remainder must be negative.
2285 '*))))
2287 #+sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2288 (defoptimizer (random derive-type) ((bound &optional state))
2289 (declare (ignore state))
2290 (let ((type (lvar-type bound)))
2291 (when (numeric-type-p type)
2292 (let ((class (numeric-type-class type))
2293 (high (numeric-type-high type))
2294 (format (numeric-type-format type)))
2295 (make-numeric-type
2296 :class class
2297 :format format
2298 :low (coerce 0 (or format class 'real))
2299 :high (cond ((not high) nil)
2300 ((eq class 'integer) (max (1- high) 0))
2301 ((or (consp high) (zerop high)) high)
2302 (t `(,high))))))))
2304 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2305 (defun random-derive-type-aux (type)
2306 (let ((class (numeric-type-class type))
2307 (high (numeric-type-high type))
2308 (format (numeric-type-format type)))
2309 (make-numeric-type
2310 :class class
2311 :format format
2312 :low (coerce 0 (or format class 'real))
2313 :high (cond ((not high) nil)
2314 ((eq class 'integer) (max (1- high) 0))
2315 ((or (consp high) (zerop high)) high)
2316 (t `(,high))))))
2318 #-sb-xc-host ; (See CROSS-FLOAT-INFINITY-KLUDGE.)
2319 (defoptimizer (random derive-type) ((bound &optional state))
2320 (declare (ignore state))
2321 (one-arg-derive-type bound #'random-derive-type-aux nil))
2323 ;;;; miscellaneous derive-type methods
2325 (defoptimizer (integer-length derive-type) ((x))
2326 (let ((x-type (lvar-type x)))
2327 (when (numeric-type-p x-type)
2328 ;; If the X is of type (INTEGER LO HI), then the INTEGER-LENGTH
2329 ;; of X is (INTEGER (MIN lo hi) (MAX lo hi), basically. Be
2330 ;; careful about LO or HI being NIL, though. Also, if 0 is
2331 ;; contained in X, the lower bound is obviously 0.
2332 (flet ((null-or-min (a b)
2333 (and a b (min (integer-length a)
2334 (integer-length b))))
2335 (null-or-max (a b)
2336 (and a b (max (integer-length a)
2337 (integer-length b)))))
2338 (let* ((min (numeric-type-low x-type))
2339 (max (numeric-type-high x-type))
2340 (min-len (null-or-min min max))
2341 (max-len (null-or-max min max)))
2342 (when (ctypep 0 x-type)
2343 (setf min-len 0))
2344 (specifier-type `(integer ,(or min-len '*) ,(or max-len '*))))))))
2346 (defoptimizer (logcount derive-type) ((x))
2347 (let ((x-type (lvar-type x)))
2348 (when (numeric-type-p x-type)
2349 (let ((min (numeric-type-low x-type))
2350 (max (numeric-type-high x-type)))
2351 (when (and min max)
2352 (specifier-type
2353 `(integer ,(if (or (> min 0)
2354 (< max -1))
2357 ,(max (integer-length min)
2358 (integer-length max)))))))))
2360 (defoptimizer (isqrt derive-type) ((x))
2361 (let ((x-type (lvar-type x)))
2362 (when (numeric-type-p x-type)
2363 (let* ((lo (numeric-type-low x-type))
2364 (hi (numeric-type-high x-type))
2365 (lo-res (if (typep lo 'unsigned-byte)
2366 (isqrt lo)
2368 (hi-res (if (typep hi 'unsigned-byte)
2369 (isqrt hi)
2370 '*)))
2371 (specifier-type `(integer ,lo-res ,hi-res))))))
2373 (defoptimizer (char-code derive-type) ((char))
2374 (let ((type (type-intersection (lvar-type char) (specifier-type 'character))))
2375 (cond ((member-type-p type)
2376 (specifier-type
2377 `(member
2378 ,@(loop for member in (member-type-members type)
2379 when (characterp member)
2380 collect (char-code member)))))
2381 ((sb!kernel::character-set-type-p type)
2382 (specifier-type
2383 `(or
2384 ,@(loop for (low . high)
2385 in (character-set-type-pairs type)
2386 collect `(integer ,low ,high)))))
2387 ((csubtypep type (specifier-type 'base-char))
2388 (specifier-type
2389 `(mod ,base-char-code-limit)))
2391 (specifier-type
2392 `(mod ,sb!xc:char-code-limit))))))
2394 (defoptimizer (code-char derive-type) ((code))
2395 (let ((type (lvar-type code)))
2396 ;; FIXME: unions of integral ranges? It ought to be easier to do
2397 ;; this, given that CHARACTER-SET is basically an integral range
2398 ;; type. -- CSR, 2004-10-04
2399 (when (numeric-type-p type)
2400 (let* ((lo (numeric-type-low type))
2401 (hi (numeric-type-high type))
2402 (type (specifier-type `(character-set ((,lo . ,hi))))))
2403 (cond
2404 ;; KLUDGE: when running on the host, we lose a slight amount
2405 ;; of precision so that we don't have to "unparse" types
2406 ;; that formally we can't, such as (CHARACTER-SET ((0
2407 ;; . 0))). -- CSR, 2004-10-06
2408 #+sb-xc-host
2409 ((csubtypep type (specifier-type 'standard-char)) type)
2410 #+sb-xc-host
2411 ((csubtypep type (specifier-type 'base-char))
2412 (specifier-type 'base-char))
2413 #+sb-xc-host
2414 ((csubtypep type (specifier-type 'extended-char))
2415 (specifier-type 'extended-char))
2416 (t #+sb-xc-host (specifier-type 'character)
2417 #-sb-xc-host type))))))
2419 (defoptimizer (values derive-type) ((&rest values))
2420 (make-values-type :required (mapcar #'lvar-type values)))
2422 (defun signum-derive-type-aux (type)
2423 (if (eq (numeric-type-complexp type) :complex)
2424 (let* ((format (case (numeric-type-class type)
2425 ((integer rational) 'single-float)
2426 (t (numeric-type-format type))))
2427 (bound-format (or format 'float)))
2428 (make-numeric-type :class 'float
2429 :format format
2430 :complexp :complex
2431 :low (coerce -1 bound-format)
2432 :high (coerce 1 bound-format)))
2433 (let* ((interval (numeric-type->interval type))
2434 (range-info (interval-range-info interval))
2435 (contains-0-p (interval-contains-p 0 interval))
2436 (class (numeric-type-class type))
2437 (format (numeric-type-format type))
2438 (one (coerce 1 (or format class 'real)))
2439 (zero (coerce 0 (or format class 'real)))
2440 (minus-one (coerce -1 (or format class 'real)))
2441 (plus (make-numeric-type :class class :format format
2442 :low one :high one))
2443 (minus (make-numeric-type :class class :format format
2444 :low minus-one :high minus-one))
2445 ;; KLUDGE: here we have a fairly horrible hack to deal
2446 ;; with the schizophrenia in the type derivation engine.
2447 ;; The problem is that the type derivers reinterpret
2448 ;; numeric types as being exact; so (DOUBLE-FLOAT 0d0
2449 ;; 0d0) within the derivation mechanism doesn't include
2450 ;; -0d0. Ugh. So force it in here, instead.
2451 (zero (make-numeric-type :class class :format format
2452 :low (- zero) :high zero)))
2453 (case range-info
2454 (+ (if contains-0-p (type-union plus zero) plus))
2455 (- (if contains-0-p (type-union minus zero) minus))
2456 (t (type-union minus zero plus))))))
2458 (defoptimizer (signum derive-type) ((num))
2459 (one-arg-derive-type num #'signum-derive-type-aux nil))
2461 ;;;; byte operations
2462 ;;;;
2463 ;;;; We try to turn byte operations into simple logical operations.
2464 ;;;; First, we convert byte specifiers into separate size and position
2465 ;;;; arguments passed to internal %FOO functions. We then attempt to
2466 ;;;; transform the %FOO functions into boolean operations when the
2467 ;;;; size and position are constant and the operands are fixnums.
2468 ;;;; The goal of the source-transform is to avoid consing a byte specifier
2469 ;;;; to immediately throw away. A more powerful framework could recognize
2470 ;;;; in IR1 when a constructor call flows to one or more accessors for the
2471 ;;;; constructed object and nowhere else (no mutators). If so, forwarding
2472 ;;;; the constructor arguments to their reads would generally solve this.
2473 ;;;; A transform approximates that, but fails when BYTE is produced by an
2474 ;;;; inline function and not a macro.
2475 (flet ((xform (bytespec-form env int fun &optional (new nil setter-p))
2476 (let ((spec (%macroexpand bytespec-form env)))
2477 (if (and (consp spec) (eq (car spec) 'byte))
2478 (if (proper-list-of-length-p (cdr spec) 2)
2479 (values `(,fun ,@(if setter-p (list new))
2480 ,(second spec) ,(third spec) ,int) nil)
2481 ;; No point in compiling calls to BYTE-{SIZE,POSITION}
2482 (values nil t)) ; T => "pass" (meaning "fail")
2483 (let ((new-temp (if setter-p (copy-symbol 'new)))
2484 (byte (copy-symbol 'byte)))
2485 (values `(let (,@(if new-temp `((,new-temp ,new)))
2486 (,byte ,spec))
2487 (,fun ,@(if setter-p (list new-temp))
2488 (byte-size ,byte) (byte-position ,byte) ,int))
2489 nil))))))
2491 ;; DEFINE-SOURCE-TRANSFORM has no compile-time effect, so it's fine that
2492 ;; these 4 things are non-toplevel. (xform does not need to be a macro)
2493 (define-source-transform ldb (spec int &environment env)
2494 (xform spec env int '%ldb))
2496 (define-source-transform dpb (newbyte spec int &environment env)
2497 (xform spec env int '%dpb newbyte))
2499 (define-source-transform mask-field (spec int &environment env)
2500 (xform spec env int '%mask-field))
2502 (define-source-transform deposit-field (newbyte spec int &environment env)
2503 (xform spec env int '%deposit-field newbyte)))
2505 (defoptimizer (%ldb derive-type) ((size posn num))
2506 (declare (ignore posn num))
2507 (let ((size (lvar-type size)))
2508 (if (and (numeric-type-p size)
2509 (csubtypep size (specifier-type 'integer)))
2510 (let ((size-high (numeric-type-high size)))
2511 (if (and size-high (<= size-high sb!vm:n-word-bits))
2512 (specifier-type `(unsigned-byte* ,size-high))
2513 (specifier-type 'unsigned-byte)))
2514 *universal-type*)))
2516 (defoptimizer (%mask-field derive-type) ((size posn num))
2517 (declare (ignore num))
2518 (let ((size (lvar-type size))
2519 (posn (lvar-type posn)))
2520 (if (and (numeric-type-p size)
2521 (csubtypep size (specifier-type 'integer))
2522 (numeric-type-p posn)
2523 (csubtypep posn (specifier-type 'integer)))
2524 (let ((size-high (numeric-type-high size))
2525 (posn-high (numeric-type-high posn)))
2526 (if (and size-high posn-high
2527 (<= (+ size-high posn-high) sb!vm:n-word-bits))
2528 (specifier-type `(unsigned-byte* ,(+ size-high posn-high)))
2529 (specifier-type 'unsigned-byte)))
2530 *universal-type*)))
2532 (defun %deposit-field-derive-type-aux (size posn int)
2533 (let ((size (lvar-type size))
2534 (posn (lvar-type posn))
2535 (int (lvar-type int)))
2536 (when (and (numeric-type-p size)
2537 (numeric-type-p posn)
2538 (numeric-type-p int))
2539 (let ((size-high (numeric-type-high size))
2540 (posn-high (numeric-type-high posn))
2541 (high (numeric-type-high int))
2542 (low (numeric-type-low int)))
2543 (when (and size-high posn-high high low
2544 ;; KLUDGE: we need this cutoff here, otherwise we
2545 ;; will merrily derive the type of %DPB as
2546 ;; (UNSIGNED-BYTE 1073741822), and then attempt to
2547 ;; canonicalize this type to (INTEGER 0 (1- (ASH 1
2548 ;; 1073741822))), with hilarious consequences. We
2549 ;; cutoff at 4*SB!VM:N-WORD-BITS to allow inference
2550 ;; over a reasonable amount of shifting, even on
2551 ;; the alpha/32 port, where N-WORD-BITS is 32 but
2552 ;; machine integers are 64-bits. -- CSR,
2553 ;; 2003-09-12
2554 (<= (+ size-high posn-high) (* 4 sb!vm:n-word-bits)))
2555 (let ((raw-bit-count (max (integer-length high)
2556 (integer-length low)
2557 (+ size-high posn-high))))
2558 (specifier-type
2559 (if (minusp low)
2560 `(signed-byte ,(1+ raw-bit-count))
2561 `(unsigned-byte* ,raw-bit-count)))))))))
2563 (defoptimizer (%dpb derive-type) ((newbyte size posn int))
2564 (declare (ignore newbyte))
2565 (%deposit-field-derive-type-aux size posn int))
2567 (defoptimizer (%deposit-field derive-type) ((newbyte size posn int))
2568 (declare (ignore newbyte))
2569 (%deposit-field-derive-type-aux size posn int))
2571 (deftransform %ldb ((size posn int)
2572 (fixnum fixnum integer)
2573 (unsigned-byte #.sb!vm:n-word-bits))
2574 "convert to inline logical operations"
2575 (if (and (constant-lvar-p size)
2576 (constant-lvar-p posn)
2577 (<= (+ (lvar-value size) (lvar-value posn)) sb!vm:n-fixnum-bits))
2578 (let ((size (lvar-value size))
2579 (posn (lvar-value posn)))
2580 `(logand (ash (mask-signed-field sb!vm:n-fixnum-bits int) ,(- posn))
2581 ,(ash (1- (ash 1 sb!vm:n-word-bits))
2582 (- size sb!vm:n-word-bits))))
2583 `(logand (ash int (- posn))
2584 (ash ,(1- (ash 1 sb!vm:n-word-bits))
2585 (- size ,sb!vm:n-word-bits)))))
2587 (deftransform %mask-field ((size posn int)
2588 (fixnum fixnum integer)
2589 (unsigned-byte #.sb!vm:n-word-bits))
2590 "convert to inline logical operations"
2591 `(logand int
2592 (ash (ash ,(1- (ash 1 sb!vm:n-word-bits))
2593 (- size ,sb!vm:n-word-bits))
2594 posn)))
2596 ;;; Note: for %DPB and %DEPOSIT-FIELD, we can't use
2597 ;;; (OR (SIGNED-BYTE N) (UNSIGNED-BYTE N))
2598 ;;; as the result type, as that would allow result types that cover
2599 ;;; the range -2^(n-1) .. 1-2^n, instead of allowing result types of
2600 ;;; (UNSIGNED-BYTE N) and result types of (SIGNED-BYTE N).
2602 (deftransform %dpb ((new size posn int)
2604 (unsigned-byte #.sb!vm:n-word-bits))
2605 "convert to inline logical operations"
2606 `(let ((mask (ldb (byte size 0) -1)))
2607 (logior (ash (logand new mask) posn)
2608 (logand int (lognot (ash mask posn))))))
2610 (deftransform %dpb ((new size posn int)
2612 (signed-byte #.sb!vm:n-word-bits))
2613 "convert to inline logical operations"
2614 `(let ((mask (ldb (byte size 0) -1)))
2615 (logior (ash (logand new mask) posn)
2616 (logand int (lognot (ash mask posn))))))
2618 (deftransform %deposit-field ((new size posn int)
2620 (unsigned-byte #.sb!vm:n-word-bits))
2621 "convert to inline logical operations"
2622 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2623 (logior (logand new mask)
2624 (logand int (lognot mask)))))
2626 (deftransform %deposit-field ((new size posn int)
2628 (signed-byte #.sb!vm:n-word-bits))
2629 "convert to inline logical operations"
2630 `(let ((mask (ash (ldb (byte size 0) -1) posn)))
2631 (logior (logand new mask)
2632 (logand int (lognot mask)))))
2634 (defoptimizer (mask-signed-field derive-type) ((size x))
2635 (declare (ignore x))
2636 (let ((size (lvar-type size)))
2637 (if (numeric-type-p size)
2638 (let ((size-high (numeric-type-high size)))
2639 (if (and size-high (<= 1 size-high sb!vm:n-word-bits))
2640 (specifier-type `(signed-byte ,size-high))
2641 *universal-type*))
2642 *universal-type*)))
2644 ;;; Rightward ASH
2645 #!+ash-right-vops
2646 (progn
2647 (defun %ash/right (integer amount)
2648 (ash integer (- amount)))
2650 (deftransform ash ((integer amount))
2651 "Convert ASH of signed word to %ASH/RIGHT"
2652 (unless (and (csubtypep (lvar-type integer) ; do that ourselves to avoid
2653 (specifier-type 'sb!vm:signed-word)) ; optimization
2654 (csubtypep (lvar-type amount) ; notes.
2655 (specifier-type '(integer * 0))))
2656 (give-up-ir1-transform))
2657 (when (constant-lvar-p amount)
2658 (give-up-ir1-transform))
2659 (let ((use (lvar-uses amount)))
2660 (cond ((and (combination-p use)
2661 (eql '%negate (lvar-fun-name (combination-fun use))))
2662 (splice-fun-args amount '%negate 1)
2663 `(lambda (integer amount)
2664 (declare (type unsigned-byte amount))
2665 (%ash/right integer (if (>= amount ,sb!vm:n-word-bits)
2666 ,(1- sb!vm:n-word-bits)
2667 amount))))
2669 `(%ash/right integer (if (<= amount ,(- sb!vm:n-word-bits))
2670 ,(1- sb!vm:n-word-bits)
2671 (- amount)))))))
2673 (deftransform ash ((integer amount))
2674 "Convert ASH of word to %ASH/RIGHT"
2675 (unless (and (csubtypep (lvar-type integer)
2676 (specifier-type 'sb!vm:word))
2677 (csubtypep (lvar-type amount)
2678 (specifier-type '(integer * 0))))
2679 (give-up-ir1-transform))
2680 (when (constant-lvar-p amount)
2681 (give-up-ir1-transform))
2682 (let ((use (lvar-uses amount)))
2683 (cond ((and (combination-p use)
2684 (eql '%negate (lvar-fun-name (combination-fun use))))
2685 (splice-fun-args amount '%negate 1)
2686 `(lambda (integer amount)
2687 (declare (type unsigned-byte amount))
2688 (if (>= amount ,sb!vm:n-word-bits)
2690 (%ash/right integer amount))))
2692 `(if (<= amount ,(- sb!vm:n-word-bits))
2694 (%ash/right integer (- amount)))))))
2696 (deftransform %ash/right ((integer amount) (integer (constant-arg unsigned-byte)))
2697 "Convert %ASH/RIGHT by constant back to ASH"
2698 `(ash integer ,(- (lvar-value amount))))
2700 (deftransform %ash/right ((integer amount) * * :node node)
2701 "strength reduce large variable right shift"
2702 (let ((return-type (single-value-type (node-derived-type node))))
2703 (cond ((type= return-type (specifier-type '(eql 0)))
2705 ((type= return-type (specifier-type '(eql -1)))
2707 ((csubtypep return-type (specifier-type '(member -1 0)))
2708 `(ash integer ,(- sb!vm:n-word-bits)))
2710 (give-up-ir1-transform)))))
2712 (defun %ash/right-derive-type-aux (n-type shift same-arg)
2713 (declare (ignore same-arg))
2714 (or (and (or (csubtypep n-type (specifier-type 'sb!vm:signed-word))
2715 (csubtypep n-type (specifier-type 'word)))
2716 (csubtypep shift (specifier-type `(mod ,sb!vm:n-word-bits)))
2717 (let ((n-low (numeric-type-low n-type))
2718 (n-high (numeric-type-high n-type))
2719 (s-low (numeric-type-low shift))
2720 (s-high (numeric-type-high shift)))
2721 (make-numeric-type :class 'integer :complexp :real
2722 :low (when n-low
2723 (if (minusp n-low)
2724 (ash n-low (- s-low))
2725 (ash n-low (- s-high))))
2726 :high (when n-high
2727 (if (minusp n-high)
2728 (ash n-high (- s-high))
2729 (ash n-high (- s-low)))))))
2730 *universal-type*))
2732 (defoptimizer (%ash/right derive-type) ((n shift))
2733 (two-arg-derive-type n shift #'%ash/right-derive-type-aux #'%ash/right))
2736 ;;; Not declaring it as actually being RATIO becuase it is used as one
2737 ;;; of the legs in the EXPT transform below and that may result in
2738 ;;; some unwanted type conflicts, e.g. (random (expt 2 (the integer y)))
2739 (declaim (type (sfunction (integer) rational) reciprocate))
2740 (defun reciprocate (x)
2741 (declare (optimize (safety 0)))
2742 #+sb-xc-host (error "Can't call reciprocate ~D" x)
2743 #-sb-xc-host (%make-ratio 1 x))
2745 (deftransform expt ((base power) ((constant-arg unsigned-byte) integer))
2746 (let ((base (lvar-value base)))
2747 (cond ((/= (logcount base) 1)
2748 (give-up-ir1-transform))
2749 ((= base 1)
2752 `(let ((%denominator (ash 1 ,(if (= base 2)
2753 `(abs power)
2754 `(* (abs power) ,(1- (integer-length base)))))))
2755 (if (minusp power)
2756 (reciprocate %denominator)
2757 %denominator))))))
2759 (deftransform expt ((base power) ((constant-arg unsigned-byte) unsigned-byte))
2760 (let ((base (lvar-value base)))
2761 (unless (= (logcount base) 1)
2762 (give-up-ir1-transform))
2763 `(ash 1 ,(if (= base 2)
2764 `power
2765 `(* power ,(1- (integer-length base)))))))
2767 ;;; Modular functions
2769 ;;; (ldb (byte s 0) (foo x y ...)) =
2770 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2772 ;;; and similar for other arguments.
2774 (defun make-modular-fun-type-deriver (prototype kind width signedp)
2775 (declare (ignore kind))
2776 #!-sb-fluid
2777 (binding* ((info (info :function :info prototype) :exit-if-null)
2778 (fun (fun-info-derive-type info) :exit-if-null)
2779 (mask-type (specifier-type
2780 (ecase signedp
2781 ((nil) (let ((mask (1- (ash 1 width))))
2782 `(integer ,mask ,mask)))
2783 ((t) `(signed-byte ,width))))))
2784 (lambda (call)
2785 (let ((res (funcall fun call)))
2786 (when res
2787 (if (eq signedp nil)
2788 (logand-derive-type-aux res mask-type))))))
2789 #!+sb-fluid
2790 (lambda (call)
2791 (binding* ((info (info :function :info prototype) :exit-if-null)
2792 (fun (fun-info-derive-type info) :exit-if-null)
2793 (res (funcall fun call) :exit-if-null)
2794 (mask-type (specifier-type
2795 (ecase signedp
2796 ((nil) (let ((mask (1- (ash 1 width))))
2797 `(integer ,mask ,mask)))
2798 ((t) `(signed-byte ,width))))))
2799 (if (eq signedp nil)
2800 (logand-derive-type-aux res mask-type)))))
2802 ;;; Try to recursively cut all uses of LVAR to WIDTH bits.
2804 ;;; For good functions, we just recursively cut arguments; their
2805 ;;; "goodness" means that the result will not increase (in the
2806 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
2807 ;;; replaced with the version, cutting its result to WIDTH or more
2808 ;;; bits. For most functions (e.g. for +) we cut all arguments; for
2809 ;;; others (e.g. for ASH) we have "optimizers", cutting only necessary
2810 ;;; arguments (maybe to a different width) and returning the name of a
2811 ;;; modular version, if it exists, or NIL. If we have changed
2812 ;;; anything, we need to flush old derived types, because they have
2813 ;;; nothing in common with the new code.
2814 (defun cut-to-width (lvar kind width signedp)
2815 (declare (type lvar lvar) (type (integer 0) width))
2816 (let ((type (specifier-type (if (zerop width)
2817 '(eql 0)
2818 `(,(ecase signedp
2819 ((nil) 'unsigned-byte)
2820 ((t) 'signed-byte))
2821 ,width)))))
2822 (labels ((reoptimize-node (node name)
2823 (setf (node-derived-type node)
2824 (fun-type-returns
2825 (proclaimed-ftype name)))
2826 (setf (lvar-%derived-type (node-lvar node)) nil)
2827 (setf (node-reoptimize node) t)
2828 (setf (block-reoptimize (node-block node)) t)
2829 (reoptimize-component (node-component node) :maybe))
2830 (insert-lvar-cut (lvar)
2831 "Insert a LOGAND/MASK-SIGNED-FIELD to cut the value of LVAR
2832 to the required bit width. Returns T if any change was made.
2834 When the destination of LVAR will definitely cut LVAR's value
2835 to width (i.e. it's a logand or mask-signed-field with constant
2836 other argument), do nothing. Otherwise, splice LOGAND/M-S-F in."
2837 (binding* ((dest (lvar-dest lvar) :exit-if-null)
2838 (nil (combination-p dest) :exit-if-null)
2839 (name (lvar-fun-name (combination-fun dest) t))
2840 (args (combination-args dest)))
2841 (case name
2842 (logand
2843 (when (= 2 (length args))
2844 (let ((other (if (eql (first args) lvar)
2845 (second args)
2846 (first args))))
2847 (when (and (constant-lvar-p other)
2848 (ctypep (lvar-value other) type)
2849 (not signedp))
2850 (return-from insert-lvar-cut)))))
2851 (mask-signed-field
2852 (when (and signedp
2853 (eql lvar (second args))
2854 (constant-lvar-p (first args))
2855 (<= (lvar-value (first args)) width))
2856 (return-from insert-lvar-cut)))))
2857 (filter-lvar lvar
2858 (if signedp
2859 `(mask-signed-field ,width 'dummy)
2860 `(logand 'dummy ,(ldb (byte width 0) -1))))
2861 (do-uses (node lvar)
2862 (setf (block-reoptimize (node-block node)) t)
2863 (reoptimize-component (node-component node) :maybe))
2865 (cut-node (node)
2866 "Try to cut a node to width. The primary return value is
2867 whether we managed to cut (cleverly), and the second whether
2868 anything was changed. The third return value tells whether
2869 the cut value might be wider than expected."
2870 (when (block-delete-p (node-block node))
2871 (return-from cut-node (values t nil)))
2872 (typecase node
2873 (ref
2874 (typecase (ref-leaf node)
2875 (constant
2876 (let* ((constant-value (constant-value (ref-leaf node)))
2877 (new-value
2878 (cond ((not (integerp constant-value))
2879 (return-from cut-node (values t nil)))
2880 (signedp
2881 (mask-signed-field width constant-value))
2883 (ldb (byte width 0) constant-value)))))
2884 (cond ((= constant-value new-value)
2885 (values t nil)) ; we knew what to do and did nothing
2887 (change-ref-leaf node (make-constant new-value)
2888 :recklessly t)
2889 (let ((lvar (node-lvar node)))
2890 (setf (lvar-%derived-type lvar)
2891 (and (lvar-has-single-use-p lvar)
2892 (make-values-type :required (list (ctype-of new-value))))))
2893 (setf (block-reoptimize (node-block node)) t)
2894 (reoptimize-component (node-component node) :maybe)
2895 (values t t)))))))
2896 (combination
2897 (when (eq (basic-combination-kind node) :known)
2898 (let* ((fun-ref (lvar-use (combination-fun node)))
2899 (fun-name (lvar-fun-name (combination-fun node)))
2900 (modular-fun (find-modular-version fun-name kind
2901 signedp width)))
2902 (cond ((not modular-fun)
2903 ;; don't know what to do here
2904 (values nil nil))
2905 ((let ((dtype (single-value-type
2906 (node-derived-type node))))
2907 (and
2908 (case fun-name
2909 (logand
2910 (csubtypep dtype
2911 (specifier-type 'unsigned-byte)))
2912 (logior
2913 (csubtypep dtype
2914 (specifier-type '(integer * 0))))
2915 (mask-signed-field
2917 (t nil))
2918 (csubtypep dtype type)))
2919 ;; nothing to do
2920 (values t nil))
2922 (binding* ((name (etypecase modular-fun
2923 ((eql :good) fun-name)
2924 (modular-fun-info
2925 (modular-fun-info-name modular-fun))
2926 (function
2927 (funcall modular-fun node width)))
2928 :exit-if-null)
2929 (did-something nil)
2930 (over-wide nil))
2931 (unless (eql modular-fun :good)
2932 (setq did-something t
2933 over-wide t)
2934 (change-ref-leaf
2935 fun-ref
2936 (find-free-fun name "in a strange place"))
2937 (setf (combination-kind node) :full))
2938 (unless (functionp modular-fun)
2939 (dolist (arg (basic-combination-args node))
2940 (multiple-value-bind (change wide)
2941 (cut-lvar arg)
2942 (setf did-something (or did-something change)
2943 over-wide (or over-wide wide)))))
2944 (when did-something
2945 (reoptimize-node node name))
2946 (values t did-something over-wide)))))))))
2947 (cut-lvar (lvar &key head
2948 &aux did-something must-insert over-wide)
2949 "Cut all the LVAR's use nodes. If any of them wasn't handled
2950 and its type is too wide for the operation we wish to perform
2951 insert an explicit bit-width narrowing operation (LOGAND or
2952 MASK-SIGNED-FIELD) between the LVAR (*) and its destination.
2953 The narrowing operation might not be inserted if the LVAR's
2954 destination is already such an operation, to avoid endless
2955 recursion.
2957 If we're at the head, forcibly insert a cut operation if the
2958 result might be too wide.
2960 (*) We can't easily do that for each node, and doing so might
2961 result in code bloat, anyway. (I'm also not sure it would be
2962 correct for complicated C/D FG)"
2963 (do-uses (node lvar)
2964 (multiple-value-bind (handled any-change wide)
2965 (cut-node node)
2966 (setf did-something (or did-something any-change)
2967 must-insert (or must-insert
2968 (not (or handled
2969 (csubtypep (single-value-type
2970 (node-derived-type node))
2971 type))))
2972 over-wide (or over-wide wide))))
2973 (when (or must-insert
2974 (and head over-wide))
2975 (setf did-something (or (insert-lvar-cut lvar) did-something)
2976 ;; we're just the right width after an explicit cut.
2977 over-wide nil))
2978 (values did-something over-wide)))
2979 (cut-lvar lvar :head t))))
2981 (defun best-modular-version (width signedp)
2982 ;; 1. exact width-matched :untagged
2983 ;; 2. >/>= width-matched :tagged
2984 ;; 3. >/>= width-matched :untagged
2985 (let* ((uuwidths (modular-class-widths *untagged-unsigned-modular-class*))
2986 (uswidths (modular-class-widths *untagged-signed-modular-class*))
2987 (uwidths (if (and uuwidths uswidths)
2988 (merge 'list (copy-list uuwidths) (copy-list uswidths)
2989 #'< :key #'car)
2990 (or uuwidths uswidths)))
2991 (twidths (modular-class-widths *tagged-modular-class*)))
2992 (let ((exact (find (cons width signedp) uwidths :test #'equal)))
2993 (when exact
2994 (return-from best-modular-version (values width :untagged signedp))))
2995 (flet ((inexact-match (w)
2996 (cond
2997 ((eq signedp (cdr w)) (<= width (car w)))
2998 ((eq signedp nil) (< width (car w))))))
2999 (let ((tgt (find-if #'inexact-match twidths)))
3000 (when tgt
3001 (return-from best-modular-version
3002 (values (car tgt) :tagged (cdr tgt)))))
3003 (let ((ugt (find-if #'inexact-match uwidths)))
3004 (when ugt
3005 (return-from best-modular-version
3006 (values (car ugt) :untagged (cdr ugt))))))))
3008 (defun integer-type-numeric-bounds (type)
3009 (typecase type
3010 ;; KLUDGE: this is not INTEGER-type-numeric-bounds
3011 (numeric-type (values (numeric-type-low type)
3012 (numeric-type-high type)))
3013 (union-type
3014 (let ((low nil)
3015 (high nil))
3016 (dolist (type (union-type-types type) (values low high))
3017 (unless (and (numeric-type-p type)
3018 (eql (numeric-type-class type) 'integer))
3019 (return (values nil nil)))
3020 (let ((this-low (numeric-type-low type))
3021 (this-high (numeric-type-high type)))
3022 (unless (and this-low this-high)
3023 (return (values nil nil)))
3024 (setf low (min this-low (or low this-low))
3025 high (max this-high (or high this-high)))))))))
3027 (defoptimizer (logand optimizer) ((x y) node)
3028 (let ((result-type (single-value-type (node-derived-type node))))
3029 (multiple-value-bind (low high)
3030 (integer-type-numeric-bounds result-type)
3031 (when (and (numberp low)
3032 (numberp high)
3033 (>= low 0))
3034 (let ((width (integer-length high)))
3035 (multiple-value-bind (w kind signedp)
3036 (best-modular-version width nil)
3037 (when w
3038 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND WIDTH SIGNEDP).
3040 ;; FIXME: I think the FIXME (which is from APD) above
3041 ;; implies that CUT-TO-WIDTH should do /everything/
3042 ;; that's required, including reoptimizing things
3043 ;; itself that it knows are necessary. At the moment,
3044 ;; CUT-TO-WIDTH sets up some new calls with
3045 ;; combination-type :FULL, which later get noticed as
3046 ;; known functions and properly converted.
3048 ;; We cut to W not WIDTH if SIGNEDP is true, because
3049 ;; signed constant replacement needs to know which bit
3050 ;; in the field is the signed bit.
3051 (let ((xact (cut-to-width x kind (if signedp w width) signedp))
3052 (yact (cut-to-width y kind (if signedp w width) signedp)))
3053 (declare (ignore xact yact))
3054 nil) ; After fixing above, replace with T, meaning
3055 ; "don't reoptimize this (LOGAND) node any more".
3056 )))))))
3058 (defoptimizer (mask-signed-field optimizer) ((width x) node)
3059 (declare (ignore width))
3060 (let ((result-type (single-value-type (node-derived-type node))))
3061 (multiple-value-bind (low high)
3062 (integer-type-numeric-bounds result-type)
3063 (when (and (numberp low) (numberp high))
3064 (let ((width (max (integer-length high) (integer-length low))))
3065 (multiple-value-bind (w kind)
3066 (best-modular-version (1+ width) t)
3067 (when w
3068 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND W T).
3069 ;; [ see comment above in LOGAND optimizer ]
3070 (cut-to-width x kind w t)
3071 nil ; After fixing above, replace with T.
3072 )))))))
3074 (defoptimizer (logior optimizer) ((x y) node)
3075 (let ((result-type (single-value-type (node-derived-type node))))
3076 (multiple-value-bind (low high)
3077 (integer-type-numeric-bounds result-type)
3078 (when (and (numberp low)
3079 (numberp high)
3080 (<= high 0))
3081 (let ((width (integer-length low)))
3082 (multiple-value-bind (w kind)
3083 (best-modular-version (1+ width) t)
3084 (when w
3085 ;; FIXME: see comment in LOGAND optimizer
3086 (let ((xact (cut-to-width x kind w t))
3087 (yact (cut-to-width y kind w t)))
3088 (declare (ignore xact yact))
3089 nil) ; After fixing above, replace with T
3090 )))))))
3092 ;;; Handle the case of a constant BOOLE-CODE.
3093 (deftransform boole ((op x y) * *)
3094 "convert to inline logical operations"
3095 (unless (constant-lvar-p op)
3096 (give-up-ir1-transform "BOOLE code is not a constant."))
3097 (let ((control (lvar-value op)))
3098 (case control
3099 (#.sb!xc:boole-clr 0)
3100 (#.sb!xc:boole-set -1)
3101 (#.sb!xc:boole-1 'x)
3102 (#.sb!xc:boole-2 'y)
3103 (#.sb!xc:boole-c1 '(lognot x))
3104 (#.sb!xc:boole-c2 '(lognot y))
3105 (#.sb!xc:boole-and '(logand x y))
3106 (#.sb!xc:boole-ior '(logior x y))
3107 (#.sb!xc:boole-xor '(logxor x y))
3108 (#.sb!xc:boole-eqv '(logeqv x y))
3109 (#.sb!xc:boole-nand '(lognand x y))
3110 (#.sb!xc:boole-nor '(lognor x y))
3111 (#.sb!xc:boole-andc1 '(logandc1 x y))
3112 (#.sb!xc:boole-andc2 '(logandc2 x y))
3113 (#.sb!xc:boole-orc1 '(logorc1 x y))
3114 (#.sb!xc:boole-orc2 '(logorc2 x y))
3116 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
3117 control)))))
3119 ;;;; converting special case multiply/divide to shifts
3121 ;;; If arg is a constant power of two, turn * into a shift.
3122 (deftransform * ((x y) (integer integer) *)
3123 "convert x*2^k to shift"
3124 (unless (constant-lvar-p y)
3125 (give-up-ir1-transform))
3126 (let* ((y (lvar-value y))
3127 (y-abs (abs y))
3128 (len (1- (integer-length y-abs))))
3129 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3130 (give-up-ir1-transform))
3131 (if (minusp y)
3132 `(- (ash x ,len))
3133 `(ash x ,len))))
3135 ;;; These must come before the ones below, so that they are tried
3136 ;;; first.
3137 (deftransform floor ((number divisor))
3138 `(multiple-value-bind (tru rem) (truncate number divisor)
3139 (if (and (not (zerop rem))
3140 (if (minusp divisor)
3141 (plusp number)
3142 (minusp number)))
3143 (values (1- tru) (+ rem divisor))
3144 (values tru rem))))
3146 (deftransform ceiling ((number divisor))
3147 `(multiple-value-bind (tru rem) (truncate number divisor)
3148 (if (and (not (zerop rem))
3149 (if (minusp divisor)
3150 (minusp number)
3151 (plusp number)))
3152 (values (+ tru 1) (- rem divisor))
3153 (values tru rem))))
3155 (deftransform rem ((number divisor))
3156 `(nth-value 1 (truncate number divisor)))
3158 (deftransform mod ((number divisor))
3159 `(let ((rem (rem number divisor)))
3160 (if (and (not (zerop rem))
3161 (if (minusp divisor)
3162 (plusp number)
3163 (minusp number)))
3164 (+ rem divisor)
3165 rem)))
3167 ;;; If arg is a constant power of two, turn FLOOR into a shift and
3168 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
3169 ;;; remainder.
3170 (flet ((frob (y ceil-p)
3171 (unless (constant-lvar-p y)
3172 (give-up-ir1-transform))
3173 (let* ((y (lvar-value y))
3174 (y-abs (abs y))
3175 (len (1- (integer-length y-abs))))
3176 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3177 (give-up-ir1-transform))
3178 (let ((shift (- len))
3179 (mask (1- y-abs))
3180 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
3181 `(let ((x (+ x ,delta)))
3182 ,(if (minusp y)
3183 `(values (ash (- x) ,shift)
3184 (- (- (logand (- x) ,mask)) ,delta))
3185 `(values (ash x ,shift)
3186 (- (logand x ,mask) ,delta))))))))
3187 (deftransform floor ((x y) (integer integer) *)
3188 "convert division by 2^k to shift"
3189 (frob y nil))
3190 (deftransform ceiling ((x y) (integer integer) *)
3191 "convert division by 2^k to shift"
3192 (frob y t)))
3194 ;;; Do the same for MOD.
3195 (deftransform mod ((x y) (integer integer) *)
3196 "convert remainder mod 2^k to LOGAND"
3197 (unless (constant-lvar-p y)
3198 (give-up-ir1-transform))
3199 (let* ((y (lvar-value y))
3200 (y-abs (abs y))
3201 (len (1- (integer-length y-abs))))
3202 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3203 (give-up-ir1-transform))
3204 (let ((mask (1- y-abs)))
3205 (if (minusp y)
3206 `(- (logand (- x) ,mask))
3207 `(logand x ,mask)))))
3209 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
3210 (deftransform truncate ((x y) (integer integer))
3211 "convert division by 2^k to shift"
3212 (unless (constant-lvar-p y)
3213 (give-up-ir1-transform))
3214 (let* ((y (lvar-value y))
3215 (y-abs (abs y))
3216 (len (1- (integer-length y-abs))))
3217 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3218 (give-up-ir1-transform))
3219 (let* ((shift (- len))
3220 (mask (1- y-abs)))
3221 `(if (minusp x)
3222 (values ,(if (minusp y)
3223 `(ash (- x) ,shift)
3224 `(- (ash (- x) ,shift)))
3225 (- (logand (- x) ,mask)))
3226 (values ,(if (minusp y)
3227 `(ash (- ,mask x) ,shift)
3228 `(ash x ,shift))
3229 (logand x ,mask))))))
3231 ;;; And the same for REM.
3232 (deftransform rem ((x y) (integer integer) *)
3233 "convert remainder mod 2^k to LOGAND"
3234 (unless (constant-lvar-p y)
3235 (give-up-ir1-transform))
3236 (let* ((y (lvar-value y))
3237 (y-abs (abs y))
3238 (len (1- (integer-length y-abs))))
3239 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3240 (give-up-ir1-transform))
3241 (let ((mask (1- y-abs)))
3242 `(if (minusp x)
3243 (- (logand (- x) ,mask))
3244 (logand x ,mask)))))
3246 ;;; Return an expression to calculate the integer quotient of X and
3247 ;;; constant Y, using multiplication, shift and add/sub instead of
3248 ;;; division. Both arguments must be unsigned, fit in a machine word and
3249 ;;; Y must neither be zero nor a power of two. The quotient is rounded
3250 ;;; towards zero.
3251 ;;; The algorithm is taken from the paper "Division by Invariant
3252 ;;; Integers using Multiplication", 1994 by Torbj\"{o}rn Granlund and
3253 ;;; Peter L. Montgomery, Figures 4.2 and 6.2, modified to exclude the
3254 ;;; case of division by powers of two.
3255 ;;; The algorithm includes an adaptive precision argument. Use it, since
3256 ;;; we often have sub-word value ranges. Careful, in this case, we need
3257 ;;; p s.t 2^p > n, not the ceiling of the binary log.
3258 ;;; Also, for some reason, the paper prefers shifting to masking. Mask
3259 ;;; instead. Masking is equivalent to shifting right, then left again;
3260 ;;; all the intermediate values are still words, so we just have to shift
3261 ;;; right a bit more to compensate, at the end.
3263 ;;; The following two examples show an average case and the worst case
3264 ;;; with respect to the complexity of the generated expression, under
3265 ;;; a word size of 64 bits:
3267 ;;; (UNSIGNED-DIV-TRANSFORMER 10 MOST-POSITIVE-WORD) ->
3268 ;;; (ASH (%MULTIPLY (LOGANDC2 X 0) 14757395258967641293) -3)
3270 ;;; (UNSIGNED-DIV-TRANSFORMER 7 MOST-POSITIVE-WORD) ->
3271 ;;; (LET* ((NUM X)
3272 ;;; (T1 (%MULTIPLY NUM 2635249153387078803)))
3273 ;;; (ASH (LDB (BYTE 64 0)
3274 ;;; (+ T1 (ASH (LDB (BYTE 64 0)
3275 ;;; (- NUM T1))
3276 ;;; -1)))
3277 ;;; -2))
3279 (defun gen-unsigned-div-by-constant-expr (y max-x)
3280 (declare (type (integer 3 #.most-positive-word) y)
3281 (type word max-x))
3282 (aver (not (zerop (logand y (1- y)))))
3283 (labels ((ld (x)
3284 ;; the floor of the binary logarithm of (positive) X
3285 (integer-length (1- x)))
3286 (choose-multiplier (y precision)
3287 (do* ((l (ld y))
3288 (shift l (1- shift))
3289 (expt-2-n+l (expt 2 (+ sb!vm:n-word-bits l)))
3290 (m-low (truncate expt-2-n+l y) (ash m-low -1))
3291 (m-high (truncate (+ expt-2-n+l
3292 (ash expt-2-n+l (- precision)))
3294 (ash m-high -1)))
3295 ((not (and (< (ash m-low -1) (ash m-high -1))
3296 (> shift 0)))
3297 (values m-high shift)))))
3298 (let ((n (expt 2 sb!vm:n-word-bits))
3299 (precision (integer-length max-x))
3300 (shift1 0))
3301 (multiple-value-bind (m shift2)
3302 (choose-multiplier y precision)
3303 (when (and (>= m n) (evenp y))
3304 (setq shift1 (ld (logand y (- y))))
3305 (multiple-value-setq (m shift2)
3306 (choose-multiplier (/ y (ash 1 shift1))
3307 (- precision shift1))))
3308 (cond ((>= m n)
3309 (flet ((word (x)
3310 `(truly-the word ,x)))
3311 `(let* ((num x)
3312 (t1 (%multiply-high num ,(- m n))))
3313 (ash ,(word `(+ t1 (ash ,(word `(- num t1))
3314 -1)))
3315 ,(- 1 shift2)))))
3316 ((and (zerop shift1) (zerop shift2))
3317 (let ((max (truncate max-x y)))
3318 ;; Explicit TRULY-THE needed to get the FIXNUM=>FIXNUM
3319 ;; VOP.
3320 `(truly-the (integer 0 ,max)
3321 (%multiply-high x ,m))))
3323 `(ash (%multiply-high (logandc2 x ,(1- (ash 1 shift1))) ,m)
3324 ,(- (+ shift1 shift2)))))))))
3326 #!-multiply-high-vops
3327 (define-source-transform %multiply-high (x y)
3328 `(values (sb!bignum:%multiply ,x ,y)))
3330 ;;; If the divisor is constant and both args are positive and fit in a
3331 ;;; machine word, replace the division by a multiplication and possibly
3332 ;;; some shifts and an addition. Calculate the remainder by a second
3333 ;;; multiplication and a subtraction. Dead code elimination will
3334 ;;; suppress the latter part if only the quotient is needed. If the type
3335 ;;; of the dividend allows to derive that the quotient will always have
3336 ;;; the same value, emit much simpler code to handle that. (This case
3337 ;;; may be rare but it's easy to detect and the compiler doesn't find
3338 ;;; this optimization on its own.)
3339 (deftransform truncate ((x y) (word (constant-arg word))
3341 :policy (and (> speed compilation-speed)
3342 (> speed space)))
3343 "convert integer division to multiplication"
3344 (let* ((y (lvar-value y))
3345 (x-type (lvar-type x))
3346 (max-x (or (and (numeric-type-p x-type)
3347 (numeric-type-high x-type))
3348 most-positive-word)))
3349 ;; Division by zero, one or powers of two is handled elsewhere.
3350 (when (zerop (logand y (1- y)))
3351 (give-up-ir1-transform))
3352 `(let* ((quot ,(gen-unsigned-div-by-constant-expr y max-x))
3353 (rem (ldb (byte #.sb!vm:n-word-bits 0)
3354 (- x (* quot ,y)))))
3355 (values quot rem))))
3357 ;;;; arithmetic and logical identity operation elimination
3359 ;;; Flush calls to various arith functions that convert to the
3360 ;;; identity function or a constant.
3361 (macrolet ((def (name identity result)
3362 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
3363 "fold identity operations"
3364 ',result)))
3365 (def ash 0 x)
3366 (def logand -1 x)
3367 (def logand 0 0)
3368 (def logior 0 x)
3369 (def logior -1 -1)
3370 (def logxor -1 (lognot x))
3371 (def logxor 0 x))
3373 (defun least-zero-bit (x)
3374 (and (/= x -1)
3375 (1- (integer-length (logxor x (1+ x))))))
3377 (deftransform logand ((x y) (* (constant-arg t)) *)
3378 "fold identity operation"
3379 (let* ((y (lvar-value y))
3380 (width (or (least-zero-bit y) '*)))
3381 (unless (and (neq width 0) ; (logand x 0) handled elsewhere
3382 (csubtypep (lvar-type x)
3383 (specifier-type `(unsigned-byte ,width))))
3384 (give-up-ir1-transform))
3385 'x))
3387 (deftransform mask-signed-field ((size x) ((constant-arg t) *) *)
3388 "fold identity operation"
3389 (let ((size (lvar-value size)))
3390 (when (= size 0) (give-up-ir1-transform))
3391 (unless (csubtypep (lvar-type x) (specifier-type `(signed-byte ,size)))
3392 (give-up-ir1-transform))
3393 'x))
3395 (deftransform logior ((x y) (* (constant-arg integer)) *)
3396 "fold identity operation"
3397 (let* ((y (lvar-value y))
3398 (width (or (least-zero-bit (lognot y))
3399 (give-up-ir1-transform)))) ; (logior x 0) handled elsewhere
3400 (unless (csubtypep (lvar-type x)
3401 (specifier-type `(integer ,(- (ash 1 width)) -1)))
3402 (give-up-ir1-transform))
3403 'x))
3405 ;;; Pick off easy association opportunities for constant folding.
3406 ;;; More complicated stuff that also depends on commutativity
3407 ;;; (e.g. (f (f x k1) (f y k2)) => (f (f x y) (f k1 k2))) should
3408 ;;; probably be handled with a more general tree-rewriting pass.
3409 (macrolet ((def (operator &key (type 'integer) (folded operator))
3410 `(deftransform ,operator ((x z) (,type (constant-arg ,type)))
3411 ,(format nil "associate ~A/~A of constants"
3412 operator folded)
3413 (binding* ((node (if (lvar-has-single-use-p x)
3414 (lvar-use x)
3415 (give-up-ir1-transform)))
3416 (nil (or (and (combination-p node)
3417 (eq (lvar-fun-name
3418 (combination-fun node))
3419 ',folded))
3420 (give-up-ir1-transform)))
3421 (y (second (combination-args node)))
3422 (nil (or (constant-lvar-p y)
3423 (give-up-ir1-transform)))
3424 (y (lvar-value y)))
3425 (unless (typep y ',type)
3426 (give-up-ir1-transform))
3427 (splice-fun-args x ',folded 2)
3428 `(lambda (x y z)
3429 (declare (ignore y z))
3430 ;; (operator (folded x y) z)
3431 ;; == (operator x (folded z y))
3432 (,',operator x ',(,folded (lvar-value z) y)))))))
3433 (def logand)
3434 (def logior)
3435 (def logxor)
3436 (def logtest :folded logand)
3437 (def + :type rational)
3438 (def + :type rational :folded -)
3439 (def * :type rational)
3440 (def * :type rational :folded /))
3442 (deftransform mask-signed-field ((width x) ((constant-arg unsigned-byte) *))
3443 "Fold mask-signed-field/mask-signed-field of constant width"
3444 (binding* ((node (if (lvar-has-single-use-p x)
3445 (lvar-use x)
3446 (give-up-ir1-transform)))
3447 (nil (or (combination-p node)
3448 (give-up-ir1-transform)))
3449 (nil (or (eq (lvar-fun-name (combination-fun node))
3450 'mask-signed-field)
3451 (give-up-ir1-transform)))
3452 (x-width (first (combination-args node)))
3453 (nil (or (constant-lvar-p x-width)
3454 (give-up-ir1-transform)))
3455 (x-width (lvar-value x-width)))
3456 (unless (typep x-width 'unsigned-byte)
3457 (give-up-ir1-transform))
3458 (splice-fun-args x 'mask-signed-field 2)
3459 `(lambda (width x-width x)
3460 (declare (ignore width x-width))
3461 (mask-signed-field ,(min (lvar-value width) x-width) x))))
3463 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
3464 ;;; (* 0 -4.0) is -0.0.
3465 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
3466 "convert (- 0 x) to negate"
3467 '(%negate y))
3468 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
3469 "convert (* x 0) to 0"
3472 (deftransform %negate ((x) (rational))
3473 "Eliminate %negate/%negate of rationals"
3474 (splice-fun-args x '%negate 1)
3475 '(the rational x))
3477 (deftransform %negate ((x) (number))
3478 "Combine %negate/*"
3479 (let ((use (lvar-uses x))
3480 arg)
3481 (unless (and (combination-p use)
3482 (eql '* (lvar-fun-name (combination-fun use)))
3483 (constant-lvar-p (setf arg (second (combination-args use))))
3484 (numberp (setf arg (lvar-value arg))))
3485 (give-up-ir1-transform))
3486 (splice-fun-args x '* 2)
3487 `(lambda (x y)
3488 (declare (ignore y))
3489 (* x ,(- arg)))))
3491 ;;; Return T if in an arithmetic op including lvars X and Y, the
3492 ;;; result type is not affected by the type of X. That is, Y is at
3493 ;;; least as contagious as X.
3494 #+nil
3495 (defun not-more-contagious (x y)
3496 (declare (type continuation x y))
3497 (let ((x (lvar-type x))
3498 (y (lvar-type y)))
3499 (values (type= (numeric-contagion x y)
3500 (numeric-contagion y y)))))
3501 ;;; Patched version by Raymond Toy. dtc: Should be safer although it
3502 ;;; XXX needs more work as valid transforms are missed; some cases are
3503 ;;; specific to particular transform functions so the use of this
3504 ;;; function may need a re-think.
3505 (defun not-more-contagious (x y)
3506 (declare (type lvar x y))
3507 (flet ((simple-numeric-type (num)
3508 (and (numeric-type-p num)
3509 ;; Return non-NIL if NUM is integer, rational, or a float
3510 ;; of some type (but not FLOAT)
3511 (case (numeric-type-class num)
3512 ((integer rational)
3514 (float
3515 (numeric-type-format num))
3517 nil)))))
3518 (let ((x (lvar-type x))
3519 (y (lvar-type y)))
3520 (if (and (simple-numeric-type x)
3521 (simple-numeric-type y))
3522 (values (type= (numeric-contagion x y)
3523 (numeric-contagion y y)))))))
3525 (def!type exact-number ()
3526 '(or rational (complex rational)))
3528 ;;; Fold (+ x 0).
3530 ;;; Only safely applicable for exact numbers. For floating-point
3531 ;;; x, one would have to first show that neither x or y are signed
3532 ;;; 0s, and that x isn't an SNaN.
3533 (deftransform + ((x y) (exact-number (constant-arg (eql 0))) *)
3534 "fold zero arg"
3537 ;;; Fold (- x 0).
3538 (deftransform - ((x y) (exact-number (constant-arg (eql 0))) *)
3539 "fold zero arg"
3542 ;;; Fold (OP x +/-1)
3544 ;;; %NEGATE might not always signal correctly.
3545 (macrolet
3546 ((def (name result minus-result)
3547 `(deftransform ,name ((x y)
3548 (exact-number (constant-arg (member 1 -1))))
3549 "fold identity operations"
3550 (if (minusp (lvar-value y)) ',minus-result ',result))))
3551 (def * x (%negate x))
3552 (def / x (%negate x))
3553 (def expt x (/ 1 x)))
3555 ;;; Fold (expt x n) into multiplications for small integral values of
3556 ;;; N; convert (expt x 1/2) to sqrt.
3557 (deftransform expt ((x y) (t (constant-arg real)) *)
3558 "recode as multiplication or sqrt"
3559 (let ((val (lvar-value y)))
3560 ;; If Y would cause the result to be promoted to the same type as
3561 ;; Y, we give up. If not, then the result will be the same type
3562 ;; as X, so we can replace the exponentiation with simple
3563 ;; multiplication and division for small integral powers.
3564 (unless (not-more-contagious y x)
3565 (give-up-ir1-transform))
3566 (cond ((zerop val)
3567 (let ((x-type (lvar-type x)))
3568 (cond ((csubtypep x-type (specifier-type '(or rational
3569 (complex rational))))
3571 ((csubtypep x-type (specifier-type 'real))
3572 `(if (rationalp x)
3574 (float 1 x)))
3575 ((csubtypep x-type (specifier-type 'complex))
3576 ;; both parts are float
3577 `(1+ (* x ,val)))
3578 (t (give-up-ir1-transform)))))
3579 ((= val 2) '(* x x))
3580 ((= val -2) '(/ (* x x)))
3581 ((= val 3) '(* x x x))
3582 ((= val -3) '(/ (* x x x)))
3583 ((= val 1/2) '(sqrt x))
3584 ((= val -1/2) '(/ (sqrt x)))
3585 (t (give-up-ir1-transform)))))
3587 (deftransform expt ((x y) ((constant-arg (member -1 -1.0 -1.0d0)) integer) *)
3588 "recode as an ODDP check"
3589 (let ((val (lvar-value x)))
3590 (if (eql -1 val)
3591 '(- 1 (* 2 (logand 1 y)))
3592 `(if (oddp y)
3593 ,val
3594 ,(abs val)))))
3596 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
3597 ;;; transformations?
3598 ;;; Perhaps we should have to prove that the denominator is nonzero before
3599 ;;; doing them? -- WHN 19990917
3600 (macrolet ((def (name)
3601 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3603 "fold zero arg"
3604 0)))
3605 (def ash)
3606 (def /))
3608 (macrolet ((def (name)
3609 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3611 "fold zero arg"
3612 '(values 0 0))))
3613 (def truncate)
3614 (def round)
3615 (def floor)
3616 (def ceiling))
3618 (macrolet ((def (name &optional float)
3619 (let ((x (if float '(float x) 'x)))
3620 `(deftransform ,name ((x y) (integer (constant-arg (member 1 -1)))
3622 "fold division by 1"
3623 `(values ,(if (minusp (lvar-value y))
3624 '(%negate ,x)
3625 ',x) 0)))))
3626 (def truncate)
3627 (def round)
3628 (def floor)
3629 (def ceiling)
3630 (def ftruncate t)
3631 (def fround t)
3632 (def ffloor t)
3633 (def fceiling t))
3636 ;;;; character operations
3638 (deftransform two-arg-char-equal ((a b) (base-char base-char) *
3639 :policy (> speed space))
3640 "open code"
3641 '(let* ((ac (char-code a))
3642 (bc (char-code b))
3643 (sum (logxor ac bc)))
3644 (or (zerop sum)
3645 (when (eql sum #x20)
3646 (let ((sum (+ ac bc)))
3647 (or (and (> sum 161) (< sum 213))
3648 (and (> sum 415) (< sum 461))
3649 (and (> sum 463) (< sum 477))))))))
3651 (deftransform two-arg-char-equal ((a b) (* (constant-arg character)) *
3652 :node node)
3653 (let ((char (lvar-value b)))
3654 (if (both-case-p char)
3655 (let ((reverse (if (upper-case-p char)
3656 (char-downcase char)
3657 (char-upcase char))))
3658 (if (policy node (> speed space))
3659 `(or (char= a ,char)
3660 (char= a ,reverse))
3661 `(char-equal-constant a ,char ,reverse)))
3662 '(char= a b))))
3664 (deftransform char-upcase ((x) (base-char))
3665 "open code"
3666 '(let ((n-code (char-code x)))
3667 (if (or (and (> n-code #o140) ; Octal 141 is #\a.
3668 (< n-code #o173)) ; Octal 172 is #\z.
3669 (and (> n-code #o337)
3670 (< n-code #o367))
3671 (and (> n-code #o367)
3672 (< n-code #o377)))
3673 (code-char (logxor #x20 n-code))
3674 x)))
3676 (deftransform char-downcase ((x) (base-char))
3677 "open code"
3678 '(let ((n-code (char-code x)))
3679 (if (or (and (> n-code 64) ; 65 is #\A.
3680 (< n-code 91)) ; 90 is #\Z.
3681 (and (> n-code 191)
3682 (< n-code 215))
3683 (and (> n-code 215)
3684 (< n-code 223)))
3685 (code-char (logxor #x20 n-code))
3686 x)))
3688 ;;;; equality predicate transforms
3690 ;;; Return true if X and Y are lvars whose only use is a
3691 ;;; reference to the same leaf, and the value of the leaf cannot
3692 ;;; change.
3693 (defun same-leaf-ref-p (x y)
3694 (declare (type lvar x y))
3695 (let ((x-use (principal-lvar-use x))
3696 (y-use (principal-lvar-use y)))
3697 (and (ref-p x-use)
3698 (ref-p y-use)
3699 (eq (ref-leaf x-use) (ref-leaf y-use))
3700 (constant-reference-p x-use))))
3702 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
3703 ;;; if there is no intersection between the types of the arguments,
3704 ;;; then the result is definitely false.
3705 (deftransforms (eq char=) ((x y) * *)
3706 "Simple equality transform"
3707 (cond
3708 ((same-leaf-ref-p x y) t)
3709 ((not (types-equal-or-intersect (lvar-type x) (lvar-type y)))
3710 nil)
3711 (t (give-up-ir1-transform))))
3713 ;;; Can't use the above thing, since TYPES-EQUAL-OR-INTERSECT is case sensitive.
3714 (deftransform two-arg-char-equal ((x y) * *)
3715 (cond
3716 ((same-leaf-ref-p x y) t)
3717 (t (give-up-ir1-transform))))
3719 ;;; This is similar to SIMPLE-EQUALITY-TRANSFORM, except that we also
3720 ;;; try to convert to a type-specific predicate or EQ:
3721 ;;; -- If both args are characters, convert to CHAR=. This is better than
3722 ;;; just converting to EQ, since CHAR= may have special compilation
3723 ;;; strategies for non-standard representations, etc.
3724 ;;; -- If either arg is definitely a fixnum, we check to see if X is
3725 ;;; constant and if so, put X second. Doing this results in better
3726 ;;; code from the backend, since the backend assumes that any constant
3727 ;;; argument comes second.
3728 ;;; -- If either arg is definitely not a number or a fixnum, then we
3729 ;;; can compare with EQ.
3730 ;;; -- Otherwise, we try to put the arg we know more about second. If X
3731 ;;; is constant then we put it second. If X is a subtype of Y, we put
3732 ;;; it second. These rules make it easier for the back end to match
3733 ;;; these interesting cases.
3734 (deftransform eql ((x y) * * :node node)
3735 "convert to simpler equality predicate"
3736 (let ((x-type (lvar-type x))
3737 (y-type (lvar-type y))
3738 #!+integer-eql-vop (int-type (specifier-type 'integer))
3739 (char-type (specifier-type 'character)))
3740 (cond
3741 ((same-leaf-ref-p x y) t)
3742 ((not (types-equal-or-intersect x-type y-type))
3743 nil)
3744 ((and (csubtypep x-type char-type)
3745 (csubtypep y-type char-type))
3746 '(char= x y))
3747 ((or (eq-comparable-type-p x-type) (eq-comparable-type-p y-type))
3748 '(eq y x))
3749 #!+integer-eql-vop
3750 ((or (csubtypep x-type int-type) (csubtypep y-type int-type))
3751 '(%eql/integer x y))
3753 (give-up-ir1-transform)))))
3755 ;;; similarly to the EQL transform above, we attempt to constant-fold
3756 ;;; or convert to a simpler predicate: mostly we have to be careful
3757 ;;; with strings and bit-vectors.
3758 (deftransform equal ((x y) * *)
3759 "convert to simpler equality predicate"
3760 (let ((x-type (lvar-type x))
3761 (y-type (lvar-type y))
3762 (combination-type (specifier-type '(or bit-vector string
3763 cons pathname))))
3764 (flet ((both-csubtypep (type)
3765 (let ((ctype (specifier-type type)))
3766 (and (csubtypep x-type ctype)
3767 (csubtypep y-type ctype)))))
3768 (cond
3769 ((same-leaf-ref-p x y) t)
3770 ((and (constant-lvar-p x)
3771 (equal (lvar-value x) ""))
3772 `(and (stringp y)
3773 (zerop (length y))))
3774 ((and (constant-lvar-p y)
3775 (equal (lvar-value y) ""))
3776 `(and (stringp x)
3777 (zerop (length x))))
3778 ((both-csubtypep 'string)
3779 '(string= x y))
3780 ((both-csubtypep 'bit-vector)
3781 '(bit-vector-= x y))
3782 ((both-csubtypep 'pathname)
3783 '(pathname= x y))
3784 ((or (not (types-equal-or-intersect x-type combination-type))
3785 (not (types-equal-or-intersect y-type combination-type)))
3786 (if (types-equal-or-intersect x-type y-type)
3787 '(eql x y)
3788 ;; Can't simply check for type intersection if both types are combination-type
3789 ;; since array specialization would mean types don't intersect, even when EQUAL
3790 ;; doesn't care for specialization.
3791 ;; Previously checking for intersection in the outer COND resulted in
3793 ;; (equal (the (cons (or simple-bit-vector
3794 ;; simple-base-string))
3795 ;; x)
3796 ;; (the (cons (or (and bit-vector (not simple-array))
3797 ;; (simple-array character (*))))
3798 ;; y))
3799 ;; being incorrectly folded to NIL
3800 nil))
3801 (t (give-up-ir1-transform))))))
3803 (deftransform equalp ((x y) * *)
3804 "convert to simpler equality predicate"
3805 (let ((x-type (lvar-type x))
3806 (y-type (lvar-type y))
3807 (combination-type (specifier-type '(or number array
3808 character
3809 cons pathname
3810 instance hash-table))))
3811 (flet ((both-csubtypep (type)
3812 (let ((ctype (specifier-type type)))
3813 (and (csubtypep x-type ctype)
3814 (csubtypep y-type ctype)))))
3815 (cond
3816 ((same-leaf-ref-p x y) t)
3817 ((and (constant-lvar-p x)
3818 (equal (lvar-value x) ""))
3819 `(and (stringp y)
3820 (zerop (length y))))
3821 ((and (constant-lvar-p y)
3822 (equal (lvar-value y) ""))
3823 `(and (stringp x)
3824 (zerop (length x))))
3825 ((both-csubtypep 'string)
3826 '(string-equal x y))
3827 ((both-csubtypep 'bit-vector)
3828 '(bit-vector-= x y))
3829 ((both-csubtypep 'pathname)
3830 '(pathname= x y))
3831 ((both-csubtypep 'character)
3832 '(char-equal x y))
3833 ((both-csubtypep 'number)
3834 '(= x y))
3835 ((both-csubtypep 'hash-table)
3836 '(hash-table-equalp x y))
3837 ((or (not (types-equal-or-intersect x-type combination-type))
3838 (not (types-equal-or-intersect y-type combination-type)))
3839 ;; See the comment about specialized types in the EQUAL transform above
3840 (if (types-equal-or-intersect y-type x-type)
3841 '(eq x y)
3842 nil))
3843 (t (give-up-ir1-transform))))))
3845 ;;; Convert to EQL if both args are rational and complexp is specified
3846 ;;; and the same for both.
3847 (deftransform = ((x y) (number number) *)
3848 "open code"
3849 (let ((x-type (lvar-type x))
3850 (y-type (lvar-type y)))
3851 (cond ((or (and (csubtypep x-type (specifier-type 'float))
3852 (csubtypep y-type (specifier-type 'float)))
3853 (and (csubtypep x-type (specifier-type '(complex float)))
3854 (csubtypep y-type (specifier-type '(complex float))))
3855 #!+complex-float-vops
3856 (and (csubtypep x-type (specifier-type '(or single-float (complex single-float))))
3857 (csubtypep y-type (specifier-type '(or single-float (complex single-float)))))
3858 #!+complex-float-vops
3859 (and (csubtypep x-type (specifier-type '(or double-float (complex double-float))))
3860 (csubtypep y-type (specifier-type '(or double-float (complex double-float))))))
3861 ;; They are both floats. Leave as = so that -0.0 is
3862 ;; handled correctly.
3863 (give-up-ir1-transform))
3864 ((or (and (csubtypep x-type (specifier-type 'rational))
3865 (csubtypep y-type (specifier-type 'rational)))
3866 (and (csubtypep x-type
3867 (specifier-type '(complex rational)))
3868 (csubtypep y-type
3869 (specifier-type '(complex rational)))))
3870 ;; They are both rationals and complexp is the same.
3871 ;; Convert to EQL.
3872 '(eql x y))
3874 (give-up-ir1-transform
3875 "The operands might not be the same type.")))))
3877 (defun maybe-float-lvar-p (lvar)
3878 (neq *empty-type* (type-intersection (specifier-type 'float)
3879 (lvar-type lvar))))
3881 (flet ((maybe-invert (node op inverted x y)
3882 ;; Don't invert if either argument can be a float (NaNs)
3883 (cond
3884 ((or (maybe-float-lvar-p x) (maybe-float-lvar-p y))
3885 (delay-ir1-transform node :constraint)
3886 `(or (,op x y) (= x y)))
3888 `(if (,inverted x y) nil t)))))
3889 (deftransform >= ((x y) (number number) * :node node)
3890 "invert or open code"
3891 (maybe-invert node '> '< x y))
3892 (deftransform <= ((x y) (number number) * :node node)
3893 "invert or open code"
3894 (maybe-invert node '< '> x y)))
3896 ;;; See whether we can statically determine (< X Y) using type
3897 ;;; information. If X's high bound is < Y's low, then X < Y.
3898 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
3899 ;;; NIL). If not, at least make sure any constant arg is second.
3900 (macrolet ((def (name inverse reflexive-p surely-true surely-false)
3901 `(deftransform ,name ((x y))
3902 "optimize using intervals"
3903 (if (and (same-leaf-ref-p x y)
3904 ;; For non-reflexive functions we don't need
3905 ;; to worry about NaNs: (non-ref-op NaN NaN) => false,
3906 ;; but with reflexive ones we don't know...
3907 ,@(when reflexive-p
3908 '((and (not (maybe-float-lvar-p x))
3909 (not (maybe-float-lvar-p y))))))
3910 ,reflexive-p
3911 (let ((ix (or (type-approximate-interval (lvar-type x))
3912 (give-up-ir1-transform)))
3913 (iy (or (type-approximate-interval (lvar-type y))
3914 (give-up-ir1-transform))))
3915 (cond (,surely-true
3917 (,surely-false
3918 nil)
3919 ((and (constant-lvar-p x)
3920 (not (constant-lvar-p y)))
3921 `(,',inverse y x))
3923 (give-up-ir1-transform))))))))
3924 (def = = t (interval-= ix iy) (interval-/= ix iy))
3925 (def /= /= nil (interval-/= ix iy) (interval-= ix iy))
3926 (def < > nil (interval-< ix iy) (interval->= ix iy))
3927 (def > < nil (interval-< iy ix) (interval->= iy ix))
3928 (def <= >= t (interval->= iy ix) (interval-< iy ix))
3929 (def >= <= t (interval->= ix iy) (interval-< ix iy)))
3931 (defun ir1-transform-char< (x y first second inverse)
3932 (cond
3933 ((same-leaf-ref-p x y) nil)
3934 ;; If we had interval representation of character types, as we
3935 ;; might eventually have to to support 2^21 characters, then here
3936 ;; we could do some compile-time computation as in transforms for
3937 ;; < above. -- CSR, 2003-07-01
3938 ((and (constant-lvar-p first)
3939 (not (constant-lvar-p second)))
3940 `(,inverse y x))
3941 (t (give-up-ir1-transform))))
3943 (deftransform char< ((x y) (character character) *)
3944 (ir1-transform-char< x y x y 'char>))
3946 (deftransform char> ((x y) (character character) *)
3947 (ir1-transform-char< y x x y 'char<))
3949 ;;;; converting N-arg comparisons
3950 ;;;;
3951 ;;;; We convert calls to N-arg comparison functions such as < into
3952 ;;;; two-arg calls. This transformation is enabled for all such
3953 ;;;; comparisons in this file. If any of these predicates are not
3954 ;;;; open-coded, then the transformation should be removed at some
3955 ;;;; point to avoid pessimization.
3957 ;;; This function is used for source transformation of N-arg
3958 ;;; comparison functions other than inequality. We deal both with
3959 ;;; converting to two-arg calls and inverting the sense of the test,
3960 ;;; if necessary. If the call has two args, then we pass or return a
3961 ;;; negated test as appropriate. If it is a degenerate one-arg call,
3962 ;;; then we transform to code that returns true. Otherwise, we bind
3963 ;;; all the arguments and expand into a bunch of IFs.
3964 (defun multi-compare (predicate args not-p type &optional force-two-arg-p)
3965 (let ((nargs (length args)))
3966 (cond ((< nargs 1) (values nil t))
3967 ((= nargs 1) `(progn (the ,type ,@args) t))
3968 ((= nargs 2)
3969 (if not-p
3970 `(if (,predicate ,(first args) ,(second args)) nil t)
3971 (if force-two-arg-p
3972 `(,predicate ,(first args) ,(second args))
3973 (values nil t))))
3975 (do* ((i (1- nargs) (1- i))
3976 (last nil current)
3977 (current (gensym) (gensym))
3978 (vars (list current) (cons current vars))
3979 (result t (if not-p
3980 `(if (,predicate ,current ,last)
3981 nil ,result)
3982 `(if (,predicate ,current ,last)
3983 ,result nil))))
3984 ((zerop i)
3985 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
3986 ,@args)))))))
3988 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
3989 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
3990 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
3991 ;;; We cannot do the inversion for >= and <= here, since both
3992 ;;; (< NaN X) and (> NaN X)
3993 ;;; are false, and we don't have type-information available yet. The
3994 ;;; deftransforms for two-argument versions of >= and <= takes care of
3995 ;;; the inversion to > and < when possible.
3996 (define-source-transform <= (&rest args) (multi-compare '<= args nil 'real))
3997 (define-source-transform >= (&rest args) (multi-compare '>= args nil 'real))
3999 (define-source-transform char= (&rest args) (multi-compare 'char= args nil
4000 'character))
4001 (define-source-transform char< (&rest args) (multi-compare 'char< args nil
4002 'character))
4003 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
4004 'character))
4005 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
4006 'character))
4007 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
4008 'character))
4010 (define-source-transform char-equal (&rest args)
4011 (multi-compare 'two-arg-char-equal args nil 'character t))
4012 (define-source-transform char-lessp (&rest args)
4013 (multi-compare 'two-arg-char-lessp args nil 'character t))
4014 (define-source-transform char-greaterp (&rest args)
4015 (multi-compare 'two-arg-char-greaterp args nil 'character t))
4016 (define-source-transform char-not-greaterp (&rest args)
4017 (multi-compare 'two-arg-char-greaterp args t 'character t))
4018 (define-source-transform char-not-lessp (&rest args)
4019 (multi-compare 'two-arg-char-lessp args t 'character t))
4021 ;;; This function does source transformation of N-arg inequality
4022 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
4023 ;;; arg cases. If there are more than two args, then we expand into
4024 ;;; the appropriate n^2 comparisons only when speed is important.
4025 (declaim (ftype (function (symbol list t) *) multi-not-equal))
4026 (defun multi-not-equal (predicate args type)
4027 (let ((nargs (length args)))
4028 (cond ((< nargs 1) (values nil t))
4029 ((= nargs 1) `(progn (the ,type ,@args) t))
4030 ((= nargs 2)
4031 `(if (,predicate ,(first args) ,(second args)) nil t))
4032 ((not (policy *lexenv*
4033 (and (>= speed space)
4034 (>= speed compilation-speed))))
4035 (values nil t))
4037 (let ((vars (make-gensym-list nargs)))
4038 (do ((var vars next)
4039 (next (cdr vars) (cdr next))
4040 (result t))
4041 ((null next)
4042 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
4043 ,@args))
4044 (let ((v1 (first var)))
4045 (dolist (v2 next)
4046 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
4048 (define-source-transform /= (&rest args)
4049 (multi-not-equal '= args 'number))
4050 (define-source-transform char/= (&rest args)
4051 (multi-not-equal 'char= args 'character))
4052 (define-source-transform char-not-equal (&rest args)
4053 (multi-not-equal 'char-equal args 'character))
4055 ;;; Expand MAX and MIN into the obvious comparisons.
4056 (define-source-transform max (arg0 &rest rest)
4057 (once-only ((arg0 arg0))
4058 (if (null rest)
4059 `(values (the real ,arg0))
4060 `(let ((maxrest (max ,@rest)))
4061 (if (>= ,arg0 maxrest) ,arg0 maxrest)))))
4062 (define-source-transform min (arg0 &rest rest)
4063 (once-only ((arg0 arg0))
4064 (if (null rest)
4065 `(values (the real ,arg0))
4066 `(let ((minrest (min ,@rest)))
4067 (if (<= ,arg0 minrest) ,arg0 minrest)))))
4069 ;;; Simplify some cross-type comparisons
4070 (macrolet ((def (comparator round)
4071 `(progn
4072 (deftransform ,comparator
4073 ((x y) (rational (constant-arg float)))
4074 "open-code RATIONAL to FLOAT comparison"
4075 (let ((y (lvar-value y)))
4076 #-sb-xc-host
4077 (when (or (float-nan-p y)
4078 (float-infinity-p y))
4079 (give-up-ir1-transform))
4080 (setf y (rational y))
4081 `(,',comparator
4082 x ,(if (csubtypep (lvar-type x)
4083 (specifier-type 'integer))
4084 (,round y)
4085 y))))
4086 (deftransform ,comparator
4087 ((x y) (integer (constant-arg ratio)))
4088 "open-code INTEGER to RATIO comparison"
4089 `(,',comparator x ,(,round (lvar-value y)))))))
4090 (def < ceiling)
4091 (def > floor))
4093 (deftransform = ((x y) (rational (constant-arg float)))
4094 "open-code RATIONAL to FLOAT comparison"
4095 (let ((y (lvar-value y)))
4096 #-sb-xc-host
4097 (when (or (float-nan-p y)
4098 (float-infinity-p y))
4099 (give-up-ir1-transform))
4100 (setf y (rational y))
4101 (if (and (csubtypep (lvar-type x)
4102 (specifier-type 'integer))
4103 (ratiop y))
4105 `(= x ,y))))
4107 (deftransform = ((x y) (integer (constant-arg ratio)))
4108 "constant-fold INTEGER to RATIO comparison"
4109 nil)
4111 ;;;; converting N-arg arithmetic functions
4112 ;;;;
4113 ;;;; N-arg arithmetic and logic functions are associated into two-arg
4114 ;;;; versions, and degenerate cases are flushed.
4116 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
4117 (declaim (ftype (sfunction (symbol t list) list) associate-args))
4118 (defun associate-args (fun first-arg more-args)
4119 (aver more-args)
4120 (let ((next (rest more-args))
4121 (arg (first more-args)))
4122 (if (null next)
4123 `(,fun ,first-arg ,arg)
4124 (associate-args fun `(,fun ,first-arg ,arg) next))))
4126 ;;; Reduce constants in ARGS list.
4127 (declaim (ftype (sfunction (symbol list symbol) list) reduce-constants))
4128 (defun reduce-constants (fun args one-arg-result-type)
4129 (let ((one-arg-constant-p (ecase one-arg-result-type
4130 (number #'numberp)
4131 (integer #'integerp)))
4132 (reduced-value)
4133 (reduced-p nil))
4134 (collect ((not-constants))
4135 (dolist (arg args)
4136 (let ((value (if (constantp arg)
4137 (constant-form-value arg)
4138 arg)))
4139 (cond ((not (funcall one-arg-constant-p value))
4140 (not-constants arg))
4141 (reduced-value
4142 (setf reduced-value (funcall fun reduced-value value)
4143 reduced-p t))
4145 (setf reduced-value value)))))
4146 ;; It is tempting to drop constants reduced to identity here,
4147 ;; but if X is SNaN in (* X 1), we cannot drop the 1.
4148 (if (not-constants)
4149 (if reduced-p
4150 `(,reduced-value ,@(not-constants))
4151 args)
4152 `(,reduced-value)))))
4154 ;;; Do source transformations for transitive functions such as +.
4155 ;;; One-arg cases are replaced with the arg and zero arg cases with
4156 ;;; the identity. ONE-ARG-RESULT-TYPE is the type to ensure (with THE)
4157 ;;; that the argument in one-argument calls is.
4158 (declaim (ftype (function (symbol list t &optional symbol list)
4159 * ; KLUDGE: avoid "assertion too complex to check"
4160 #|(values t &optional (member nil t))|#)
4161 source-transform-transitive))
4162 (defun source-transform-transitive (fun args identity
4163 &optional (one-arg-result-type 'number)
4164 (one-arg-prefixes '(values)))
4165 (case (length args)
4166 (0 identity)
4167 (1 `(,@one-arg-prefixes (the ,one-arg-result-type ,(first args))))
4168 (2 (values nil t))
4170 (let* ((reduced-args (reduce-constants fun args one-arg-result-type))
4171 (first (first reduced-args))
4172 (rest (rest reduced-args)))
4173 (if rest
4174 (associate-args fun first rest)
4175 first)))))
4177 (define-source-transform + (&rest args)
4178 (source-transform-transitive '+ args 0))
4179 (define-source-transform * (&rest args)
4180 (source-transform-transitive '* args 1))
4181 (define-source-transform logior (&rest args)
4182 (source-transform-transitive 'logior args 0 'integer))
4183 (define-source-transform logxor (&rest args)
4184 (source-transform-transitive 'logxor args 0 'integer))
4185 (define-source-transform logand (&rest args)
4186 (source-transform-transitive 'logand args -1 'integer))
4187 (define-source-transform logeqv (&rest args)
4188 (source-transform-transitive 'logeqv args -1 'integer))
4189 (define-source-transform gcd (&rest args)
4190 (source-transform-transitive 'gcd args 0 'integer '(abs)))
4191 (define-source-transform lcm (&rest args)
4192 (source-transform-transitive 'lcm args 1 'integer '(abs)))
4194 ;;; Do source transformations for intransitive n-arg functions such as
4195 ;;; /. With one arg, we form the inverse. With two args we pass.
4196 ;;; Otherwise we associate into two-arg calls.
4197 (declaim (ftype (function (symbol symbol list list &optional symbol)
4198 * ; KLUDGE: avoid "assertion too complex to check"
4199 #|(values list &optional (member nil t))|#)
4200 source-transform-intransitive))
4201 (defun source-transform-intransitive (fun fun* args one-arg-prefixes
4202 &optional (one-arg-result-type 'number))
4203 (case (length args)
4204 ((0 2) (values nil t))
4205 (1 `(,@one-arg-prefixes (the ,one-arg-result-type ,(first args))))
4207 (let ((reduced-args
4208 (reduce-constants fun* (rest args) one-arg-result-type)))
4209 (associate-args fun (first args) reduced-args)))))
4211 (define-source-transform - (&rest args)
4212 (source-transform-intransitive '- '+ args '(%negate)))
4213 (define-source-transform / (&rest args)
4214 (source-transform-intransitive '/ '* args '(/ 1)))
4216 ;;;; transforming APPLY
4218 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
4219 ;;; only needs to understand one kind of variable-argument call. It is
4220 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
4221 (define-source-transform apply (fun arg &rest more-args)
4222 (let ((args (cons arg more-args)))
4223 `(multiple-value-call ,fun
4224 ,@(mapcar (lambda (x) `(values ,x)) (butlast args))
4225 (values-list ,(car (last args))))))
4227 ;;;; transforming references to &REST argument
4229 ;;; We add magical &MORE arguments to all functions with &REST. If ARG names
4230 ;;; the &REST argument, this returns the lambda-vars for the context and
4231 ;;; count.
4232 (defun possible-rest-arg-context (arg)
4233 (when (symbolp arg)
4234 (let* ((var (lexenv-find arg vars))
4235 (info (when (lambda-var-p var)
4236 (lambda-var-arg-info var))))
4237 (when (and info
4238 (eq :rest (arg-info-kind info))
4239 (consp (arg-info-default info)))
4240 (values-list (arg-info-default info))))))
4242 (defun mark-more-context-used (rest-var)
4243 (let ((info (lambda-var-arg-info rest-var)))
4244 (aver (eq :rest (arg-info-kind info)))
4245 (destructuring-bind (context count &optional used) (arg-info-default info)
4246 (unless used
4247 (setf (arg-info-default info) (list context count t))))))
4249 (defun mark-more-context-invalid (rest-var)
4250 (let ((info (lambda-var-arg-info rest-var)))
4251 (aver (eq :rest (arg-info-kind info)))
4252 (setf (arg-info-default info) t)))
4254 ;;; This determines of we the REF to a &REST variable is headed towards
4255 ;;; parts unknown, or if we can really use the context.
4256 (defun rest-var-more-context-ok (lvar)
4257 (let* ((use (lvar-use lvar))
4258 (var (when (ref-p use) (ref-leaf use)))
4259 (home (when (lambda-var-p var) (lambda-var-home var)))
4260 (info (when (lambda-var-p var) (lambda-var-arg-info var)))
4261 (restp (when info (eq :rest (arg-info-kind info)))))
4262 (flet ((ref-good-for-more-context-p (ref)
4263 (when (not (node-lvar ref)) ; ref that goes nowhere is ok
4264 (return-from ref-good-for-more-context-p t))
4265 (let ((dest (principal-lvar-end (node-lvar ref))))
4266 (and (combination-p dest)
4267 ;; If the destination is to anything but these, we're going to
4268 ;; actually need the rest list -- and since other operations
4269 ;; might modify the list destructively, the using the context
4270 ;; isn't good anywhere else either.
4271 (lvar-fun-is (combination-fun dest)
4272 '(%rest-values %rest-ref %rest-length
4273 %rest-null %rest-true))
4274 ;; If the home lambda is different and isn't DX, it might
4275 ;; escape -- in which case using the more context isn't safe.
4276 (let ((clambda (node-home-lambda dest)))
4277 (or (eq home clambda)
4278 (leaf-dynamic-extent clambda)))))))
4279 (let ((ok (and restp
4280 (consp (arg-info-default info))
4281 (not (lambda-var-specvar var))
4282 (not (lambda-var-sets var))
4283 (every #'ref-good-for-more-context-p (lambda-var-refs var)))))
4284 (if ok
4285 (mark-more-context-used var)
4286 (when restp
4287 (mark-more-context-invalid var)))
4288 ok))))
4290 ;;; VALUES-LIST -> %REST-VALUES
4291 (define-source-transform values-list (list)
4292 (multiple-value-bind (context count) (possible-rest-arg-context list)
4293 (if context
4294 `(%rest-values ,list ,context ,count)
4295 (values nil t))))
4297 ;;; NTH -> %REST-REF
4298 (define-source-transform nth (n list)
4299 (multiple-value-bind (context count) (possible-rest-arg-context list)
4300 (if context
4301 `(%rest-ref ,n ,list ,context ,count)
4302 `(car (nthcdr ,n ,list)))))
4303 (define-source-transform fast-&rest-nth (n list)
4304 (multiple-value-bind (context count) (possible-rest-arg-context list)
4305 (if context
4306 `(%rest-ref ,n ,list ,context ,count t)
4307 (bug "no &REST context for FAST-REST-NTH"))))
4309 (define-source-transform elt (seq n)
4310 (if (policy *lexenv* (= safety 3))
4311 (values nil t)
4312 (multiple-value-bind (context count) (possible-rest-arg-context seq)
4313 (if context
4314 `(%rest-ref ,n ,seq ,context ,count)
4315 (values nil t)))))
4317 ;;; CAxR -> %REST-REF
4318 (defun source-transform-car (list nth)
4319 (multiple-value-bind (context count) (possible-rest-arg-context list)
4320 (if context
4321 `(%rest-ref ,nth ,list ,context ,count)
4322 (values nil t))))
4324 (define-source-transform car (list)
4325 (source-transform-car list 0))
4327 (define-source-transform cadr (list)
4328 (or (source-transform-car list 1)
4329 `(car (cdr ,list))))
4331 (define-source-transform caddr (list)
4332 (or (source-transform-car list 2)
4333 `(car (cdr (cdr ,list)))))
4335 (define-source-transform cadddr (list)
4336 (or (source-transform-car list 3)
4337 `(car (cdr (cdr (cdr ,list))))))
4339 ;;; LENGTH -> %REST-LENGTH
4340 (defun source-transform-length (list)
4341 (multiple-value-bind (context count) (possible-rest-arg-context list)
4342 (if context
4343 `(%rest-length ,list ,context ,count)
4344 (values nil t))))
4345 (define-source-transform length (list) (source-transform-length list))
4346 (define-source-transform list-length (list) (source-transform-length list))
4348 ;;; ENDP, NULL and NOT -> %REST-NULL
4350 ;;; Outside &REST convert into an IF so that IF optimizations will eliminate
4351 ;;; redundant negations.
4352 (defun source-transform-null (x op)
4353 (multiple-value-bind (context count) (possible-rest-arg-context x)
4354 (cond (context
4355 `(%rest-null ',op ,x ,context ,count))
4356 ((eq 'endp op)
4357 `(if (the list ,x) nil t))
4359 `(if ,x nil t)))))
4360 (define-source-transform not (x) (source-transform-null x 'not))
4361 (define-source-transform null (x) (source-transform-null x 'null))
4362 (define-source-transform endp (x) (source-transform-null x 'endp))
4364 (deftransform %rest-values ((list context count))
4365 (if (rest-var-more-context-ok list)
4366 `(%more-arg-values context 0 count)
4367 `(values-list list)))
4369 (deftransform %rest-ref ((n list context count &optional length-checked-p))
4370 (cond ((rest-var-more-context-ok list)
4371 (if (and (constant-lvar-p length-checked-p)
4372 (lvar-value length-checked-p))
4373 `(%more-arg context n)
4374 `(and (< (the index n) count) (%more-arg context n))))
4375 ((and (constant-lvar-p n) (zerop (lvar-value n)))
4376 `(car list))
4378 `(nth n list))))
4380 (deftransform %rest-length ((list context count))
4381 (if (rest-var-more-context-ok list)
4382 'count
4383 `(length list)))
4385 (deftransform %rest-null ((op list context count))
4386 (aver (constant-lvar-p op))
4387 (if (rest-var-more-context-ok list)
4388 `(eql 0 count)
4389 `(,(lvar-value op) list)))
4391 (deftransform %rest-true ((list context count))
4392 (if (rest-var-more-context-ok list)
4393 `(not (eql 0 count))
4394 `list))
4396 ;;;; transforming FORMAT
4397 ;;;;
4398 ;;;; If the control string is a compile-time constant, then replace it
4399 ;;;; with a use of the FORMATTER macro so that the control string is
4400 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
4401 ;;;; or T and the control string is a function (i.e. FORMATTER), then
4402 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
4404 ;;; for compile-time argument count checking.
4406 ;;; FIXME II: In some cases, type information could be correlated; for
4407 ;;; instance, ~{ ... ~} requires a list argument, so if the lvar-type
4408 ;;; of a corresponding argument is known and does not intersect the
4409 ;;; list type, a warning could be signalled.
4410 (defun check-format-args (string args fun)
4411 (declare (type string string))
4412 (unless (typep string 'simple-string)
4413 (setq string (coerce string 'simple-string)))
4414 (multiple-value-bind (min max)
4415 (handler-case (sb!format:%compiler-walk-format-string string args)
4416 (sb!format:format-error (c)
4417 (compiler-warn "~A" c)))
4418 (when min
4419 (let ((nargs (length args)))
4420 (cond
4421 ((< nargs min)
4422 (warn 'format-too-few-args-warning
4423 :format-control
4424 "Too few arguments (~D) to ~S ~S: requires at least ~D."
4425 :format-arguments (list nargs fun string min)))
4426 ((> nargs max)
4427 (warn 'format-too-many-args-warning
4428 :format-control
4429 "Too many arguments (~D) to ~S ~S: uses at most ~D."
4430 :format-arguments (list nargs fun string max))))))))
4432 (defoptimizer (format optimizer) ((dest control &rest args) node)
4433 (declare (ignore dest))
4434 (when (constant-lvar-p control)
4435 (let ((x (lvar-value control)))
4436 (when (stringp x)
4437 (let ((*compiler-error-context* node))
4438 (check-format-args x args 'format))))))
4440 (defoptimizer (format derive-type) ((dest control &rest args))
4441 (declare (ignore control args))
4442 (when (and (constant-lvar-p dest)
4443 (null (lvar-value dest)))
4444 (specifier-type '(simple-array character (*)))))
4446 ;;; We disable this transform in the cross-compiler to save memory in
4447 ;;; the target image; most of the uses of FORMAT in the compiler are for
4448 ;;; error messages, and those don't need to be particularly fast.
4449 #+sb-xc
4450 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
4451 :policy (>= speed space))
4452 (unless (constant-lvar-p control)
4453 (give-up-ir1-transform "The control string is not a constant."))
4454 (let* ((argc (length args))
4455 (arg-names (make-gensym-list argc))
4456 (control (lvar-value control))
4457 ;; Expanding the control string now avoids deferring to FORMATTER
4458 ;; so that we don't need an internal-only variant of it that
4459 ;; passes through extra args to %FORMATTER.
4460 (expr (handler-case ; in case %formatter wants to signal an error
4461 (sb!format::%formatter control argc nil)
4462 ;; otherwise, let the macro complain
4463 (sb!format:format-error (c)
4464 (if (string= (sb!format::format-error-complaint c)
4465 "no package named ~S")
4466 ;; "~/apackage:afun/" might become legal later.
4467 ;; To put it in perspective, "~/f" (no closing slash)
4468 ;; *will* be a runtime error, but this only *might* be
4469 ;; a runtime error, so we can't signal a full warning.
4470 ;; At absolute worst it should be a style-warning.
4471 (give-up-ir1-transform "~~// directive mentions unknown package")
4472 `(formatter ,control))))))
4473 `(lambda (dest control ,@arg-names)
4474 (declare (ignore control))
4475 (format dest ,expr ,@arg-names))))
4477 (deftransform format ((stream control &rest args) (stream function &rest t))
4478 (let ((arg-names (make-gensym-list (length args))))
4479 `(lambda (stream control ,@arg-names)
4480 (funcall control stream ,@arg-names)
4481 nil)))
4483 (deftransform format ((tee control &rest args) ((member t) function &rest t))
4484 (let ((arg-names (make-gensym-list (length args))))
4485 `(lambda (tee control ,@arg-names)
4486 (declare (ignore tee))
4487 (funcall control *standard-output* ,@arg-names)
4488 nil)))
4490 (deftransform format ((stream control &rest args) (null function &rest t))
4491 (let ((arg-names (make-gensym-list (length args))))
4492 `(lambda (stream control ,@arg-names)
4493 (declare (ignore stream))
4494 (with-simple-output-to-string (stream)
4495 (funcall control stream ,@arg-names)))))
4497 (defun concatenate-format-p (control args)
4498 (and
4499 (loop for directive in control
4500 always
4501 (or (stringp directive)
4502 (and (sb!format::format-directive-p directive)
4503 (let ((char (sb!format::format-directive-character directive))
4504 (params (sb!format::format-directive-params directive)))
4506 (and
4507 (char-equal char #\a)
4508 (null params)
4509 (pop args))
4510 (and
4511 (or (eql char #\~)
4512 (eql char #\%))
4513 (null (sb!format::format-directive-colonp directive))
4514 (null (sb!format::format-directive-atsignp directive))
4515 (or (null params)
4516 (typep params
4517 '(cons (cons (eql 1) unsigned-byte) null)))))))))
4518 (null args)))
4520 (deftransform format ((stream control &rest args) (null (constant-arg string) &rest string))
4521 (let ((tokenized
4522 (handler-case
4523 (sb!format::tokenize-control-string (lvar-value control))
4524 (sb!format:format-error ()
4525 (give-up-ir1-transform)))))
4526 (unless (concatenate-format-p tokenized args)
4527 (give-up-ir1-transform))
4528 (let ((arg-names (make-gensym-list (length args))))
4529 `(lambda (stream control ,@arg-names)
4530 (declare (ignore stream control)
4531 (ignorable ,@arg-names))
4532 (concatenate
4533 'string
4534 ,@(let ((strings
4535 (loop for directive in tokenized
4536 for char = (and (not (stringp directive))
4537 (sb!format::format-directive-character directive))
4538 when
4539 (cond ((not char)
4540 directive)
4541 ((char-equal char #\a)
4542 (let ((arg (pop args))
4543 (arg-name (pop arg-names)))
4545 (constant-lvar-p arg)
4546 (lvar-value arg)
4547 arg-name)))
4549 (let ((n (or (cdar (sb!format::format-directive-params directive))
4550 1)))
4551 (and (plusp n)
4552 (make-string n
4553 :initial-element
4554 (if (eql char #\%)
4555 #\Newline
4556 char))))))
4557 collect it)))
4558 ;; Join adjacent constant strings
4559 (loop with concat
4560 for (string . rest) on strings
4561 when (stringp string)
4562 do (setf concat
4563 (if concat
4564 (concatenate 'string concat string)
4565 string))
4566 else
4567 when concat collect (shiftf concat nil) end
4568 and collect string
4569 when (and concat (not rest))
4570 collect concat)))))))
4572 (deftransform pathname ((pathspec) (pathname) *)
4573 'pathspec)
4575 (deftransform pathname ((pathspec) (string) *)
4576 '(values (parse-namestring pathspec)))
4578 (macrolet
4579 ((def (name)
4580 `(defoptimizer (,name optimizer) ((control &rest args) node)
4581 (when (constant-lvar-p control)
4582 (let ((x (lvar-value control)))
4583 (when (stringp x)
4584 (let ((*compiler-error-context* node))
4585 (check-format-args x args ',name))))))))
4586 (def error)
4587 (def warn)
4588 #+sb-xc-host ; Only we should be using these
4589 (progn
4590 (def style-warn)
4591 (def compiler-error)
4592 (def compiler-warn)
4593 (def compiler-style-warn)
4594 (def compiler-notify)
4595 (def maybe-compiler-notify)
4596 (def bug)))
4598 (defoptimizer (cerror optimizer) ((report control &rest args))
4599 (when (and (constant-lvar-p control)
4600 (constant-lvar-p report))
4601 (let ((x (lvar-value control))
4602 (y (lvar-value report)))
4603 (when (and (stringp x) (stringp y))
4604 (multiple-value-bind (min1 max1)
4605 (handler-case
4606 (sb!format:%compiler-walk-format-string x args)
4607 (sb!format:format-error (c)
4608 (compiler-warn "~A" c)))
4609 (when min1
4610 (multiple-value-bind (min2 max2)
4611 (handler-case
4612 (sb!format:%compiler-walk-format-string y args)
4613 (sb!format:format-error (c)
4614 (compiler-warn "~A" c)))
4615 (when min2
4616 (let ((nargs (length args)))
4617 (cond
4618 ((< nargs (min min1 min2))
4619 (warn 'format-too-few-args-warning
4620 :format-control
4621 "Too few arguments (~D) to ~S ~S ~S: ~
4622 requires at least ~D."
4623 :format-arguments
4624 (list nargs 'cerror y x (min min1 min2))))
4625 ((> nargs (max max1 max2))
4626 (warn 'format-too-many-args-warning
4627 :format-control
4628 "Too many arguments (~D) to ~S ~S ~S: ~
4629 uses at most ~D."
4630 :format-arguments
4631 (list nargs 'cerror y x (max max1 max2))))))))))))))
4633 (defun constant-cons-type (type)
4634 (multiple-value-bind (singleton value)
4635 (type-singleton-p type)
4636 (if singleton
4637 (values value t)
4638 (typecase type
4639 (cons-type
4640 (multiple-value-bind (car car-good)
4641 (constant-cons-type (cons-type-car-type type))
4642 (multiple-value-bind (cdr cdr-good)
4643 (constant-cons-type (cons-type-cdr-type type))
4644 (and car-good cdr-good
4645 (values (cons car cdr) t)))))))))
4647 (defoptimizer (coerce derive-type) ((value type) node)
4648 (multiple-value-bind (type constant)
4649 (if (constant-lvar-p type)
4650 (values (lvar-value type) t)
4651 (constant-cons-type (lvar-type type)))
4652 (when constant
4653 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
4654 ;; but dealing with the niggle that complex canonicalization gets
4655 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
4656 ;; type COMPLEX.
4657 (let ((result-typeoid (careful-specifier-type type)))
4658 (cond
4659 ((null result-typeoid) nil)
4660 ((csubtypep result-typeoid (specifier-type 'number))
4661 ;; the difficult case: we have to cope with ANSI 12.1.5.3
4662 ;; Rule of Canonical Representation for Complex Rationals,
4663 ;; which is a truly nasty delivery to field.
4664 (cond
4665 ((csubtypep result-typeoid (specifier-type 'real))
4666 ;; cleverness required here: it would be nice to deduce
4667 ;; that something of type (INTEGER 2 3) coerced to type
4668 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
4669 ;; FLOAT gets its own clause because it's implemented as
4670 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
4671 ;; logic below.
4672 result-typeoid)
4673 ((and (numeric-type-p result-typeoid)
4674 (eq (numeric-type-complexp result-typeoid) :real))
4675 ;; FIXME: is this clause (a) necessary or (b) useful?
4676 result-typeoid)
4677 ((or (csubtypep result-typeoid
4678 (specifier-type '(complex single-float)))
4679 (csubtypep result-typeoid
4680 (specifier-type '(complex double-float)))
4681 #!+long-float
4682 (csubtypep result-typeoid
4683 (specifier-type '(complex long-float))))
4684 ;; float complex types are never canonicalized.
4685 result-typeoid)
4687 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
4688 ;; probably just a COMPLEX or equivalent. So, in that
4689 ;; case, we will return a complex or an object of the
4690 ;; provided type if it's rational:
4691 (type-union result-typeoid
4692 (type-intersection (lvar-type value)
4693 (specifier-type 'rational))))))
4694 ((and (policy node (zerop safety))
4695 (csubtypep result-typeoid (specifier-type '(array * (*)))))
4696 ;; At zero safety the deftransform for COERCE can elide dimension
4697 ;; checks for the things like (COERCE X '(SIMPLE-VECTOR 5)) -- so we
4698 ;; need to simplify the type to drop the dimension information.
4699 (let ((vtype (simplify-vector-type result-typeoid)))
4700 (if vtype
4701 (specifier-type vtype)
4702 result-typeoid)))
4704 result-typeoid))))))
4706 (defoptimizer (compile derive-type) ((nameoid function))
4707 (declare (ignore function))
4708 (when (csubtypep (lvar-type nameoid)
4709 (specifier-type 'null))
4710 (values-specifier-type '(values function boolean boolean))))
4712 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
4713 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
4714 ;;; optimizer, above).
4715 (defoptimizer (array-element-type derive-type) ((array))
4716 (let ((array-type (lvar-type array)))
4717 (labels ((consify (list)
4718 (if (endp list)
4719 '(eql nil)
4720 `(cons (eql ,(car list)) ,(consify (rest list)))))
4721 (get-element-type (a)
4722 (let ((element-type
4723 (type-specifier (array-type-specialized-element-type a))))
4724 (cond ((eq element-type '*)
4725 (specifier-type 'type-specifier))
4726 ((symbolp element-type)
4727 (make-eql-type element-type))
4728 ((consp element-type)
4729 (specifier-type (consify element-type)))
4731 (error "can't understand type ~S~%" element-type))))))
4732 (labels ((recurse (type)
4733 (cond ((array-type-p type)
4734 (get-element-type type))
4735 ((union-type-p type)
4736 (apply #'type-union
4737 (mapcar #'recurse (union-type-types type))))
4739 *universal-type*))))
4740 (recurse array-type)))))
4742 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
4743 ;; Like CMU CL, we use HEAPSORT. However, other than that, this code
4744 ;; isn't really related to the CMU CL code, since instead of trying
4745 ;; to generalize the CMU CL code to allow START and END values, this
4746 ;; code has been written from scratch following Chapter 7 of
4747 ;; _Introduction to Algorithms_ by Corman, Rivest, and Shamir.
4748 `(macrolet ((%index (x) `(truly-the index ,x))
4749 (%parent (i) `(ash ,i -1))
4750 (%left (i) `(%index (ash ,i 1)))
4751 (%right (i) `(%index (1+ (ash ,i 1))))
4752 (%heapify (i)
4753 `(do* ((i ,i)
4754 (left (%left i) (%left i)))
4755 ((> left current-heap-size))
4756 (declare (type index i left))
4757 (let* ((i-elt (%elt i))
4758 (i-key (funcall keyfun i-elt))
4759 (left-elt (%elt left))
4760 (left-key (funcall keyfun left-elt)))
4761 (multiple-value-bind (large large-elt large-key)
4762 (if (funcall ,',predicate i-key left-key)
4763 (values left left-elt left-key)
4764 (values i i-elt i-key))
4765 (let ((right (%right i)))
4766 (multiple-value-bind (largest largest-elt)
4767 (if (> right current-heap-size)
4768 (values large large-elt)
4769 (let* ((right-elt (%elt right))
4770 (right-key (funcall keyfun right-elt)))
4771 (if (funcall ,',predicate large-key right-key)
4772 (values right right-elt)
4773 (values large large-elt))))
4774 (cond ((= largest i)
4775 (return))
4777 (setf (%elt i) largest-elt
4778 (%elt largest) i-elt
4779 i largest)))))))))
4780 (%sort-vector (keyfun &optional (vtype 'vector))
4781 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had
4782 ;; trouble getting type inference to
4783 ;; propagate all the way through this
4784 ;; tangled mess of inlining. The TRULY-THE
4785 ;; here works around that. -- WHN
4786 (%elt (i)
4787 `(aref (truly-the ,',vtype ,',',vector)
4788 (%index (+ (%index ,i) start-1)))))
4789 (let (;; Heaps prefer 1-based addressing.
4790 (start-1 (1- ,',start))
4791 (current-heap-size (- ,',end ,',start))
4792 (keyfun ,keyfun))
4793 (declare (type (integer -1 #.(1- sb!xc:most-positive-fixnum))
4794 start-1))
4795 (declare (type index current-heap-size))
4796 (declare (type function keyfun))
4797 (loop for i of-type index
4798 from (ash current-heap-size -1) downto 1 do
4799 (%heapify i))
4800 (loop
4801 (when (< current-heap-size 2)
4802 (return))
4803 (rotatef (%elt 1) (%elt current-heap-size))
4804 (decf current-heap-size)
4805 (%heapify 1))))))
4806 (if (typep ,vector 'simple-vector)
4807 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
4808 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
4809 (if (null ,key)
4810 ;; Special-casing the KEY=NIL case lets us avoid some
4811 ;; function calls.
4812 (%sort-vector #'identity simple-vector)
4813 (%sort-vector ,key simple-vector))
4814 ;; It's hard to anticipate many speed-critical applications for
4815 ;; sorting vector types other than (VECTOR T), so we just lump
4816 ;; them all together in one slow dynamically typed mess.
4817 (locally
4818 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
4819 (%sort-vector (or ,key #'identity))))))
4821 (deftransform sort ((list predicate &key key)
4822 (list * &rest t) *)
4823 `(sb!impl::stable-sort-list list
4824 (%coerce-callable-to-fun predicate)
4825 (if key (%coerce-callable-to-fun key) #'identity)))
4827 (deftransform stable-sort ((sequence predicate &key key)
4828 ((or vector list) *))
4829 (let ((sequence-type (lvar-type sequence)))
4830 (cond ((csubtypep sequence-type (specifier-type 'list))
4831 `(sb!impl::stable-sort-list sequence
4832 (%coerce-callable-to-fun predicate)
4833 (if key (%coerce-callable-to-fun key) #'identity)))
4834 ((csubtypep sequence-type (specifier-type 'simple-vector))
4835 `(sb!impl::stable-sort-simple-vector sequence
4836 (%coerce-callable-to-fun predicate)
4837 (and key (%coerce-callable-to-fun key))))
4839 `(sb!impl::stable-sort-vector sequence
4840 (%coerce-callable-to-fun predicate)
4841 (and key (%coerce-callable-to-fun key)))))))
4843 ;;;; debuggers' little helpers
4845 ;;; for debugging when transforms are behaving mysteriously,
4846 ;;; e.g. when debugging a problem with an ASH transform
4847 ;;; (defun foo (&optional s)
4848 ;;; (sb-c::/report-lvar s "S outside WHEN")
4849 ;;; (when (and (integerp s) (> s 3))
4850 ;;; (sb-c::/report-lvar s "S inside WHEN")
4851 ;;; (let ((bound (ash 1 (1- s))))
4852 ;;; (sb-c::/report-lvar bound "BOUND")
4853 ;;; (let ((x (- bound))
4854 ;;; (y (1- bound)))
4855 ;;; (sb-c::/report-lvar x "X")
4856 ;;; (sb-c::/report-lvar x "Y"))
4857 ;;; `(integer ,(- bound) ,(1- bound)))))
4858 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
4859 ;;; and the function doesn't do anything at all.)
4860 #!+sb-show
4861 (progn
4862 (defknown /report-lvar (t t) null)
4863 (deftransform /report-lvar ((x message) (t t))
4864 (format t "~%/in /REPORT-LVAR~%")
4865 (format t "/(LVAR-TYPE X)=~S~%" (lvar-type x))
4866 (when (constant-lvar-p x)
4867 (format t "/(LVAR-VALUE X)=~S~%" (lvar-value x)))
4868 (format t "/MESSAGE=~S~%" (lvar-value message))
4869 (give-up-ir1-transform "not a real transform"))
4870 (defun /report-lvar (x message)
4871 (declare (ignore x message))))
4873 (deftransform encode-universal-time
4874 ((second minute hour date month year &optional time-zone)
4875 ((constant-arg (mod 60)) (constant-arg (mod 60))
4876 (constant-arg (mod 24))
4877 (constant-arg (integer 1 31))
4878 (constant-arg (integer 1 12))
4879 (constant-arg (integer 1899))
4880 (constant-arg (rational -24 24))))
4881 (let ((second (lvar-value second))
4882 (minute (lvar-value minute))
4883 (hour (lvar-value hour))
4884 (date (lvar-value date))
4885 (month (lvar-value month))
4886 (year (lvar-value year))
4887 (time-zone (lvar-value time-zone)))
4888 (if (zerop (rem time-zone 1/3600))
4889 (encode-universal-time second minute hour date month year time-zone)
4890 (give-up-ir1-transform))))
4892 #!-(and win32 (not sb-thread))
4893 (deftransform sleep ((seconds) ((integer 0 #.(expt 10 8))))
4894 `(sb!unix:nanosleep seconds 0))
4896 #!-(and win32 (not sb-thread))
4897 (deftransform sleep ((seconds) ((constant-arg (real 0))))
4898 (let ((seconds-value (lvar-value seconds)))
4899 (multiple-value-bind (seconds nano)
4900 (sb!impl::split-seconds-for-sleep seconds-value)
4901 (if (> seconds (expt 10 8))
4902 (give-up-ir1-transform)
4903 `(sb!unix:nanosleep ,seconds ,nano)))))
4905 ;; On 64-bit architectures the TLS index is in the symbol header,
4906 ;; !DEFINE-PRIMITIVE-OBJECT doesn't define an accessor for it.
4907 ;; In the architectures where tls-index is an ordinary slot holding a tagged
4908 ;; object, it represents the byte offset to an aligned object and looks
4909 ;; in Lisp like a fixnum that is off by a factor of (EXPT 2 N-FIXNUM-TAG-BITS).
4910 ;; We're reading with a raw SAP accessor, so must make it look equally "off".
4911 ;; Also we don't get the defknown automatically.
4912 #!+(and 64-bit sb-thread)
4913 (defknown symbol-tls-index (t) fixnum (flushable))
4914 #!+(and 64-bit sb-thread)
4915 (define-source-transform symbol-tls-index (sym)
4916 `(ash (sap-ref-32 (int-sap (get-lisp-obj-address (the symbol ,sym)))
4917 (- 4 sb!vm:other-pointer-lowtag))
4918 (- sb!vm:n-fixnum-tag-bits)))