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