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