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