x86-64: LEA with neither disp nor index is MOV
[sbcl.git] / src / compiler / srctran.lisp
blob50928c32abad5e8bef2a96285ac5f76c9c6ae927
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))
2638 "Convert ASH of signed word to %ASH/RIGHT"
2639 (unless (and (csubtypep (lvar-type integer) ; do that ourselves to avoid
2640 (specifier-type 'sb!vm:signed-word)) ; optimization
2641 (csubtypep (lvar-type amount) ; notes.
2642 (specifier-type '(integer * 0))))
2643 (give-up-ir1-transform))
2644 (when (constant-lvar-p amount)
2645 (give-up-ir1-transform))
2646 (let ((use (lvar-uses amount)))
2647 (cond ((and (combination-p use)
2648 (eql '%negate (lvar-fun-name (combination-fun use))))
2649 (splice-fun-args amount '%negate 1)
2650 `(lambda (integer amount)
2651 (declare (type unsigned-byte amount))
2652 (%ash/right integer (if (>= amount ,sb!vm:n-word-bits)
2653 ,(1- sb!vm:n-word-bits)
2654 amount))))
2656 `(%ash/right integer (if (<= amount ,(- sb!vm:n-word-bits))
2657 ,(1- sb!vm:n-word-bits)
2658 (- amount)))))))
2660 (deftransform ash ((integer amount))
2661 "Convert ASH of word to %ASH/RIGHT"
2662 (unless (and (csubtypep (lvar-type integer)
2663 (specifier-type 'sb!vm:word))
2664 (csubtypep (lvar-type amount)
2665 (specifier-type '(integer * 0))))
2666 (give-up-ir1-transform))
2667 (when (constant-lvar-p amount)
2668 (give-up-ir1-transform))
2669 (let ((use (lvar-uses amount)))
2670 (cond ((and (combination-p use)
2671 (eql '%negate (lvar-fun-name (combination-fun use))))
2672 (splice-fun-args amount '%negate 1)
2673 `(lambda (integer amount)
2674 (declare (type unsigned-byte amount))
2675 (if (>= amount ,sb!vm:n-word-bits)
2677 (%ash/right integer amount))))
2679 `(if (<= amount ,(- sb!vm:n-word-bits))
2681 (%ash/right integer (- amount)))))))
2683 (deftransform %ash/right ((integer amount) (integer (constant-arg unsigned-byte)))
2684 "Convert %ASH/RIGHT by constant back to ASH"
2685 `(ash integer ,(- (lvar-value amount))))
2687 (deftransform %ash/right ((integer amount) * * :node node)
2688 "strength reduce large variable right shift"
2689 (let ((return-type (single-value-type (node-derived-type node))))
2690 (cond ((type= return-type (specifier-type '(eql 0)))
2692 ((type= return-type (specifier-type '(eql -1)))
2694 ((csubtypep return-type (specifier-type '(member -1 0)))
2695 `(ash integer ,(- sb!vm:n-word-bits)))
2697 (give-up-ir1-transform)))))
2699 (defun %ash/right-derive-type-aux (n-type shift same-arg)
2700 (declare (ignore same-arg))
2701 (or (and (or (csubtypep n-type (specifier-type 'sb!vm:signed-word))
2702 (csubtypep n-type (specifier-type 'word)))
2703 (csubtypep shift (specifier-type `(mod ,sb!vm:n-word-bits)))
2704 (let ((n-low (numeric-type-low n-type))
2705 (n-high (numeric-type-high n-type))
2706 (s-low (numeric-type-low shift))
2707 (s-high (numeric-type-high shift)))
2708 (make-numeric-type :class 'integer :complexp :real
2709 :low (when n-low
2710 (if (minusp n-low)
2711 (ash n-low (- s-low))
2712 (ash n-low (- s-high))))
2713 :high (when n-high
2714 (if (minusp n-high)
2715 (ash n-high (- s-high))
2716 (ash n-high (- s-low)))))))
2717 *universal-type*))
2719 (defoptimizer (%ash/right derive-type) ((n shift))
2720 (two-arg-derive-type n shift #'%ash/right-derive-type-aux #'%ash/right))
2723 ;;; Not declaring it as actually being RATIO becuase it is used as one
2724 ;;; of the legs in the EXPT transform below and that may result in
2725 ;;; some unwanted type conflicts, e.g. (random (expt 2 (the integer y)))
2726 (declaim (type (sfunction (integer) rational) reciprocate))
2727 (defun reciprocate (x)
2728 (declare (optimize (safety 0)))
2729 #+sb-xc-host (error "Can't call reciprocate ~D" x)
2730 #-sb-xc-host (%make-ratio 1 x))
2732 (deftransform expt ((base power) ((constant-arg unsigned-byte) integer))
2733 (let ((base (lvar-value base)))
2734 (cond ((/= (logcount base) 1)
2735 (give-up-ir1-transform))
2736 ((= base 1)
2739 `(let ((%denominator (ash 1 ,(if (= base 2)
2740 `(abs power)
2741 `(* (abs power) ,(1- (integer-length base)))))))
2742 (if (minusp power)
2743 (reciprocate %denominator)
2744 %denominator))))))
2746 (deftransform expt ((base power) ((constant-arg unsigned-byte) unsigned-byte))
2747 (let ((base (lvar-value base)))
2748 (unless (= (logcount base) 1)
2749 (give-up-ir1-transform))
2750 `(ash 1 ,(if (= base 2)
2751 `power
2752 `(* power ,(1- (integer-length base)))))))
2754 ;;; Modular functions
2756 ;;; (ldb (byte s 0) (foo x y ...)) =
2757 ;;; (ldb (byte s 0) (foo (ldb (byte s 0) x) y ...))
2759 ;;; and similar for other arguments.
2761 (defun make-modular-fun-type-deriver (prototype kind width signedp)
2762 (declare (ignore kind))
2763 #!-sb-fluid
2764 (binding* ((info (info :function :info prototype) :exit-if-null)
2765 (fun (fun-info-derive-type info) :exit-if-null)
2766 (mask-type (specifier-type
2767 (ecase signedp
2768 ((nil) (let ((mask (1- (ash 1 width))))
2769 `(integer ,mask ,mask)))
2770 ((t) `(signed-byte ,width))))))
2771 (lambda (call)
2772 (let ((res (funcall fun call)))
2773 (when res
2774 (if (eq signedp nil)
2775 (logand-derive-type-aux res mask-type))))))
2776 #!+sb-fluid
2777 (lambda (call)
2778 (binding* ((info (info :function :info prototype) :exit-if-null)
2779 (fun (fun-info-derive-type info) :exit-if-null)
2780 (res (funcall fun call) :exit-if-null)
2781 (mask-type (specifier-type
2782 (ecase signedp
2783 ((nil) (let ((mask (1- (ash 1 width))))
2784 `(integer ,mask ,mask)))
2785 ((t) `(signed-byte ,width))))))
2786 (if (eq signedp nil)
2787 (logand-derive-type-aux res mask-type)))))
2789 ;;; Try to recursively cut all uses of LVAR to WIDTH bits.
2791 ;;; For good functions, we just recursively cut arguments; their
2792 ;;; "goodness" means that the result will not increase (in the
2793 ;;; (unsigned-byte +infinity) sense). An ordinary modular function is
2794 ;;; replaced with the version, cutting its result to WIDTH or more
2795 ;;; bits. For most functions (e.g. for +) we cut all arguments; for
2796 ;;; others (e.g. for ASH) we have "optimizers", cutting only necessary
2797 ;;; arguments (maybe to a different width) and returning the name of a
2798 ;;; modular version, if it exists, or NIL. If we have changed
2799 ;;; anything, we need to flush old derived types, because they have
2800 ;;; nothing in common with the new code.
2801 (defun cut-to-width (lvar kind width signedp)
2802 (declare (type lvar lvar) (type (integer 0) width))
2803 (let ((type (specifier-type (if (zerop width)
2804 '(eql 0)
2805 `(,(ecase signedp
2806 ((nil) 'unsigned-byte)
2807 ((t) 'signed-byte))
2808 ,width)))))
2809 (labels ((reoptimize-node (node name)
2810 (setf (node-derived-type node)
2811 (fun-type-returns
2812 (proclaimed-ftype name)))
2813 (setf (lvar-%derived-type (node-lvar node)) nil)
2814 (setf (node-reoptimize node) t)
2815 (setf (block-reoptimize (node-block node)) t)
2816 (reoptimize-component (node-component node) :maybe))
2817 (insert-lvar-cut (lvar)
2818 "Insert a LOGAND/MASK-SIGNED-FIELD to cut the value of LVAR
2819 to the required bit width. Returns T if any change was made.
2821 When the destination of LVAR will definitely cut LVAR's value
2822 to width (i.e. it's a logand or mask-signed-field with constant
2823 other argument), do nothing. Otherwise, splice LOGAND/M-S-F in."
2824 (binding* ((dest (lvar-dest lvar) :exit-if-null)
2825 (nil (combination-p dest) :exit-if-null)
2826 (name (lvar-fun-name (combination-fun dest) t))
2827 (args (combination-args dest)))
2828 (case name
2829 (logand
2830 (when (= 2 (length args))
2831 (let ((other (if (eql (first args) lvar)
2832 (second args)
2833 (first args))))
2834 (when (and (constant-lvar-p other)
2835 (ctypep (lvar-value other) type)
2836 (not signedp))
2837 (return-from insert-lvar-cut)))))
2838 (mask-signed-field
2839 (when (and signedp
2840 (eql lvar (second args))
2841 (constant-lvar-p (first args))
2842 (<= (lvar-value (first args)) width))
2843 (return-from insert-lvar-cut)))))
2844 (filter-lvar lvar
2845 (if signedp
2846 `(mask-signed-field ,width 'dummy)
2847 `(logand 'dummy ,(ldb (byte width 0) -1))))
2848 (do-uses (node lvar)
2849 (setf (block-reoptimize (node-block node)) t)
2850 (reoptimize-component (node-component node) :maybe))
2852 (cut-node (node)
2853 "Try to cut a node to width. The primary return value is
2854 whether we managed to cut (cleverly), and the second whether
2855 anything was changed. The third return value tells whether
2856 the cut value might be wider than expected."
2857 (when (block-delete-p (node-block node))
2858 (return-from cut-node (values t nil)))
2859 (typecase node
2860 (ref
2861 (typecase (ref-leaf node)
2862 (constant
2863 (let* ((constant-value (constant-value (ref-leaf node)))
2864 (new-value
2865 (cond ((not (integerp constant-value))
2866 (return-from cut-node (values t nil)))
2867 (signedp
2868 (mask-signed-field width constant-value))
2870 (ldb (byte width 0) constant-value)))))
2871 (cond ((= constant-value new-value)
2872 (values t nil)) ; we knew what to do and did nothing
2874 (change-ref-leaf node (make-constant new-value)
2875 :recklessly t)
2876 (let ((lvar (node-lvar node)))
2877 (setf (lvar-%derived-type lvar)
2878 (and (lvar-has-single-use-p lvar)
2879 (make-values-type :required (list (ctype-of new-value))))))
2880 (setf (block-reoptimize (node-block node)) t)
2881 (reoptimize-component (node-component node) :maybe)
2882 (values t t)))))))
2883 (combination
2884 (when (eq (basic-combination-kind node) :known)
2885 (let* ((fun-ref (lvar-use (combination-fun node)))
2886 (fun-name (lvar-fun-name (combination-fun node)))
2887 (modular-fun (find-modular-version fun-name kind
2888 signedp width)))
2889 (cond ((not modular-fun)
2890 ;; don't know what to do here
2891 (values nil nil))
2892 ((let ((dtype (single-value-type
2893 (node-derived-type node))))
2894 (and
2895 (case fun-name
2896 (logand
2897 (csubtypep dtype
2898 (specifier-type 'unsigned-byte)))
2899 (logior
2900 (csubtypep dtype
2901 (specifier-type '(integer * 0))))
2902 (mask-signed-field
2904 (t nil))
2905 (csubtypep dtype type)))
2906 ;; nothing to do
2907 (values t nil))
2909 (binding* ((name (etypecase modular-fun
2910 ((eql :good) fun-name)
2911 (modular-fun-info
2912 (modular-fun-info-name modular-fun))
2913 (function
2914 (funcall modular-fun node width)))
2915 :exit-if-null)
2916 (did-something nil)
2917 (over-wide nil))
2918 (unless (eql modular-fun :good)
2919 (setq did-something t
2920 over-wide t)
2921 (change-ref-leaf
2922 fun-ref
2923 (find-free-fun name "in a strange place"))
2924 (setf (combination-kind node) :full))
2925 (unless (functionp modular-fun)
2926 (dolist (arg (basic-combination-args node))
2927 (multiple-value-bind (change wide)
2928 (cut-lvar arg)
2929 (setf did-something (or did-something change)
2930 over-wide (or over-wide wide)))))
2931 (when did-something
2932 (reoptimize-node node name))
2933 (values t did-something over-wide)))))))))
2934 (cut-lvar (lvar &key head
2935 &aux did-something must-insert over-wide)
2936 "Cut all the LVAR's use nodes. If any of them wasn't handled
2937 and its type is too wide for the operation we wish to perform
2938 insert an explicit bit-width narrowing operation (LOGAND or
2939 MASK-SIGNED-FIELD) between the LVAR (*) and its destination.
2940 The narrowing operation might not be inserted if the LVAR's
2941 destination is already such an operation, to avoid endless
2942 recursion.
2944 If we're at the head, forcibly insert a cut operation if the
2945 result might be too wide.
2947 (*) We can't easily do that for each node, and doing so might
2948 result in code bloat, anyway. (I'm also not sure it would be
2949 correct for complicated C/D FG)"
2950 (do-uses (node lvar)
2951 (multiple-value-bind (handled any-change wide)
2952 (cut-node node)
2953 (setf did-something (or did-something any-change)
2954 must-insert (or must-insert
2955 (not (or handled
2956 (csubtypep (single-value-type
2957 (node-derived-type node))
2958 type))))
2959 over-wide (or over-wide wide))))
2960 (when (or must-insert
2961 (and head over-wide))
2962 (setf did-something (or (insert-lvar-cut lvar) did-something)
2963 ;; we're just the right width after an explicit cut.
2964 over-wide nil))
2965 (values did-something over-wide)))
2966 (cut-lvar lvar :head t))))
2968 (defun best-modular-version (width signedp)
2969 ;; 1. exact width-matched :untagged
2970 ;; 2. >/>= width-matched :tagged
2971 ;; 3. >/>= width-matched :untagged
2972 (let* ((uuwidths (modular-class-widths *untagged-unsigned-modular-class*))
2973 (uswidths (modular-class-widths *untagged-signed-modular-class*))
2974 (uwidths (if (and uuwidths uswidths)
2975 (merge 'list (copy-list uuwidths) (copy-list uswidths)
2976 #'< :key #'car)
2977 (or uuwidths uswidths)))
2978 (twidths (modular-class-widths *tagged-modular-class*)))
2979 (let ((exact (find (cons width signedp) uwidths :test #'equal)))
2980 (when exact
2981 (return-from best-modular-version (values width :untagged signedp))))
2982 (flet ((inexact-match (w)
2983 (cond
2984 ((eq signedp (cdr w)) (<= width (car w)))
2985 ((eq signedp nil) (< width (car w))))))
2986 (let ((tgt (find-if #'inexact-match twidths)))
2987 (when tgt
2988 (return-from best-modular-version
2989 (values (car tgt) :tagged (cdr tgt)))))
2990 (let ((ugt (find-if #'inexact-match uwidths)))
2991 (when ugt
2992 (return-from best-modular-version
2993 (values (car ugt) :untagged (cdr ugt))))))))
2995 (defun integer-type-numeric-bounds (type)
2996 (typecase type
2997 ;; KLUDGE: this is not INTEGER-type-numeric-bounds
2998 (numeric-type (values (numeric-type-low type)
2999 (numeric-type-high type)))
3000 (union-type
3001 (let ((low nil)
3002 (high nil))
3003 (dolist (type (union-type-types type) (values low high))
3004 (unless (and (numeric-type-p type)
3005 (eql (numeric-type-class type) 'integer))
3006 (return (values nil nil)))
3007 (let ((this-low (numeric-type-low type))
3008 (this-high (numeric-type-high type)))
3009 (unless (and this-low this-high)
3010 (return (values nil nil)))
3011 (setf low (min this-low (or low this-low))
3012 high (max this-high (or high this-high)))))))))
3014 (defoptimizer (logand optimizer) ((x y) node)
3015 (let ((result-type (single-value-type (node-derived-type node))))
3016 (multiple-value-bind (low high)
3017 (integer-type-numeric-bounds result-type)
3018 (when (and (numberp low)
3019 (numberp high)
3020 (>= low 0))
3021 (let ((width (integer-length high)))
3022 (multiple-value-bind (w kind signedp)
3023 (best-modular-version width nil)
3024 (when w
3025 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND WIDTH SIGNEDP).
3027 ;; FIXME: I think the FIXME (which is from APD) above
3028 ;; implies that CUT-TO-WIDTH should do /everything/
3029 ;; that's required, including reoptimizing things
3030 ;; itself that it knows are necessary. At the moment,
3031 ;; CUT-TO-WIDTH sets up some new calls with
3032 ;; combination-type :FULL, which later get noticed as
3033 ;; known functions and properly converted.
3035 ;; We cut to W not WIDTH if SIGNEDP is true, because
3036 ;; signed constant replacement needs to know which bit
3037 ;; in the field is the signed bit.
3038 (let ((xact (cut-to-width x kind (if signedp w width) signedp))
3039 (yact (cut-to-width y kind (if signedp w width) signedp)))
3040 (declare (ignore xact yact))
3041 nil) ; After fixing above, replace with T, meaning
3042 ; "don't reoptimize this (LOGAND) node any more".
3043 )))))))
3045 (defoptimizer (mask-signed-field optimizer) ((width x) node)
3046 (declare (ignore width))
3047 (let ((result-type (single-value-type (node-derived-type node))))
3048 (multiple-value-bind (low high)
3049 (integer-type-numeric-bounds result-type)
3050 (when (and (numberp low) (numberp high))
3051 (let ((width (max (integer-length high) (integer-length low))))
3052 (multiple-value-bind (w kind)
3053 (best-modular-version (1+ width) t)
3054 (when w
3055 ;; FIXME: This should be (CUT-TO-WIDTH NODE KIND W T).
3056 ;; [ see comment above in LOGAND optimizer ]
3057 (cut-to-width x kind w t)
3058 nil ; After fixing above, replace with T.
3059 )))))))
3061 (defoptimizer (logior optimizer) ((x y) node)
3062 (let ((result-type (single-value-type (node-derived-type node))))
3063 (multiple-value-bind (low high)
3064 (integer-type-numeric-bounds result-type)
3065 (when (and (numberp low)
3066 (numberp high)
3067 (<= high 0))
3068 (let ((width (integer-length low)))
3069 (multiple-value-bind (w kind)
3070 (best-modular-version (1+ width) t)
3071 (when w
3072 ;; FIXME: see comment in LOGAND optimizer
3073 (let ((xact (cut-to-width x kind w t))
3074 (yact (cut-to-width y kind w t)))
3075 (declare (ignore xact yact))
3076 nil) ; After fixing above, replace with T
3077 )))))))
3079 ;;; Handle the case of a constant BOOLE-CODE.
3080 (deftransform boole ((op x y) * *)
3081 "convert to inline logical operations"
3082 (unless (constant-lvar-p op)
3083 (give-up-ir1-transform "BOOLE code is not a constant."))
3084 (let ((control (lvar-value op)))
3085 (case control
3086 (#.sb!xc:boole-clr 0)
3087 (#.sb!xc:boole-set -1)
3088 (#.sb!xc:boole-1 'x)
3089 (#.sb!xc:boole-2 'y)
3090 (#.sb!xc:boole-c1 '(lognot x))
3091 (#.sb!xc:boole-c2 '(lognot y))
3092 (#.sb!xc:boole-and '(logand x y))
3093 (#.sb!xc:boole-ior '(logior x y))
3094 (#.sb!xc:boole-xor '(logxor x y))
3095 (#.sb!xc:boole-eqv '(logeqv x y))
3096 (#.sb!xc:boole-nand '(lognand x y))
3097 (#.sb!xc:boole-nor '(lognor x y))
3098 (#.sb!xc:boole-andc1 '(logandc1 x y))
3099 (#.sb!xc:boole-andc2 '(logandc2 x y))
3100 (#.sb!xc:boole-orc1 '(logorc1 x y))
3101 (#.sb!xc:boole-orc2 '(logorc2 x y))
3103 (abort-ir1-transform "~S is an illegal control arg to BOOLE."
3104 control)))))
3106 ;;;; converting special case multiply/divide to shifts
3108 ;;; If arg is a constant power of two, turn * into a shift.
3109 (deftransform * ((x y) (integer integer) *)
3110 "convert x*2^k to shift"
3111 (unless (constant-lvar-p y)
3112 (give-up-ir1-transform))
3113 (let* ((y (lvar-value y))
3114 (y-abs (abs y))
3115 (len (1- (integer-length y-abs))))
3116 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3117 (give-up-ir1-transform))
3118 (if (minusp y)
3119 `(- (ash x ,len))
3120 `(ash x ,len))))
3122 ;;; These must come before the ones below, so that they are tried
3123 ;;; first.
3124 (deftransform floor ((number divisor))
3125 `(multiple-value-bind (tru rem) (truncate number divisor)
3126 (if (and (not (zerop rem))
3127 (if (minusp divisor)
3128 (plusp number)
3129 (minusp number)))
3130 (values (1- tru) (+ rem divisor))
3131 (values tru rem))))
3133 (deftransform ceiling ((number divisor))
3134 `(multiple-value-bind (tru rem) (truncate number divisor)
3135 (if (and (not (zerop rem))
3136 (if (minusp divisor)
3137 (minusp number)
3138 (plusp number)))
3139 (values (+ tru 1) (- rem divisor))
3140 (values tru rem))))
3142 (deftransform rem ((number divisor))
3143 `(nth-value 1 (truncate number divisor)))
3145 (deftransform mod ((number divisor))
3146 `(let ((rem (rem number divisor)))
3147 (if (and (not (zerop rem))
3148 (if (minusp divisor)
3149 (plusp number)
3150 (minusp number)))
3151 (+ rem divisor)
3152 rem)))
3154 ;;; If arg is a constant power of two, turn FLOOR into a shift and
3155 ;;; mask. If CEILING, add in (1- (ABS Y)), do FLOOR and correct a
3156 ;;; remainder.
3157 (flet ((frob (y ceil-p)
3158 (unless (constant-lvar-p y)
3159 (give-up-ir1-transform))
3160 (let* ((y (lvar-value y))
3161 (y-abs (abs y))
3162 (len (1- (integer-length y-abs))))
3163 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3164 (give-up-ir1-transform))
3165 (let ((shift (- len))
3166 (mask (1- y-abs))
3167 (delta (if ceil-p (* (signum y) (1- y-abs)) 0)))
3168 `(let ((x (+ x ,delta)))
3169 ,(if (minusp y)
3170 `(values (ash (- x) ,shift)
3171 (- (- (logand (- x) ,mask)) ,delta))
3172 `(values (ash x ,shift)
3173 (- (logand x ,mask) ,delta))))))))
3174 (deftransform floor ((x y) (integer integer) *)
3175 "convert division by 2^k to shift"
3176 (frob y nil))
3177 (deftransform ceiling ((x y) (integer integer) *)
3178 "convert division by 2^k to shift"
3179 (frob y t)))
3181 ;;; Do the same for MOD.
3182 (deftransform mod ((x y) (integer (constant-arg integer)) *)
3183 "convert remainder mod 2^k to LOGAND"
3184 (let* ((y (lvar-value y))
3185 (y-abs (abs y))
3186 (len (1- (integer-length y-abs))))
3187 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3188 (give-up-ir1-transform))
3189 (let ((mask (1- y-abs)))
3190 (if (minusp y)
3191 `(- (logand (- x) ,mask))
3192 `(logand x ,mask)))))
3194 ;;; If arg is a constant power of two, turn TRUNCATE into a shift and mask.
3195 (deftransform truncate ((x y) (integer (constant-arg integer)))
3196 "convert division by 2^k to shift"
3197 (let* ((y (lvar-value y))
3198 (y-abs (abs y))
3199 (len (1- (integer-length y-abs))))
3200 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3201 (give-up-ir1-transform))
3202 (let ((shift (- len))
3203 (mask (1- y-abs)))
3204 `(if (minusp x)
3205 (values ,(if (minusp y)
3206 `(ash (- x) ,shift)
3207 `(- (ash (- x) ,shift)))
3208 (- (logand (- x) ,mask)))
3209 (values ,(if (minusp y)
3210 `(- (ash x ,shift))
3211 `(ash x ,shift))
3212 (logand x ,mask))))))
3214 ;;; And the same for REM.
3215 (deftransform rem ((x y) (integer (constant-arg integer)) *)
3216 "convert remainder mod 2^k to LOGAND"
3217 (let* ((y (lvar-value y))
3218 (y-abs (abs y))
3219 (len (1- (integer-length y-abs))))
3220 (unless (and (> y-abs 0) (= y-abs (ash 1 len)))
3221 (give-up-ir1-transform))
3222 (let ((mask (1- y-abs)))
3223 `(if (minusp x)
3224 (- (logand (- x) ,mask))
3225 (logand x ,mask)))))
3227 ;;; Return an expression to calculate the integer quotient of X and
3228 ;;; constant Y, using multiplication, shift and add/sub instead of
3229 ;;; division. Both arguments must be unsigned, fit in a machine word and
3230 ;;; Y must neither be zero nor a power of two. The quotient is rounded
3231 ;;; towards zero.
3232 ;;; The algorithm is taken from the paper "Division by Invariant
3233 ;;; Integers using Multiplication", 1994 by Torbj\"{o}rn Granlund and
3234 ;;; Peter L. Montgomery, Figures 4.2 and 6.2, modified to exclude the
3235 ;;; case of division by powers of two.
3236 ;;; The algorithm includes an adaptive precision argument. Use it, since
3237 ;;; we often have sub-word value ranges. Careful, in this case, we need
3238 ;;; p s.t 2^p > n, not the ceiling of the binary log.
3239 ;;; Also, for some reason, the paper prefers shifting to masking. Mask
3240 ;;; instead. Masking is equivalent to shifting right, then left again;
3241 ;;; all the intermediate values are still words, so we just have to shift
3242 ;;; right a bit more to compensate, at the end.
3244 ;;; The following two examples show an average case and the worst case
3245 ;;; with respect to the complexity of the generated expression, under
3246 ;;; a word size of 64 bits:
3248 ;;; (UNSIGNED-DIV-TRANSFORMER 10 MOST-POSITIVE-WORD) ->
3249 ;;; (ASH (%MULTIPLY (LOGANDC2 X 0) 14757395258967641293) -3)
3251 ;;; (UNSIGNED-DIV-TRANSFORMER 7 MOST-POSITIVE-WORD) ->
3252 ;;; (LET* ((NUM X)
3253 ;;; (T1 (%MULTIPLY NUM 2635249153387078803)))
3254 ;;; (ASH (LDB (BYTE 64 0)
3255 ;;; (+ T1 (ASH (LDB (BYTE 64 0)
3256 ;;; (- NUM T1))
3257 ;;; -1)))
3258 ;;; -2))
3260 (defun gen-unsigned-div-by-constant-expr (y max-x)
3261 (declare (type (integer 3 #.most-positive-word) y)
3262 (type word max-x))
3263 (aver (not (zerop (logand y (1- y)))))
3264 (labels ((ld (x)
3265 ;; the floor of the binary logarithm of (positive) X
3266 (integer-length (1- x)))
3267 (choose-multiplier (y precision)
3268 (do* ((l (ld y))
3269 (shift l (1- shift))
3270 (expt-2-n+l (expt 2 (+ sb!vm:n-word-bits l)))
3271 (m-low (truncate expt-2-n+l y) (ash m-low -1))
3272 (m-high (truncate (+ expt-2-n+l
3273 (ash expt-2-n+l (- precision)))
3275 (ash m-high -1)))
3276 ((not (and (< (ash m-low -1) (ash m-high -1))
3277 (> shift 0)))
3278 (values m-high shift)))))
3279 (let ((n (expt 2 sb!vm:n-word-bits))
3280 (precision (integer-length max-x))
3281 (shift1 0))
3282 (multiple-value-bind (m shift2)
3283 (choose-multiplier y precision)
3284 (when (and (>= m n) (evenp y))
3285 (setq shift1 (ld (logand y (- y))))
3286 (multiple-value-setq (m shift2)
3287 (choose-multiplier (/ y (ash 1 shift1))
3288 (- precision shift1))))
3289 (cond ((>= m n)
3290 (flet ((word (x)
3291 `(truly-the word ,x)))
3292 `(let* ((num x)
3293 (t1 (%multiply-high num ,(- m n))))
3294 (ash ,(word `(+ t1 (ash ,(word `(- num t1))
3295 -1)))
3296 ,(- 1 shift2)))))
3297 ((and (zerop shift1) (zerop shift2))
3298 (let ((max (truncate max-x y)))
3299 ;; Explicit TRULY-THE needed to get the FIXNUM=>FIXNUM
3300 ;; VOP.
3301 `(truly-the (integer 0 ,max)
3302 (%multiply-high x ,m))))
3304 `(ash (%multiply-high (logandc2 x ,(1- (ash 1 shift1))) ,m)
3305 ,(- (+ shift1 shift2)))))))))
3307 #!-multiply-high-vops
3308 (define-source-transform %multiply-high (x y)
3309 `(values (sb!bignum:%multiply ,x ,y)))
3311 ;;; If the divisor is constant and both args are positive and fit in a
3312 ;;; machine word, replace the division by a multiplication and possibly
3313 ;;; some shifts and an addition. Calculate the remainder by a second
3314 ;;; multiplication and a subtraction. Dead code elimination will
3315 ;;; suppress the latter part if only the quotient is needed. If the type
3316 ;;; of the dividend allows to derive that the quotient will always have
3317 ;;; the same value, emit much simpler code to handle that. (This case
3318 ;;; may be rare but it's easy to detect and the compiler doesn't find
3319 ;;; this optimization on its own.)
3320 (deftransform truncate ((x y) (word (constant-arg word))
3322 :policy (and (> speed compilation-speed)
3323 (> speed space)))
3324 "convert integer division to multiplication"
3325 (let* ((y (lvar-value y))
3326 (x-type (lvar-type x))
3327 (max-x (or (and (numeric-type-p x-type)
3328 (numeric-type-high x-type))
3329 most-positive-word)))
3330 ;; Division by zero, one or powers of two is handled elsewhere.
3331 (when (zerop (logand y (1- y)))
3332 (give-up-ir1-transform))
3333 `(let* ((quot ,(gen-unsigned-div-by-constant-expr y max-x))
3334 (rem (ldb (byte #.sb!vm:n-word-bits 0)
3335 (- x (* quot ,y)))))
3336 (values quot rem))))
3338 ;;;; arithmetic and logical identity operation elimination
3340 ;;; Flush calls to various arith functions that convert to the
3341 ;;; identity function or a constant.
3342 (macrolet ((def (name identity result)
3343 `(deftransform ,name ((x y) (* (constant-arg (member ,identity))) *)
3344 "fold identity operations"
3345 ',result)))
3346 (def ash 0 x)
3347 (def logand -1 x)
3348 (def logand 0 0)
3349 (def logior 0 x)
3350 (def logior -1 -1)
3351 (def logxor -1 (lognot x))
3352 (def logxor 0 x))
3354 (defun least-zero-bit (x)
3355 (and (/= x -1)
3356 (1- (integer-length (logxor x (1+ x))))))
3358 (deftransform logand ((x y) (* (constant-arg t)) *)
3359 "fold identity operation"
3360 (let* ((y (lvar-value y))
3361 (width (or (least-zero-bit y) '*)))
3362 (unless (and (neq width 0) ; (logand x 0) handled elsewhere
3363 (csubtypep (lvar-type x)
3364 (specifier-type `(unsigned-byte ,width))))
3365 (give-up-ir1-transform))
3366 'x))
3368 (deftransform mask-signed-field ((size x) ((constant-arg t) *) *)
3369 "fold identity operation"
3370 (let ((size (lvar-value size)))
3371 (when (= size 0) (give-up-ir1-transform))
3372 (unless (csubtypep (lvar-type x) (specifier-type `(signed-byte ,size)))
3373 (give-up-ir1-transform))
3374 'x))
3376 (deftransform logior ((x y) (* (constant-arg integer)) *)
3377 "fold identity operation"
3378 (let* ((y (lvar-value y))
3379 (width (or (least-zero-bit (lognot y))
3380 (give-up-ir1-transform)))) ; (logior x 0) handled elsewhere
3381 (unless (csubtypep (lvar-type x)
3382 (specifier-type `(integer ,(- (ash 1 width)) -1)))
3383 (give-up-ir1-transform))
3384 'x))
3386 ;;; Pick off easy association opportunities for constant folding.
3387 ;;; More complicated stuff that also depends on commutativity
3388 ;;; (e.g. (f (f x k1) (f y k2)) => (f (f x y) (f k1 k2))) should
3389 ;;; probably be handled with a more general tree-rewriting pass.
3390 (macrolet ((def (operator &key (type 'integer) (folded operator))
3391 `(deftransform ,operator ((x z) (,type (constant-arg ,type)))
3392 ,(format nil "associate ~A/~A of constants"
3393 operator folded)
3394 (binding* ((node (if (lvar-has-single-use-p x)
3395 (lvar-use x)
3396 (give-up-ir1-transform)))
3397 (nil (or (and (combination-p node)
3398 (eq (lvar-fun-name
3399 (combination-fun node))
3400 ',folded))
3401 (give-up-ir1-transform)))
3402 (y (second (combination-args node)))
3403 (nil (or (constant-lvar-p y)
3404 (give-up-ir1-transform)))
3405 (y (lvar-value y)))
3406 (unless (typep y ',type)
3407 (give-up-ir1-transform))
3408 (splice-fun-args x ',folded 2)
3409 `(lambda (x y z)
3410 (declare (ignore y z))
3411 ;; (operator (folded x y) z)
3412 ;; == (operator x (folded z y))
3413 (,',operator x ',(,folded (lvar-value z) y)))))))
3414 (def logand)
3415 (def logior)
3416 (def logxor)
3417 (def logtest :folded logand)
3418 (def + :type rational)
3419 (def + :type rational :folded -)
3420 (def * :type rational)
3421 (def * :type rational :folded /))
3423 (deftransform mask-signed-field ((width x) ((constant-arg unsigned-byte) *))
3424 "Fold mask-signed-field/mask-signed-field of constant width"
3425 (binding* ((node (if (lvar-has-single-use-p x)
3426 (lvar-use x)
3427 (give-up-ir1-transform)))
3428 (nil (or (combination-p node)
3429 (give-up-ir1-transform)))
3430 (nil (or (eq (lvar-fun-name (combination-fun node))
3431 'mask-signed-field)
3432 (give-up-ir1-transform)))
3433 (x-width (first (combination-args node)))
3434 (nil (or (constant-lvar-p x-width)
3435 (give-up-ir1-transform)))
3436 (x-width (lvar-value x-width)))
3437 (unless (typep x-width 'unsigned-byte)
3438 (give-up-ir1-transform))
3439 (splice-fun-args x 'mask-signed-field 2)
3440 `(lambda (width x-width x)
3441 (declare (ignore width x-width))
3442 (mask-signed-field ,(min (lvar-value width) x-width) x))))
3444 ;;; These are restricted to rationals, because (- 0 0.0) is 0.0, not -0.0, and
3445 ;;; (* 0 -4.0) is -0.0.
3446 (deftransform - ((x y) ((constant-arg (member 0)) rational) *)
3447 "convert (- 0 x) to negate"
3448 '(%negate y))
3449 (deftransform * ((x y) (rational (constant-arg (member 0))) *)
3450 "convert (* x 0) to 0"
3453 (deftransform %negate ((x) (rational))
3454 "Eliminate %negate/%negate of rationals"
3455 (splice-fun-args x '%negate 1)
3456 '(the rational x))
3458 (deftransform %negate ((x) (number))
3459 "Combine %negate/*"
3460 (let ((use (lvar-uses x))
3461 arg)
3462 (unless (and (combination-p use)
3463 (eql '* (lvar-fun-name (combination-fun use)))
3464 (constant-lvar-p (setf arg (second (combination-args use))))
3465 (numberp (setf arg (lvar-value arg))))
3466 (give-up-ir1-transform))
3467 (splice-fun-args x '* 2)
3468 `(lambda (x y)
3469 (declare (ignore y))
3470 (* x ,(- arg)))))
3472 ;;; Return T if in an arithmetic op including lvars X and Y, the
3473 ;;; result type is not affected by the type of X. That is, Y is at
3474 ;;; least as contagious as X.
3475 (defun not-more-contagious (x y)
3476 (let ((x (lvar-type x))
3477 (y (lvar-type y)))
3478 (cond
3479 ((csubtypep x (specifier-type 'rational)))
3480 ((csubtypep x (specifier-type 'single-float))
3481 (csubtypep y (specifier-type 'float)))
3482 ((csubtypep x (specifier-type 'double-float))
3483 (csubtypep y (specifier-type 'double-float))))))
3485 (def!type exact-number ()
3486 '(or rational (complex rational)))
3488 ;;; Fold (+ x 0).
3490 ;;; Only safely applicable for exact numbers. For floating-point
3491 ;;; x, one would have to first show that neither x or y are signed
3492 ;;; 0s, and that x isn't an SNaN.
3493 (deftransform + ((x y) (exact-number (constant-arg (eql 0))) *)
3494 "fold zero arg"
3497 ;;; Fold (- x 0).
3498 (deftransform - ((x y) (exact-number (constant-arg (eql 0))) *)
3499 "fold zero arg"
3502 ;;; Fold (OP x +/-1)
3504 ;;; %NEGATE might not always signal correctly.
3505 (macrolet
3506 ((def (name result minus-result)
3507 `(deftransform ,name ((x y)
3508 (exact-number (constant-arg (member 1 -1))))
3509 "fold identity operations"
3510 (if (minusp (lvar-value y)) ',minus-result ',result))))
3511 (def * x (%negate x))
3512 (def / x (%negate x))
3513 (def expt x (/ 1 x)))
3515 ;;; Fold (expt x n) into multiplications for small integral values of
3516 ;;; N; convert (expt x 1/2) to sqrt.
3517 (deftransform expt ((x y) (t (constant-arg real)) *)
3518 "recode as multiplication or sqrt"
3519 (let ((val (lvar-value y)))
3520 ;; If Y would cause the result to be promoted to the same type as
3521 ;; Y, we give up. If not, then the result will be the same type
3522 ;; as X, so we can replace the exponentiation with simple
3523 ;; multiplication and division for small integral powers.
3524 (unless (not-more-contagious y x)
3525 (give-up-ir1-transform))
3526 (cond ((zerop val)
3527 (let ((x-type (lvar-type x)))
3528 (cond ((csubtypep x-type (specifier-type '(or rational
3529 (complex rational))))
3531 ((csubtypep x-type (specifier-type 'real))
3532 `(if (rationalp x)
3534 (float 1 x)))
3535 ((csubtypep x-type (specifier-type 'complex))
3536 ;; both parts are float
3537 `(1+ (* x ,val)))
3538 (t (give-up-ir1-transform)))))
3539 ((= val 2) '(* x x))
3540 ((= val -2) '(/ (* x x)))
3541 ((= val 3) '(* x x x))
3542 ((= val -3) '(/ (* x x x)))
3543 ((= val 1/2) '(sqrt x))
3544 ((= val -1/2) '(/ (sqrt x)))
3545 (t (give-up-ir1-transform)))))
3547 (deftransform expt ((x y) ((constant-arg (member -1 -1.0 -1.0d0)) integer) *)
3548 "recode as an ODDP check"
3549 (let ((val (lvar-value x)))
3550 (if (eql -1 val)
3551 '(- 1 (* 2 (logand 1 y)))
3552 `(if (oddp y)
3553 ,val
3554 ,(abs val)))))
3556 ;;; KLUDGE: Shouldn't (/ 0.0 0.0), etc. cause exceptions in these
3557 ;;; transformations?
3558 ;;; Perhaps we should have to prove that the denominator is nonzero before
3559 ;;; doing them? -- WHN 19990917
3560 (macrolet ((def (name)
3561 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3563 "fold zero arg"
3564 0)))
3565 (def ash)
3566 (def /))
3568 (macrolet ((def (name)
3569 `(deftransform ,name ((x y) ((constant-arg (integer 0 0)) integer)
3571 "fold zero arg"
3572 '(values 0 0))))
3573 (def truncate)
3574 (def round)
3575 (def floor)
3576 (def ceiling))
3578 (macrolet ((def (name &optional float)
3579 (let ((x (if float '(float x) 'x)))
3580 `(deftransform ,name ((x y) (integer (constant-arg (member 1 -1)))
3582 "fold division by 1"
3583 `(values ,(if (minusp (lvar-value y))
3584 '(%negate ,x)
3585 ',x) 0)))))
3586 (def truncate)
3587 (def round)
3588 (def floor)
3589 (def ceiling)
3590 (def ftruncate t)
3591 (def fround t)
3592 (def ffloor t)
3593 (def fceiling t))
3596 ;;;; character operations
3598 (deftransform two-arg-char-equal ((a b) (base-char base-char) *
3599 :policy (> speed space))
3600 "open code"
3601 '(let* ((ac (char-code a))
3602 (bc (char-code b))
3603 (sum (logxor ac bc)))
3604 (or (zerop sum)
3605 (when (eql sum #x20)
3606 (let ((sum (+ ac bc)))
3607 (or (and (> sum 161) (< sum 213))
3608 (and (> sum 415) (< sum 461))
3609 (and (> sum 463) (< sum 477))))))))
3611 (deftransform two-arg-char-equal ((a b) (* (constant-arg character)) *
3612 :node node)
3613 (let ((char (lvar-value b)))
3614 (if (both-case-p char)
3615 (let ((reverse (if (upper-case-p char)
3616 (char-downcase char)
3617 (char-upcase char))))
3618 (if (policy node (> speed space))
3619 `(or (char= a ,char)
3620 (char= a ,reverse))
3621 `(char-equal-constant a ,char ,reverse)))
3622 '(char= a b))))
3624 (deftransform char-upcase ((x) (base-char))
3625 "open code"
3626 '(let ((n-code (char-code x)))
3627 (if (or (and (> n-code #o140) ; Octal 141 is #\a.
3628 (< n-code #o173)) ; Octal 172 is #\z.
3629 (and (> n-code #o337)
3630 (< n-code #o367))
3631 (and (> n-code #o367)
3632 (< n-code #o377)))
3633 (code-char (logxor #x20 n-code))
3634 x)))
3636 (deftransform char-downcase ((x) (base-char))
3637 "open code"
3638 '(let ((n-code (char-code x)))
3639 (if (or (and (> n-code 64) ; 65 is #\A.
3640 (< n-code 91)) ; 90 is #\Z.
3641 (and (> n-code 191)
3642 (< n-code 215))
3643 (and (> n-code 215)
3644 (< n-code 223)))
3645 (code-char (logxor #x20 n-code))
3646 x)))
3648 ;;;; equality predicate transforms
3650 ;;; Return true if X and Y are lvars whose only use is a
3651 ;;; reference to the same leaf, and the value of the leaf cannot
3652 ;;; change.
3653 (defun same-leaf-ref-p (x y)
3654 (declare (type lvar x y))
3655 (let ((x-use (principal-lvar-use x))
3656 (y-use (principal-lvar-use y)))
3657 (and (ref-p x-use)
3658 (ref-p y-use)
3659 (eq (ref-leaf x-use) (ref-leaf y-use))
3660 (constant-reference-p x-use))))
3662 ;;; If X and Y are the same leaf, then the result is true. Otherwise,
3663 ;;; if there is no intersection between the types of the arguments,
3664 ;;; then the result is definitely false.
3665 (deftransforms (eq char=) ((x y) * *)
3666 "Simple equality transform"
3667 (cond
3668 ((same-leaf-ref-p x y) t)
3669 ((not (types-equal-or-intersect (lvar-type x) (lvar-type y)))
3670 nil)
3671 (t (give-up-ir1-transform))))
3673 ;;; Can't use the above thing, since TYPES-EQUAL-OR-INTERSECT is case sensitive.
3674 (deftransform two-arg-char-equal ((x y) * *)
3675 (cond
3676 ((same-leaf-ref-p x y) t)
3677 (t (give-up-ir1-transform))))
3679 ;;; This is similar to SIMPLE-EQUALITY-TRANSFORM, except that we also
3680 ;;; try to convert to a type-specific predicate or EQ:
3681 ;;; -- If both args are characters, convert to CHAR=. This is better than
3682 ;;; just converting to EQ, since CHAR= may have special compilation
3683 ;;; strategies for non-standard representations, etc.
3684 ;;; -- If either arg is definitely a fixnum, we check to see if X is
3685 ;;; constant and if so, put X second. Doing this results in better
3686 ;;; code from the backend, since the backend assumes that any constant
3687 ;;; argument comes second.
3688 ;;; -- If either arg is definitely not a number or a fixnum, then we
3689 ;;; can compare with EQ.
3690 ;;; -- Otherwise, we try to put the arg we know more about second. If X
3691 ;;; is constant then we put it second. If X is a subtype of Y, we put
3692 ;;; it second. These rules make it easier for the back end to match
3693 ;;; these interesting cases.
3694 (deftransform eql ((x y) * * :node node)
3695 "convert to simpler equality predicate"
3696 (let ((x-type (lvar-type x))
3697 (y-type (lvar-type y))
3698 #!+integer-eql-vop (int-type (specifier-type 'integer))
3699 (char-type (specifier-type 'character)))
3700 (cond
3701 ((same-leaf-ref-p x y) t)
3702 ((not (types-equal-or-intersect x-type y-type))
3703 nil)
3704 ((and (csubtypep x-type char-type)
3705 (csubtypep y-type char-type))
3706 '(char= x y))
3707 ((or (eq-comparable-type-p x-type) (eq-comparable-type-p y-type))
3708 '(eq y x))
3709 #!+integer-eql-vop
3710 ((or (csubtypep x-type int-type) (csubtypep y-type int-type))
3711 '(%eql/integer x y))
3713 (give-up-ir1-transform)))))
3715 (defun array-type-dimensions-mismatch (x-type y-type)
3716 (let ((array-type (specifier-type 'array))
3717 (simple-array-type (specifier-type 'simple-array)))
3718 (and (csubtypep x-type array-type)
3719 (csubtypep y-type array-type)
3720 (let ((x-dims (ctype-array-dimensions x-type))
3721 (y-dims (ctype-array-dimensions y-type)))
3722 (and (consp x-dims)
3723 (consp y-dims)
3724 (or (/= (length x-dims)
3725 (length y-dims))
3726 ;; Can compare dimensions only for simple
3727 ;; arrays due to fill-pointer and
3728 ;; adjust-array.
3729 (and (csubtypep x-type simple-array-type)
3730 (csubtypep y-type simple-array-type)
3731 (loop for x-dim in x-dims
3732 for y-dim in y-dims
3733 thereis (and (integerp x-dim)
3734 (integerp y-dim)
3735 (not (= x-dim y-dim)))))))))))
3737 ;;; similarly to the EQL transform above, we attempt to constant-fold
3738 ;;; or convert to a simpler predicate: mostly we have to be careful
3739 ;;; with strings and bit-vectors.
3740 (deftransform equal ((x y) * *)
3741 "convert to simpler equality predicate"
3742 (let ((x-type (lvar-type x))
3743 (y-type (lvar-type y))
3744 (combination-type (specifier-type '(or bit-vector string
3745 cons pathname))))
3746 (flet ((both-csubtypep (type)
3747 (let ((ctype (specifier-type type)))
3748 (and (csubtypep x-type ctype)
3749 (csubtypep y-type ctype))))
3750 (some-csubtypep (type)
3751 (let ((ctype (specifier-type type)))
3752 (or (csubtypep x-type ctype)
3753 (csubtypep y-type ctype))))
3754 (some-csubtypep2 (type1 type2)
3755 (let ((ctype1 (specifier-type type1))
3756 (ctype2 (specifier-type type2)))
3757 (or (and (csubtypep x-type ctype1)
3758 (csubtypep y-type ctype2))
3759 (and (csubtypep y-type ctype1)
3760 (csubtypep x-type ctype2)))))
3761 (mismatching-types-p (type)
3762 (let* ((ctype (specifier-type type))
3763 (x-equal (types-equal-or-intersect x-type ctype))
3764 (y-equal (types-equal-or-intersect y-type ctype)))
3765 (or (and x-equal (not y-equal))
3766 (and (not x-equal) y-equal))))
3767 (non-equal-array-p (type)
3768 (and (csubtypep type (specifier-type 'array))
3769 (let ((equal-types (specifier-type '(or bit character)))
3770 (element-types (ctype-array-specialized-element-types type)))
3771 (and (neq element-types *wild-type*)
3772 (notany (lambda (x)
3773 (csubtypep x equal-types))
3774 element-types))))))
3775 (cond
3776 ((same-leaf-ref-p x y) t)
3777 ((array-type-dimensions-mismatch x-type y-type)
3778 nil)
3779 ((and (constant-lvar-p x)
3780 (equal (lvar-value x) ""))
3781 `(and (stringp y)
3782 (zerop (length y))))
3783 ((and (constant-lvar-p y)
3784 (equal (lvar-value y) ""))
3785 `(and (stringp x)
3786 (zerop (length x))))
3787 ((both-csubtypep 'string)
3788 '(string= x y))
3789 ((both-csubtypep 'bit-vector)
3790 '(bit-vector-= x y))
3791 ((both-csubtypep 'pathname)
3792 '(pathname= x y))
3793 ((or (non-equal-array-p x-type)
3794 (non-equal-array-p y-type))
3795 '(eq x y))
3796 ((types-equal-or-intersect x-type y-type)
3797 (cond ((some-csubtypep 'number)
3798 '(eql x y))
3799 ((some-csubtypep '(and array (not vector)))
3800 '(eq x y))
3801 ((both-csubtypep 'simple-array)
3802 ;; Can only work on simple arrays due to fill-pointer
3803 (let ((x-dim (ctype-array-dimensions x-type))
3804 (y-dim (ctype-array-dimensions x-type)))
3805 (if (and (consp x-dim)
3806 (consp y-dim)
3807 (integerp (car x-dim))
3808 (integerp (car y-dim))
3809 (not (equal x-dim y-dim)))
3811 (give-up-ir1-transform))))
3812 ((or (types-equal-or-intersect x-type combination-type)
3813 (types-equal-or-intersect y-type combination-type))
3814 (give-up-ir1-transform))
3816 '(eql x y))))
3817 ((or (mismatching-types-p 'cons)
3818 (mismatching-types-p 'bit-vector)
3819 (mismatching-types-p 'string))
3820 nil)
3821 ((some-csubtypep2 '(and array (not vector))
3822 'vector)
3823 nil)
3824 (t (give-up-ir1-transform))))))
3826 (deftransform equalp ((x y) * *)
3827 "convert to simpler equality predicate"
3828 (let ((x-type (lvar-type x))
3829 (y-type (lvar-type y))
3830 (combination-type (specifier-type '(or number array
3831 character
3832 cons pathname
3833 instance hash-table))))
3834 (flet ((both-csubtypep (type)
3835 (let ((ctype (specifier-type type)))
3836 (and (csubtypep x-type ctype)
3837 (csubtypep y-type ctype))))
3838 (mismatching-types-p (type)
3839 (let* ((ctype (specifier-type type))
3840 (x-equal (types-equal-or-intersect x-type ctype))
3841 (y-equal (types-equal-or-intersect y-type ctype)))
3842 (or (and x-equal (not y-equal))
3843 (and (not x-equal) y-equal)))))
3844 (cond
3845 ((same-leaf-ref-p x y) t)
3846 ((array-type-dimensions-mismatch x-type y-type)
3847 nil)
3848 ((and (constant-lvar-p x)
3849 (equal (lvar-value x) ""))
3850 `(and (stringp y)
3851 (zerop (length y))))
3852 ((and (constant-lvar-p y)
3853 (equal (lvar-value y) ""))
3854 `(and (stringp x)
3855 (zerop (length x))))
3856 ((both-csubtypep 'string)
3857 '(string-equal x y))
3858 ((both-csubtypep 'bit-vector)
3859 '(bit-vector-= x y))
3860 ((both-csubtypep 'pathname)
3861 '(pathname= x y))
3862 ((both-csubtypep 'character)
3863 '(char-equal x y))
3864 ((both-csubtypep 'number)
3865 '(= x y))
3866 ((both-csubtypep 'hash-table)
3867 '(hash-table-equalp x y))
3868 ((and (both-csubtypep 'array)
3869 (flet ((upgraded-et (type)
3870 (multiple-value-bind (specialized supetype)
3871 (array-type-upgraded-element-type type)
3872 (or supetype specialized))))
3873 (let ((number-ctype (specifier-type 'number))
3874 (x-et (upgraded-et x-type))
3875 (y-et (upgraded-et y-type)))
3876 (and (neq x-et *wild-type*)
3877 (neq y-et *wild-type*)
3878 (cond ((types-equal-or-intersect x-et y-et)
3879 nil)
3880 ((csubtypep x-et number-ctype)
3881 (not (types-equal-or-intersect y-et number-ctype)))
3882 ((types-equal-or-intersect y-et number-ctype)
3883 (not (types-equal-or-intersect x-et number-ctype))))))))
3884 nil)
3885 ((types-equal-or-intersect x-type y-type)
3886 (if (or (types-equal-or-intersect x-type combination-type)
3887 (types-equal-or-intersect y-type combination-type))
3888 (give-up-ir1-transform)
3889 '(eq x y)))
3890 ((or (mismatching-types-p 'cons)
3891 (mismatching-types-p 'array)
3892 (mismatching-types-p 'number))
3893 nil)
3894 (t (give-up-ir1-transform))))))
3896 ;;; Convert to EQL if both args are rational and complexp is specified
3897 ;;; and the same for both.
3898 (deftransform = ((x y) (number number) *)
3899 "open code"
3900 (let ((x-type (lvar-type x))
3901 (y-type (lvar-type y)))
3902 (cond ((or (and (csubtypep x-type (specifier-type 'float))
3903 (csubtypep y-type (specifier-type 'float)))
3904 (and (csubtypep x-type (specifier-type '(complex float)))
3905 (csubtypep y-type (specifier-type '(complex float))))
3906 #!+complex-float-vops
3907 (and (csubtypep x-type (specifier-type '(or single-float (complex single-float))))
3908 (csubtypep y-type (specifier-type '(or single-float (complex single-float)))))
3909 #!+complex-float-vops
3910 (and (csubtypep x-type (specifier-type '(or double-float (complex double-float))))
3911 (csubtypep y-type (specifier-type '(or double-float (complex double-float))))))
3912 ;; They are both floats. Leave as = so that -0.0 is
3913 ;; handled correctly.
3914 (give-up-ir1-transform))
3915 ((or (and (csubtypep x-type (specifier-type 'rational))
3916 (csubtypep y-type (specifier-type 'rational)))
3917 (and (csubtypep x-type
3918 (specifier-type '(complex rational)))
3919 (csubtypep y-type
3920 (specifier-type '(complex rational)))))
3921 ;; They are both rationals and complexp is the same.
3922 ;; Convert to EQL.
3923 '(eql x y))
3925 (give-up-ir1-transform
3926 "The operands might not be the same type.")))))
3928 (defun maybe-float-lvar-p (lvar)
3929 (neq *empty-type* (type-intersection (specifier-type 'float)
3930 (lvar-type lvar))))
3932 (flet ((maybe-invert (node op inverted x y)
3933 ;; Don't invert if either argument can be a float (NaNs)
3934 (cond
3935 ((or (maybe-float-lvar-p x) (maybe-float-lvar-p y))
3936 (delay-ir1-transform node :constraint)
3937 `(or (,op x y) (= x y)))
3939 `(if (,inverted x y) nil t)))))
3940 (deftransform >= ((x y) (number number) * :node node)
3941 "invert or open code"
3942 (maybe-invert node '> '< x y))
3943 (deftransform <= ((x y) (number number) * :node node)
3944 "invert or open code"
3945 (maybe-invert node '< '> x y)))
3947 ;;; See whether we can statically determine (< X Y) using type
3948 ;;; information. If X's high bound is < Y's low, then X < Y.
3949 ;;; Similarly, if X's low is >= to Y's high, the X >= Y (so return
3950 ;;; NIL). If not, at least make sure any constant arg is second.
3951 (macrolet ((def (name inverse reflexive-p surely-true surely-false)
3952 `(deftransform ,name ((x y))
3953 "optimize using intervals"
3954 (if (and (same-leaf-ref-p x y)
3955 ;; For non-reflexive functions we don't need
3956 ;; to worry about NaNs: (non-ref-op NaN NaN) => false,
3957 ;; but with reflexive ones we don't know...
3958 ,@(when reflexive-p
3959 '((and (not (maybe-float-lvar-p x))
3960 (not (maybe-float-lvar-p y))))))
3961 ,reflexive-p
3962 (let ((ix (or (type-approximate-interval (lvar-type x))
3963 (give-up-ir1-transform)))
3964 (iy (or (type-approximate-interval (lvar-type y))
3965 (give-up-ir1-transform))))
3966 (cond (,surely-true
3968 (,surely-false
3969 nil)
3970 ((and (constant-lvar-p x)
3971 (not (constant-lvar-p y)))
3972 `(,',inverse y x))
3974 (give-up-ir1-transform))))))))
3975 (def = = t (interval-= ix iy) (interval-/= ix iy))
3976 (def /= /= nil (interval-/= ix iy) (interval-= ix iy))
3977 (def < > nil (interval-< ix iy) (interval->= ix iy))
3978 (def > < nil (interval-< iy ix) (interval->= iy ix))
3979 (def <= >= t (interval->= iy ix) (interval-< iy ix))
3980 (def >= <= t (interval->= ix iy) (interval-< ix iy)))
3982 (defun ir1-transform-char< (x y first second inverse)
3983 (cond
3984 ((same-leaf-ref-p x y) nil)
3985 ;; If we had interval representation of character types, as we
3986 ;; might eventually have to to support 2^21 characters, then here
3987 ;; we could do some compile-time computation as in transforms for
3988 ;; < above. -- CSR, 2003-07-01
3989 ((and (constant-lvar-p first)
3990 (not (constant-lvar-p second)))
3991 `(,inverse y x))
3992 (t (give-up-ir1-transform))))
3994 (deftransform char< ((x y) (character character) *)
3995 (ir1-transform-char< x y x y 'char>))
3997 (deftransform char> ((x y) (character character) *)
3998 (ir1-transform-char< y x x y 'char<))
4000 ;;;; converting N-arg comparisons
4001 ;;;;
4002 ;;;; We convert calls to N-arg comparison functions such as < into
4003 ;;;; two-arg calls. This transformation is enabled for all such
4004 ;;;; comparisons in this file. If any of these predicates are not
4005 ;;;; open-coded, then the transformation should be removed at some
4006 ;;;; point to avoid pessimization.
4008 ;;; This function is used for source transformation of N-arg
4009 ;;; comparison functions other than inequality. We deal both with
4010 ;;; converting to two-arg calls and inverting the sense of the test,
4011 ;;; if necessary. If the call has two args, then we pass or return a
4012 ;;; negated test as appropriate. If it is a degenerate one-arg call,
4013 ;;; then we transform to code that returns true. Otherwise, we bind
4014 ;;; all the arguments and expand into a bunch of IFs.
4015 (defun multi-compare (predicate args not-p type &optional force-two-arg-p)
4016 (let ((nargs (length args)))
4017 (cond ((< nargs 1) (values nil t))
4018 ((= nargs 1) `(progn (the ,type ,@args) t))
4019 ((= nargs 2)
4020 (if not-p
4021 `(if (,predicate ,(first args) ,(second args)) nil t)
4022 (if force-two-arg-p
4023 `(,predicate ,(first args) ,(second args))
4024 (values nil t))))
4026 (do* ((i (1- nargs) (1- i))
4027 (last nil current)
4028 (current (gensym) (gensym))
4029 (vars (list current) (cons current vars))
4030 (result t (if not-p
4031 `(if (,predicate ,current ,last)
4032 nil ,result)
4033 `(if (,predicate ,current ,last)
4034 ,result nil))))
4035 ((zerop i)
4036 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
4037 ,@args)))))))
4039 (define-source-transform = (&rest args) (multi-compare '= args nil 'number))
4040 (define-source-transform < (&rest args) (multi-compare '< args nil 'real))
4041 (define-source-transform > (&rest args) (multi-compare '> args nil 'real))
4042 ;;; We cannot do the inversion for >= and <= here, since both
4043 ;;; (< NaN X) and (> NaN X)
4044 ;;; are false, and we don't have type-information available yet. The
4045 ;;; deftransforms for two-argument versions of >= and <= takes care of
4046 ;;; the inversion to > and < when possible.
4047 (define-source-transform <= (&rest args) (multi-compare '<= args nil 'real))
4048 (define-source-transform >= (&rest args) (multi-compare '>= args nil 'real))
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 nil
4053 'character))
4054 (define-source-transform char> (&rest args) (multi-compare 'char> args nil
4055 'character))
4056 (define-source-transform char<= (&rest args) (multi-compare 'char> args t
4057 'character))
4058 (define-source-transform char>= (&rest args) (multi-compare 'char< args t
4059 'character))
4061 (define-source-transform char-equal (&rest args)
4062 (multi-compare 'two-arg-char-equal args nil 'character t))
4063 (define-source-transform char-lessp (&rest args)
4064 (multi-compare 'two-arg-char-lessp args nil 'character t))
4065 (define-source-transform char-greaterp (&rest args)
4066 (multi-compare 'two-arg-char-greaterp args nil 'character t))
4067 (define-source-transform char-not-greaterp (&rest args)
4068 (multi-compare 'two-arg-char-greaterp args t 'character t))
4069 (define-source-transform char-not-lessp (&rest args)
4070 (multi-compare 'two-arg-char-lessp args t 'character t))
4072 ;;; This function does source transformation of N-arg inequality
4073 ;;; functions such as /=. This is similar to MULTI-COMPARE in the <3
4074 ;;; arg cases. If there are more than two args, then we expand into
4075 ;;; the appropriate n^2 comparisons only when speed is important.
4076 (declaim (ftype (function (symbol list t) *) multi-not-equal))
4077 (defun multi-not-equal (predicate args type)
4078 (let ((nargs (length args)))
4079 (cond ((< nargs 1) (values nil t))
4080 ((= nargs 1) `(progn (the ,type ,@args) t))
4081 ((= nargs 2)
4082 `(if (,predicate ,(first args) ,(second args)) nil t))
4083 ((not (policy *lexenv*
4084 (and (>= speed space)
4085 (>= speed compilation-speed))))
4086 (values nil t))
4088 (let ((vars (make-gensym-list nargs)))
4089 (do ((var vars next)
4090 (next (cdr vars) (cdr next))
4091 (result t))
4092 ((null next)
4093 `((lambda ,vars (declare (type ,type ,@vars)) ,result)
4094 ,@args))
4095 (let ((v1 (first var)))
4096 (dolist (v2 next)
4097 (setq result `(if (,predicate ,v1 ,v2) nil ,result))))))))))
4099 (define-source-transform /= (&rest args)
4100 (multi-not-equal '= args 'number))
4101 (define-source-transform char/= (&rest args)
4102 (multi-not-equal 'char= args 'character))
4103 (define-source-transform char-not-equal (&rest args)
4104 (multi-not-equal 'char-equal args 'character))
4106 ;;; Expand MAX and MIN into the obvious comparisons.
4107 (define-source-transform max (arg0 &rest rest)
4108 (once-only ((arg0 arg0))
4109 (if (null rest)
4110 `(values (the real ,arg0))
4111 `(let ((maxrest (max ,@rest)))
4112 (if (>= ,arg0 maxrest) ,arg0 maxrest)))))
4113 (define-source-transform min (arg0 &rest rest)
4114 (once-only ((arg0 arg0))
4115 (if (null rest)
4116 `(values (the real ,arg0))
4117 `(let ((minrest (min ,@rest)))
4118 (if (<= ,arg0 minrest) ,arg0 minrest)))))
4120 ;;; Simplify some cross-type comparisons
4121 (macrolet ((def (comparator round)
4122 `(progn
4123 (deftransform ,comparator
4124 ((x y) (rational (constant-arg float)))
4125 "open-code RATIONAL to FLOAT comparison"
4126 (let ((y (lvar-value y)))
4127 #-sb-xc-host
4128 (when (or (float-nan-p y)
4129 (float-infinity-p y))
4130 (give-up-ir1-transform))
4131 (setf y (rational y))
4132 `(,',comparator
4133 x ,(if (csubtypep (lvar-type x)
4134 (specifier-type 'integer))
4135 (,round y)
4136 y))))
4137 (deftransform ,comparator
4138 ((x y) (integer (constant-arg ratio)))
4139 "open-code INTEGER to RATIO comparison"
4140 `(,',comparator x ,(,round (lvar-value y)))))))
4141 (def < ceiling)
4142 (def > floor))
4144 (deftransform = ((x y) (rational (constant-arg float)))
4145 "open-code RATIONAL to FLOAT comparison"
4146 (let ((y (lvar-value y)))
4147 #-sb-xc-host
4148 (when (or (float-nan-p y)
4149 (float-infinity-p y))
4150 (give-up-ir1-transform))
4151 (setf y (rational y))
4152 (if (and (csubtypep (lvar-type x)
4153 (specifier-type 'integer))
4154 (ratiop y))
4156 `(= x ,y))))
4158 (deftransform = ((x y) (integer (constant-arg ratio)))
4159 "constant-fold INTEGER to RATIO comparison"
4160 nil)
4162 ;;;; converting N-arg arithmetic functions
4163 ;;;;
4164 ;;;; N-arg arithmetic and logic functions are associated into two-arg
4165 ;;;; versions, and degenerate cases are flushed.
4167 ;;; Left-associate FIRST-ARG and MORE-ARGS using FUNCTION.
4168 (declaim (ftype (sfunction (symbol t list) list) associate-args))
4169 (defun associate-args (fun first-arg more-args)
4170 (aver more-args)
4171 (let ((next (rest more-args))
4172 (arg (first more-args)))
4173 (if (null next)
4174 `(,fun ,first-arg ,arg)
4175 (associate-args fun `(,fun ,first-arg ,arg) next))))
4177 ;;; Reduce constants in ARGS list.
4178 (declaim (ftype (sfunction (symbol list symbol) list) reduce-constants))
4179 (defun reduce-constants (fun args one-arg-result-type)
4180 (let ((one-arg-constant-p (ecase one-arg-result-type
4181 (number #'numberp)
4182 (integer #'integerp)))
4183 (reduced-value)
4184 (reduced-p nil))
4185 (collect ((not-constants))
4186 (dolist (arg args)
4187 (let ((value (if (constantp arg)
4188 (constant-form-value arg)
4189 arg)))
4190 (cond ((not (funcall one-arg-constant-p value))
4191 (not-constants arg))
4192 (reduced-value
4193 (handler-case (funcall fun reduced-value value)
4194 (arithmetic-error ()
4195 (not-constants arg))
4196 (:no-error (value)
4197 ;; Some backends have no float traps
4198 (cond #!+(and (or arm arm64)
4199 (not (host-feature sb-xc-host)))
4200 ((or (and (floatp value)
4201 (or (float-infinity-p value)
4202 (float-nan-p value)))
4203 (and (complex-float-p value)
4204 (or (float-infinity-p (imagpart value))
4205 (float-nan-p (imagpart value))
4206 (float-infinity-p (realpart value))
4207 (float-nan-p (realpart value)))))
4208 (not-constants arg))
4210 (setf reduced-value value
4211 reduced-p t))))))
4213 (setf reduced-value value)))))
4214 ;; It is tempting to drop constants reduced to identity here,
4215 ;; but if X is SNaN in (* X 1), we cannot drop the 1.
4216 (if (not-constants)
4217 (if reduced-p
4218 `(,reduced-value ,@(not-constants))
4219 args)
4220 `(,reduced-value)))))
4222 ;;; Do source transformations for transitive functions such as +.
4223 ;;; One-arg cases are replaced with the arg and zero arg cases with
4224 ;;; the identity. ONE-ARG-RESULT-TYPE is the type to ensure (with THE)
4225 ;;; that the argument in one-argument calls is.
4226 (declaim (ftype (function (symbol list t &optional symbol list)
4227 * ; KLUDGE: avoid "assertion too complex to check"
4228 #|(values t &optional (member nil t))|#)
4229 source-transform-transitive))
4230 (defun source-transform-transitive (fun args identity
4231 &optional (one-arg-result-type 'number)
4232 (one-arg-prefixes '(values)))
4233 (case (length args)
4234 (0 identity)
4235 (1 `(,@one-arg-prefixes (the ,one-arg-result-type ,(first args))))
4236 (2 (values nil t))
4238 (let* ((reduced-args (reduce-constants fun args one-arg-result-type))
4239 (first (first reduced-args))
4240 (rest (rest reduced-args)))
4241 (if rest
4242 (associate-args fun first rest)
4243 first)))))
4245 (define-source-transform + (&rest args)
4246 (source-transform-transitive '+ args 0))
4247 (define-source-transform * (&rest args)
4248 (source-transform-transitive '* args 1))
4249 (define-source-transform logior (&rest args)
4250 (source-transform-transitive 'logior args 0 'integer))
4251 (define-source-transform logxor (&rest args)
4252 (source-transform-transitive 'logxor args 0 'integer))
4253 (define-source-transform logand (&rest args)
4254 (source-transform-transitive 'logand args -1 'integer))
4255 (define-source-transform logeqv (&rest args)
4256 (source-transform-transitive 'logeqv args -1 'integer))
4257 (define-source-transform gcd (&rest args)
4258 (source-transform-transitive 'gcd args 0 'integer '(abs)))
4259 (define-source-transform lcm (&rest args)
4260 (source-transform-transitive 'lcm args 1 'integer '(abs)))
4262 ;;; Do source transformations for intransitive n-arg functions such as
4263 ;;; /. With one arg, we form the inverse. With two args we pass.
4264 ;;; Otherwise we associate into two-arg calls.
4265 (declaim (ftype (function (symbol symbol list list &optional symbol)
4266 * ; KLUDGE: avoid "assertion too complex to check"
4267 #|(values list &optional (member nil t))|#)
4268 source-transform-intransitive))
4269 (defun source-transform-intransitive (fun fun* args one-arg-prefixes
4270 &optional (one-arg-result-type 'number))
4271 (case (length args)
4272 ((0 2) (values nil t))
4273 (1 `(,@one-arg-prefixes (the ,one-arg-result-type ,(first args))))
4275 (let ((reduced-args
4276 (reduce-constants fun* (rest args) one-arg-result-type)))
4277 (associate-args fun (first args) reduced-args)))))
4279 (define-source-transform - (&rest args)
4280 (source-transform-intransitive '- '+ args '(%negate)))
4281 (define-source-transform / (&rest args)
4282 (source-transform-intransitive '/ '* args '(/ 1)))
4284 ;;;; transforming APPLY
4286 ;;; We convert APPLY into MULTIPLE-VALUE-CALL so that the compiler
4287 ;;; only needs to understand one kind of variable-argument call. It is
4288 ;;; more efficient to convert APPLY to MV-CALL than MV-CALL to APPLY.
4289 (define-source-transform apply (fun arg &rest more-args)
4290 (let ((args (cons arg more-args)))
4291 `(multiple-value-call ,fun
4292 ,@(mapcar (lambda (x) `(values ,x)) (butlast args))
4293 (values-list ,(car (last args))))))
4295 ;;;; transforming references to &REST argument
4297 ;;; We add magical &MORE arguments to all functions with &REST. If ARG names
4298 ;;; the &REST argument, this returns the lambda-vars for the context and
4299 ;;; count.
4300 (defun possible-rest-arg-context (arg)
4301 (when (symbolp arg)
4302 (let* ((var (lexenv-find arg vars))
4303 (info (when (lambda-var-p var)
4304 (lambda-var-arg-info var))))
4305 (when (and info
4306 (eq :rest (arg-info-kind info))
4307 (consp (arg-info-default info)))
4308 (values-list (arg-info-default info))))))
4310 (defun mark-more-context-used (rest-var)
4311 (let ((info (lambda-var-arg-info rest-var)))
4312 (aver (eq :rest (arg-info-kind info)))
4313 (destructuring-bind (context count &optional used) (arg-info-default info)
4314 (unless used
4315 (setf (arg-info-default info) (list context count t))))))
4317 (defun mark-more-context-invalid (rest-var)
4318 (let ((info (lambda-var-arg-info rest-var)))
4319 (aver (eq :rest (arg-info-kind info)))
4320 (setf (arg-info-default info) t)))
4322 ;;; This determines if the REF to a &REST variable is headed towards
4323 ;;; parts unknown, or if we can really use the context.
4324 (defun rest-var-more-context-ok (lvar)
4325 (let* ((use (lvar-use lvar))
4326 (var (when (ref-p use) (ref-leaf use)))
4327 (home (when (lambda-var-p var) (lambda-var-home var)))
4328 (info (when (lambda-var-p var) (lambda-var-arg-info var)))
4329 (restp (when info (eq :rest (arg-info-kind info)))))
4330 (flet ((ref-good-for-more-context-p (ref)
4331 (when (not (node-lvar ref)) ; ref that goes nowhere is ok
4332 (return-from ref-good-for-more-context-p t))
4333 (let ((dest (principal-lvar-end (node-lvar ref))))
4334 (and (combination-p dest)
4335 ;; If the destination is to anything but these, we're going to
4336 ;; actually need the rest list -- and since other operations
4337 ;; might modify the list destructively, the using the context
4338 ;; isn't good anywhere else either.
4339 (lvar-fun-is (combination-fun dest)
4340 '(%rest-values %rest-ref %rest-length
4341 %rest-null %rest-true))
4342 ;; If the home lambda is different and isn't DX, it might
4343 ;; escape -- in which case using the more context isn't safe.
4344 (let ((clambda (node-home-lambda dest)))
4345 (or (eq home clambda)
4346 (leaf-dynamic-extent clambda)))))))
4347 (let ((ok (and restp
4348 (consp (arg-info-default info))
4349 (not (lambda-var-specvar var))
4350 (not (lambda-var-sets var))
4351 (every #'ref-good-for-more-context-p (lambda-var-refs var)))))
4352 (if ok
4353 (mark-more-context-used var)
4354 (when restp
4355 (mark-more-context-invalid var)))
4356 ok))))
4358 ;;; VALUES-LIST -> %REST-VALUES
4359 (define-source-transform values-list (list)
4360 (multiple-value-bind (context count) (possible-rest-arg-context list)
4361 (if context
4362 `(%rest-values ,list ,context ,count)
4363 (values nil t))))
4365 ;;; NTH -> %REST-REF
4366 (define-source-transform nth (n list)
4367 (multiple-value-bind (context count) (possible-rest-arg-context list)
4368 (if context
4369 `(%rest-ref ,n ,list ,context ,count)
4370 `(car (nthcdr ,n ,list)))))
4371 (define-source-transform fast-&rest-nth (n list)
4372 (multiple-value-bind (context count) (possible-rest-arg-context list)
4373 (if context
4374 `(%rest-ref ,n ,list ,context ,count t)
4375 (bug "no &REST context for FAST-REST-NTH"))))
4377 (define-source-transform elt (seq n)
4378 (if (policy *lexenv* (= safety 3))
4379 (values nil t)
4380 (multiple-value-bind (context count) (possible-rest-arg-context seq)
4381 (if context
4382 `(%rest-ref ,n ,seq ,context ,count)
4383 (values nil t)))))
4385 ;;; CAxR -> %REST-REF
4386 (defun source-transform-car (list nth)
4387 (multiple-value-bind (context count) (possible-rest-arg-context list)
4388 (if context
4389 `(%rest-ref ,nth ,list ,context ,count)
4390 (values nil t))))
4392 (define-source-transform car (list)
4393 (source-transform-car list 0))
4395 (define-source-transform cadr (list)
4396 (or (source-transform-car list 1)
4397 `(car (cdr ,list))))
4399 (define-source-transform caddr (list)
4400 (or (source-transform-car list 2)
4401 `(car (cdr (cdr ,list)))))
4403 (define-source-transform cadddr (list)
4404 (or (source-transform-car list 3)
4405 `(car (cdr (cdr (cdr ,list))))))
4407 ;;; LENGTH -> %REST-LENGTH
4408 (defun source-transform-length (list)
4409 (multiple-value-bind (context count) (possible-rest-arg-context list)
4410 (if context
4411 `(%rest-length ,list ,context ,count)
4412 (values nil t))))
4413 (define-source-transform length (list) (source-transform-length list))
4414 (define-source-transform list-length (list) (source-transform-length list))
4416 ;;; ENDP, NULL and NOT -> %REST-NULL
4418 ;;; Outside &REST convert into an IF so that IF optimizations will eliminate
4419 ;;; redundant negations.
4420 (defun source-transform-null (x op)
4421 (multiple-value-bind (context count) (possible-rest-arg-context x)
4422 (cond (context
4423 `(%rest-null ',op ,x ,context ,count))
4424 ((eq 'endp op)
4425 `(if (the list ,x) nil t))
4427 `(if ,x nil t)))))
4428 (define-source-transform not (x) (source-transform-null x 'not))
4429 (define-source-transform null (x) (source-transform-null x 'null))
4430 (define-source-transform endp (x) (source-transform-null x 'endp))
4432 (deftransform %rest-values ((list context count))
4433 (if (rest-var-more-context-ok list)
4434 `(%more-arg-values context 0 count)
4435 `(values-list list)))
4437 (deftransform %rest-ref ((n list context count &optional length-checked-p))
4438 (cond ((rest-var-more-context-ok list)
4439 (if (and (constant-lvar-p length-checked-p)
4440 (lvar-value length-checked-p))
4441 `(%more-arg context n)
4442 `(and (< (the index n) count) (%more-arg context n))))
4443 ((and (constant-lvar-p n) (zerop (lvar-value n)))
4444 `(car list))
4446 `(nth n list))))
4448 (deftransform %rest-length ((list context count))
4449 (if (rest-var-more-context-ok list)
4450 'count
4451 `(length list)))
4453 (deftransform %rest-null ((op list context count))
4454 (aver (constant-lvar-p op))
4455 (if (rest-var-more-context-ok list)
4456 `(eql 0 count)
4457 `(,(lvar-value op) list)))
4459 (deftransform %rest-true ((list context count))
4460 (if (rest-var-more-context-ok list)
4461 `(not (eql 0 count))
4462 `list))
4464 ;;;; transforming FORMAT
4465 ;;;;
4466 ;;;; If the control string is a compile-time constant, then replace it
4467 ;;;; with a use of the FORMATTER macro so that the control string is
4468 ;;;; ``compiled.'' Furthermore, if the destination is either a stream
4469 ;;;; or T and the control string is a function (i.e. FORMATTER), then
4470 ;;;; convert the call to FORMAT to just a FUNCALL of that function.
4472 ;;; for compile-time argument count checking.
4474 ;;; FIXME II: In some cases, type information could be correlated; for
4475 ;;; instance, ~{ ... ~} requires a list argument, so if the lvar-type
4476 ;;; of a corresponding argument is known and does not intersect the
4477 ;;; list type, a warning could be signalled.
4478 (defun check-format-args (string args fun)
4479 (declare (type string string))
4480 (unless (typep string 'simple-string)
4481 (setq string (coerce string 'simple-string)))
4482 (multiple-value-bind (min max)
4483 (handler-case (sb!format:%compiler-walk-format-string string args)
4484 (sb!format:format-error (c)
4485 (compiler-warn "~A" c)))
4486 (when min
4487 (let ((nargs (length args)))
4488 (cond
4489 ((< nargs min)
4490 (warn 'format-too-few-args-warning
4491 :format-control
4492 "Too few arguments (~D) to ~S ~S: requires at least ~D."
4493 :format-arguments (list nargs fun string min)))
4494 ((> nargs max)
4495 (warn 'format-too-many-args-warning
4496 :format-control
4497 "Too many arguments (~D) to ~S ~S: uses at most ~D."
4498 :format-arguments (list nargs fun string max))))))))
4500 (defoptimizer (format optimizer) ((dest control &rest args) node)
4501 (declare (ignore dest))
4502 (when (constant-lvar-p control)
4503 (let ((x (lvar-value control)))
4504 (when (stringp x)
4505 (let ((*compiler-error-context* node))
4506 (check-format-args x args 'format))))))
4508 (defoptimizer (format derive-type) ((dest control &rest args))
4509 (declare (ignore control args))
4510 (when (and (constant-lvar-p dest)
4511 (null (lvar-value dest)))
4512 (specifier-type 'simple-string)))
4514 ;;; We disable this transform in the cross-compiler to save memory in
4515 ;;; the target image; most of the uses of FORMAT in the compiler are for
4516 ;;; error messages, and those don't need to be particularly fast.
4517 #+sb-xc
4518 (deftransform format ((dest control &rest args) (t simple-string &rest t) *
4519 :policy (>= speed space))
4520 (unless (constant-lvar-p control)
4521 (give-up-ir1-transform "The control string is not a constant."))
4522 (let* ((argc (length args))
4523 (arg-names (make-gensym-list argc))
4524 (control (lvar-value control))
4525 ;; Expanding the control string now avoids deferring to FORMATTER
4526 ;; so that we don't need an internal-only variant of it that
4527 ;; passes through extra args to %FORMATTER.
4528 ;; FIXME: instead of checking the condition report, define a
4529 ;; dedicated condition class
4530 (expr (handler-case ; in case %formatter wants to signal an error
4531 (sb!format::%formatter control argc nil)
4532 ;; otherwise, let the macro complain
4533 (sb!format:format-error (c)
4534 (if (string= (sb!format::format-error-complaint c)
4535 "No package named ~S")
4536 ;; "~/apackage:afun/" might become legal later.
4537 ;; To put it in perspective, "~/f" (no closing slash)
4538 ;; *will* be a runtime error, but this only *might* be
4539 ;; a runtime error, so we can't signal a full warning.
4540 ;; At absolute worst it should be a style-warning.
4541 (give-up-ir1-transform "~~// directive mentions unknown package")
4542 `(formatter ,control))))))
4543 `(lambda (dest control ,@arg-names)
4544 (declare (ignore control))
4545 (format dest ,expr ,@arg-names))))
4547 (deftransform format ((stream control &rest args) (stream function &rest t))
4548 (let ((arg-names (make-gensym-list (length args))))
4549 `(lambda (stream control ,@arg-names)
4550 (funcall control stream ,@arg-names)
4551 nil)))
4553 (deftransform format ((tee control &rest args) ((member t) function &rest t))
4554 (let ((arg-names (make-gensym-list (length args))))
4555 `(lambda (tee control ,@arg-names)
4556 (declare (ignore tee))
4557 (funcall control *standard-output* ,@arg-names)
4558 nil)))
4560 (deftransform format ((stream control &rest args) (null function &rest t))
4561 (let ((arg-names (make-gensym-list (length args))))
4562 `(lambda (stream control ,@arg-names)
4563 (declare (ignore stream))
4564 (with-simple-output-to-string (stream)
4565 (funcall control stream ,@arg-names)))))
4567 (defun concatenate-format-p (control args)
4568 (and
4569 (loop for directive in control
4570 always
4571 (or (stringp directive)
4572 (and (sb!format::format-directive-p directive)
4573 (let ((char (sb!format::format-directive-character directive))
4574 (params (sb!format::format-directive-params directive)))
4576 (and
4577 (char-equal char #\a)
4578 (null params)
4579 (pop args))
4580 (and
4581 (or (eql char #\~)
4582 (eql char #\%))
4583 (null (sb!format::format-directive-colonp directive))
4584 (null (sb!format::format-directive-atsignp directive))
4585 (or (null params)
4586 (typep params
4587 '(cons (cons (eql 1) unsigned-byte) null)))))))))
4588 (null args)))
4590 (deftransform format ((stream control &rest args) (null (constant-arg string) &rest string))
4591 (let ((tokenized
4592 (handler-case
4593 (sb!format::tokenize-control-string (lvar-value control))
4594 (sb!format:format-error ()
4595 (give-up-ir1-transform)))))
4596 (unless (concatenate-format-p tokenized args)
4597 (give-up-ir1-transform))
4598 (let ((arg-names (make-gensym-list (length args))))
4599 `(lambda (stream control ,@arg-names)
4600 (declare (ignore stream control)
4601 (ignorable ,@arg-names))
4602 (concatenate
4603 'string
4604 ,@(let ((strings
4605 (loop for directive in tokenized
4606 for char = (and (not (stringp directive))
4607 (sb!format::format-directive-character directive))
4608 when
4609 (cond ((not char)
4610 directive)
4611 ((char-equal char #\a)
4612 (let ((arg (pop args))
4613 (arg-name (pop arg-names)))
4615 (constant-lvar-p arg)
4616 (lvar-value arg)
4617 arg-name)))
4619 (let ((n (or (cdar (sb!format::format-directive-params directive))
4620 1)))
4621 (and (plusp n)
4622 (make-string n
4623 :initial-element
4624 (if (eql char #\%)
4625 #\Newline
4626 char))))))
4627 collect it)))
4628 ;; Join adjacent constant strings
4629 (loop with concat
4630 for (string . rest) on strings
4631 when (stringp string)
4632 do (setf concat
4633 (if concat
4634 (concatenate 'string concat string)
4635 string))
4636 else
4637 when concat collect (shiftf concat nil) end
4638 and collect string
4639 when (and concat (not rest))
4640 collect concat)))))))
4642 (deftransform pathname ((pathspec) (pathname) *)
4643 'pathspec)
4645 (deftransform pathname ((pathspec) (string) *)
4646 '(values (parse-namestring pathspec)))
4648 (macrolet
4649 ((def (name)
4650 `(defoptimizer (,name optimizer) ((control &rest args) node)
4651 (when (constant-lvar-p control)
4652 (let ((x (lvar-value control)))
4653 (when (stringp x)
4654 (let ((*compiler-error-context* node))
4655 (check-format-args x args ',name))))))))
4656 (def error)
4657 (def warn)
4658 #+sb-xc-host ; Only we should be using these
4659 (progn
4660 (def style-warn)
4661 (def compiler-error)
4662 (def compiler-warn)
4663 (def compiler-style-warn)
4664 (def compiler-notify)
4665 (def maybe-compiler-notify)
4666 (def bug)))
4668 (defoptimizer (cerror optimizer) ((report control &rest args))
4669 (when (and (constant-lvar-p control)
4670 (constant-lvar-p report))
4671 (let ((x (lvar-value control))
4672 (y (lvar-value report)))
4673 (when (and (stringp x) (stringp y))
4674 (multiple-value-bind (min1 max1)
4675 (handler-case
4676 (sb!format:%compiler-walk-format-string x args)
4677 (sb!format:format-error (c)
4678 (compiler-warn "~A" c)))
4679 (when min1
4680 (multiple-value-bind (min2 max2)
4681 (handler-case
4682 (sb!format:%compiler-walk-format-string y args)
4683 (sb!format:format-error (c)
4684 (compiler-warn "~A" c)))
4685 (when min2
4686 (let ((nargs (length args)))
4687 (cond
4688 ((< nargs (min min1 min2))
4689 (warn 'format-too-few-args-warning
4690 :format-control
4691 "Too few arguments (~D) to ~S ~S ~S: ~
4692 requires at least ~D."
4693 :format-arguments
4694 (list nargs 'cerror y x (min min1 min2))))
4695 ((> nargs (max max1 max2))
4696 (warn 'format-too-many-args-warning
4697 :format-control
4698 "Too many arguments (~D) to ~S ~S ~S: ~
4699 uses at most ~D."
4700 :format-arguments
4701 (list nargs 'cerror y x (max max1 max2))))))))))))))
4703 (defun constant-cons-type (type)
4704 (multiple-value-bind (singleton value)
4705 (type-singleton-p type)
4706 (if singleton
4707 (values value t)
4708 (typecase type
4709 (cons-type
4710 (multiple-value-bind (car car-good)
4711 (constant-cons-type (cons-type-car-type type))
4712 (multiple-value-bind (cdr cdr-good)
4713 (constant-cons-type (cons-type-cdr-type type))
4714 (and car-good cdr-good
4715 (values (cons car cdr) t)))))))))
4717 (defoptimizer (coerce derive-type) ((value type) node)
4718 (multiple-value-bind (type constant)
4719 (if (constant-lvar-p type)
4720 (values (lvar-value type) t)
4721 (constant-cons-type (lvar-type type)))
4722 (when constant
4723 ;; This branch is essentially (RESULT-TYPE-SPECIFIER-NTH-ARG 2),
4724 ;; but dealing with the niggle that complex canonicalization gets
4725 ;; in the way: (COERCE 1 'COMPLEX) returns 1, which is not of
4726 ;; type COMPLEX.
4727 (let ((result-typeoid (careful-specifier-type type)))
4728 (cond
4729 ((null result-typeoid) nil)
4730 ((csubtypep result-typeoid (specifier-type 'number))
4731 ;; the difficult case: we have to cope with ANSI 12.1.5.3
4732 ;; Rule of Canonical Representation for Complex Rationals,
4733 ;; which is a truly nasty delivery to field.
4734 (cond
4735 ((csubtypep result-typeoid (specifier-type 'real))
4736 ;; cleverness required here: it would be nice to deduce
4737 ;; that something of type (INTEGER 2 3) coerced to type
4738 ;; DOUBLE-FLOAT should return (DOUBLE-FLOAT 2.0d0 3.0d0).
4739 ;; FLOAT gets its own clause because it's implemented as
4740 ;; a UNION-TYPE, so we don't catch it in the NUMERIC-TYPE
4741 ;; logic below.
4742 result-typeoid)
4743 ((and (numeric-type-p result-typeoid)
4744 (eq (numeric-type-complexp result-typeoid) :real))
4745 ;; FIXME: is this clause (a) necessary or (b) useful?
4746 result-typeoid)
4747 ((or (csubtypep result-typeoid
4748 (specifier-type '(complex single-float)))
4749 (csubtypep result-typeoid
4750 (specifier-type '(complex double-float)))
4751 #!+long-float
4752 (csubtypep result-typeoid
4753 (specifier-type '(complex long-float))))
4754 ;; float complex types are never canonicalized.
4755 result-typeoid)
4757 ;; if it's not a REAL, or a COMPLEX FLOAToid, it's
4758 ;; probably just a COMPLEX or equivalent. So, in that
4759 ;; case, we will return a complex or an object of the
4760 ;; provided type if it's rational:
4761 (type-union result-typeoid
4762 (type-intersection (lvar-type value)
4763 (specifier-type 'rational))))))
4764 ;; At zero safety the deftransform for COERCE can elide dimension
4765 ;; checks for the things like (COERCE X '(SIMPLE-VECTOR 5)) -- so we
4766 ;; need to simplify the type to drop the dimension information.
4767 ((and (policy node (zerop safety))
4768 (csubtypep result-typeoid (specifier-type '(array * (*))))
4769 (simplify-vector-type result-typeoid)))
4771 result-typeoid))))))
4773 (defoptimizer (compile derive-type) ((nameoid function))
4774 (declare (ignore function))
4775 (when (csubtypep (lvar-type nameoid)
4776 (specifier-type 'null))
4777 (values-specifier-type '(values function boolean boolean))))
4779 ;;; FIXME: Maybe also STREAM-ELEMENT-TYPE should be given some loving
4780 ;;; treatment along these lines? (See discussion in COERCE DERIVE-TYPE
4781 ;;; optimizer, above).
4782 (defoptimizer (array-element-type derive-type) ((array))
4783 (let ((array-type (lvar-type array)))
4784 (labels ((consify (list)
4785 (if (endp list)
4786 '(eql nil)
4787 `(cons (eql ,(car list)) ,(consify (rest list)))))
4788 (get-element-type (a)
4789 (let ((element-type
4790 (type-specifier (array-type-specialized-element-type a))))
4791 (cond ((eq element-type '*)
4792 (specifier-type 'type-specifier))
4793 ((symbolp element-type)
4794 (make-eql-type element-type))
4795 ((consp element-type)
4796 (specifier-type (consify element-type)))
4798 (error "can't understand type ~S~%" element-type))))))
4799 (labels ((recurse (type)
4800 (cond ((array-type-p type)
4801 (get-element-type type))
4802 ((union-type-p type)
4803 (apply #'type-union
4804 (mapcar #'recurse (union-type-types type))))
4806 *universal-type*))))
4807 (recurse array-type)))))
4809 (define-source-transform sb!impl::sort-vector (vector start end predicate key)
4810 ;; Like CMU CL, we use HEAPSORT. However, other than that, this code
4811 ;; isn't really related to the CMU CL code, since instead of trying
4812 ;; to generalize the CMU CL code to allow START and END values, this
4813 ;; code has been written from scratch following Chapter 7 of
4814 ;; _Introduction to Algorithms_ by Corman, Rivest, and Shamir.
4815 `(macrolet ((%index (x) `(truly-the index ,x))
4816 (%parent (i) `(ash ,i -1))
4817 (%left (i) `(%index (ash ,i 1)))
4818 (%right (i) `(%index (1+ (ash ,i 1))))
4819 (%heapify (i)
4820 `(do* ((i ,i)
4821 (left (%left i) (%left i)))
4822 ((> left current-heap-size))
4823 (declare (type index i left))
4824 (let* ((i-elt (%elt i))
4825 (i-key (funcall keyfun i-elt))
4826 (left-elt (%elt left))
4827 (left-key (funcall keyfun left-elt)))
4828 (multiple-value-bind (large large-elt large-key)
4829 (if (funcall ,',predicate i-key left-key)
4830 (values left left-elt left-key)
4831 (values i i-elt i-key))
4832 (let ((right (%right i)))
4833 (multiple-value-bind (largest largest-elt)
4834 (if (> right current-heap-size)
4835 (values large large-elt)
4836 (let* ((right-elt (%elt right))
4837 (right-key (funcall keyfun right-elt)))
4838 (if (funcall ,',predicate large-key right-key)
4839 (values right right-elt)
4840 (values large large-elt))))
4841 (cond ((= largest i)
4842 (return))
4844 (setf (%elt i) largest-elt
4845 (%elt largest) i-elt
4846 i largest)))))))))
4847 (%sort-vector (keyfun &optional (vtype 'vector))
4848 `(macrolet (;; KLUDGE: In SBCL ca. 0.6.10, I had
4849 ;; trouble getting type inference to
4850 ;; propagate all the way through this
4851 ;; tangled mess of inlining. The TRULY-THE
4852 ;; here works around that. -- WHN
4853 (%elt (i)
4854 `(aref (truly-the ,',vtype ,',',vector)
4855 (%index (+ (%index ,i) start-1)))))
4856 (let (;; Heaps prefer 1-based addressing.
4857 (start-1 (1- ,',start))
4858 (current-heap-size (- ,',end ,',start))
4859 (keyfun ,keyfun))
4860 (declare (type (integer -1 #.(1- sb!xc:most-positive-fixnum))
4861 start-1))
4862 (declare (type index current-heap-size))
4863 (declare (type function keyfun))
4864 (loop for i of-type index
4865 from (ash current-heap-size -1) downto 1 do
4866 (%heapify i))
4867 (loop
4868 (when (< current-heap-size 2)
4869 (return))
4870 (rotatef (%elt 1) (%elt current-heap-size))
4871 (decf current-heap-size)
4872 (%heapify 1))))))
4873 (if (typep ,vector 'simple-vector)
4874 ;; (VECTOR T) is worth optimizing for, and SIMPLE-VECTOR is
4875 ;; what we get from (VECTOR T) inside WITH-ARRAY-DATA.
4876 (if (null ,key)
4877 ;; Special-casing the KEY=NIL case lets us avoid some
4878 ;; function calls.
4879 (%sort-vector #'identity simple-vector)
4880 (%sort-vector ,key simple-vector))
4881 ;; It's hard to anticipate many speed-critical applications for
4882 ;; sorting vector types other than (VECTOR T), so we just lump
4883 ;; them all together in one slow dynamically typed mess.
4884 (locally
4885 (declare (optimize (speed 2) (space 2) (inhibit-warnings 3)))
4886 (%sort-vector (or ,key #'identity))))))
4888 (deftransform sort ((list predicate &key key)
4889 (list * &rest t) *)
4890 `(sb!impl::stable-sort-list list
4891 (%coerce-callable-to-fun predicate)
4892 (if key (%coerce-callable-to-fun key) #'identity)))
4894 (deftransform stable-sort ((sequence predicate &key key)
4895 ((or vector list) *))
4896 (let ((sequence-type (lvar-type sequence)))
4897 (cond ((csubtypep sequence-type (specifier-type 'list))
4898 `(sb!impl::stable-sort-list sequence
4899 (%coerce-callable-to-fun predicate)
4900 (if key (%coerce-callable-to-fun key) #'identity)))
4901 ((csubtypep sequence-type (specifier-type 'simple-vector))
4902 `(sb!impl::stable-sort-simple-vector sequence
4903 (%coerce-callable-to-fun predicate)
4904 (and key (%coerce-callable-to-fun key))))
4906 `(sb!impl::stable-sort-vector sequence
4907 (%coerce-callable-to-fun predicate)
4908 (and key (%coerce-callable-to-fun key)))))))
4910 ;;;; debuggers' little helpers
4912 ;;; for debugging when transforms are behaving mysteriously,
4913 ;;; e.g. when debugging a problem with an ASH transform
4914 ;;; (defun foo (&optional s)
4915 ;;; (sb-c::/report-lvar s "S outside WHEN")
4916 ;;; (when (and (integerp s) (> s 3))
4917 ;;; (sb-c::/report-lvar s "S inside WHEN")
4918 ;;; (let ((bound (ash 1 (1- s))))
4919 ;;; (sb-c::/report-lvar bound "BOUND")
4920 ;;; (let ((x (- bound))
4921 ;;; (y (1- bound)))
4922 ;;; (sb-c::/report-lvar x "X")
4923 ;;; (sb-c::/report-lvar x "Y"))
4924 ;;; `(integer ,(- bound) ,(1- bound)))))
4925 ;;; (The DEFTRANSFORM doesn't do anything but report at compile time,
4926 ;;; and the function doesn't do anything at all.)
4927 #!+sb-show
4928 (progn
4929 (defknown /report-lvar (t t) null)
4930 (deftransform /report-lvar ((x message) (t t))
4931 (format t "~%/in /REPORT-LVAR~%")
4932 (format t "/(LVAR-TYPE X)=~S~%" (lvar-type x))
4933 (when (constant-lvar-p x)
4934 (format t "/(LVAR-VALUE X)=~S~%" (lvar-value x)))
4935 (format t "/MESSAGE=~S~%" (lvar-value message))
4936 (give-up-ir1-transform "not a real transform"))
4937 (defun /report-lvar (x message)
4938 (declare (ignore x message))))
4940 (deftransform encode-universal-time
4941 ((second minute hour date month year &optional time-zone)
4942 ((constant-arg (mod 60)) (constant-arg (mod 60))
4943 (constant-arg (mod 24))
4944 (constant-arg (integer 1 31))
4945 (constant-arg (integer 1 12))
4946 (constant-arg (integer 1899))
4947 (constant-arg (rational -24 24))))
4948 (let ((second (lvar-value second))
4949 (minute (lvar-value minute))
4950 (hour (lvar-value hour))
4951 (date (lvar-value date))
4952 (month (lvar-value month))
4953 (year (lvar-value year))
4954 (time-zone (lvar-value time-zone)))
4955 (if (zerop (rem time-zone 1/3600))
4956 (encode-universal-time second minute hour date month year time-zone)
4957 (give-up-ir1-transform))))
4959 #!-(and win32 (not sb-thread))
4960 (deftransform sleep ((seconds) ((integer 0 #.(expt 10 8))))
4961 `(sb!unix:nanosleep seconds 0))
4963 #!-(and win32 (not sb-thread))
4964 (deftransform sleep ((seconds) ((constant-arg (real 0))))
4965 (let ((seconds-value (lvar-value seconds)))
4966 (multiple-value-bind (seconds nano)
4967 (sb!impl::split-seconds-for-sleep seconds-value)
4968 (if (> seconds (expt 10 8))
4969 (give-up-ir1-transform)
4970 `(sb!unix:nanosleep ,seconds ,nano)))))
4972 ;; On 64-bit architectures the TLS index is in the symbol header,
4973 ;; !DEFINE-PRIMITIVE-OBJECT doesn't define an accessor for it.
4974 ;; In the architectures where tls-index is an ordinary slot holding a tagged
4975 ;; object, it represents the byte offset to an aligned object and looks
4976 ;; in Lisp like a fixnum that is off by a factor of (EXPT 2 N-FIXNUM-TAG-BITS).
4977 ;; We're reading with a raw SAP accessor, so must make it look equally "off".
4978 ;; Also we don't get the defknown automatically.
4979 #!+(and 64-bit sb-thread)
4980 (defknown symbol-tls-index (t) fixnum (flushable))
4981 #!+(and 64-bit sb-thread)
4982 (define-source-transform symbol-tls-index (sym)
4983 `(ash (sap-ref-32 (int-sap (get-lisp-obj-address (the symbol ,sym)))
4984 (- 4 sb!vm:other-pointer-lowtag))
4985 (- sb!vm:n-fixnum-tag-bits)))
4987 (deftransform make-string-output-stream ((&key element-type))
4988 (let ((element-type (cond ((not element-type)
4989 'character)
4990 ((constant-lvar-p element-type)
4991 (let ((specifier (careful-specifier-type (lvar-value element-type))))
4992 (and (csubtypep specifier (specifier-type 'character))
4993 (type-specifier specifier)))))))
4994 (if element-type
4995 `(sb!impl::%make-string-output-stream
4996 ',element-type
4997 (function ,(case element-type
4998 (base-char 'sb!impl::string-ouch/base-char)
4999 (t 'sb!impl::string-ouch))))
5000 (give-up-ir1-transform))))
5002 (flet ((xform (symbol match-kind fallback)
5003 (when (constant-lvar-p symbol)
5004 (let* ((symbol (lvar-value symbol))
5005 (kind (info :variable :kind symbol))
5006 (state (deprecated-thing-p 'variable symbol)))
5007 (when state
5008 (check-deprecated-thing 'variable symbol)
5009 (case state
5010 ((:early :late)
5011 (unless (gethash symbol *free-vars*)
5012 (setf (gethash symbol *free-vars*) :deprecated)))))
5013 ;; :global in the test below is redundant if match-kind is :global
5014 ;; but it's harmless and a convenient way to express this.
5015 ;; Note that some 3rd-party libraries use variations on DEFCONSTANT
5016 ;; expanding into expressions such as:
5017 ;; (CL:DEFCONSTANT S (IF (BOUNDP 'S) (SYMBOL-VALUE 'S) (COMPUTE)))
5018 ;; which means we have to use care if S in for-evaluation position would
5019 ;; be converted to (LOAD-TIME-VALUE (SYMBOL-VALUE 'S)).
5020 ;; When S's value is directly dumpable, it works fine, but otherwise
5021 ;; it's dangerous. If the user wishes to avoid eager evaluation entirely,
5022 ;; a local notinline declaration on SYMBOL-VALUE will do.
5023 (when (or (eq kind match-kind)
5024 (eq kind :global)
5025 (and (eq kind :constant)
5026 (boundp symbol)
5027 (typep (symbol-value symbol) '(or number character symbol))))
5028 (return-from xform symbol))))
5029 fallback))
5030 (deftransform symbol-global-value ((symbol))
5031 (xform symbol :global `(sym-global-val symbol)))
5032 (deftransform symbol-value ((symbol))
5033 (xform symbol :special `(symeval symbol))))
5035 (flet ((xform (symbol match-kind)
5036 (let* ((symbol (lvar-value symbol))
5037 (kind (info :variable :kind symbol)))
5038 (if (or (eq kind match-kind) (memq kind '(:constant :global))) ; as above
5039 `(setq ,symbol value)
5040 (give-up-ir1-transform)))))
5041 (deftransform set-symbol-global-value ((symbol value) ((constant-arg symbol) *))
5042 (xform symbol :global))
5043 (deftransform set ((symbol value) ((constant-arg symbol) *))
5044 (xform symbol :special)))
5046 (deftransforms (prin1-to-string princ-to-string) ((object) (number))
5047 `(stringify-object object))