1.0.18.2: more conservative interval artihmetic
[sbcl.git] / src / code / numbers.lisp
1 ;;;; This file contains the definitions of most number functions.
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!KERNEL")
13 \f
14 ;;;; the NUMBER-DISPATCH macro
15
16 (eval-when (:compile-toplevel :load-toplevel :execute)
17
18 ;;; Grovel an individual case to NUMBER-DISPATCH, augmenting RESULT
19 ;;; with the type dispatches and bodies. Result is a tree built of
20 ;;; alists representing the dispatching off each arg (in order). The
21 ;;; leaf is the body to be executed in that case.
22 (defun parse-number-dispatch (vars result types var-types body)
23   (cond ((null vars)
24          (unless (null types) (error "More types than vars."))
25          (when (cdr result)
26            (error "Duplicate case: ~S." body))
27          (setf (cdr result)
28                (sublis var-types body :test #'equal)))
29         ((null types)
30          (error "More vars than types."))
31         (t
32          (flet ((frob (var type)
33                   (parse-number-dispatch
34                    (rest vars)
35                    (or (assoc type (cdr result) :test #'equal)
36                        (car (setf (cdr result)
37                                   (acons type nil (cdr result)))))
38                    (rest types)
39                    (acons `(dispatch-type ,var) type var-types)
40                    body)))
41            (let ((type (first types))
42                  (var (first vars)))
43              (if (and (consp type) (eq (first type) 'foreach))
44                  (dolist (type (rest type))
45                    (frob var type))
46                  (frob var type)))))))
47
48 ;;; our guess for the preferred order in which to do type tests
49 ;;; (cheaper and/or more probable first.)
50 (defparameter *type-test-ordering*
51   '(fixnum single-float double-float integer #!+long-float long-float bignum
52     complex ratio))
53
54 ;;; Should TYPE1 be tested before TYPE2?
55 (defun type-test-order (type1 type2)
56   (let ((o1 (position type1 *type-test-ordering*))
57         (o2 (position type2 *type-test-ordering*)))
58     (cond ((not o1) nil)
59           ((not o2) t)
60           (t
61            (< o1 o2)))))
62
63 ;;; Return an ETYPECASE form that does the type dispatch, ordering the
64 ;;; cases for efficiency.
65 (defun generate-number-dispatch (vars error-tags cases)
66   (if vars
67       (let ((var (first vars))
68             (cases (sort cases #'type-test-order :key #'car)))
69         `((typecase ,var
70             ,@(mapcar (lambda (case)
71                         `(,(first case)
72                           ,@(generate-number-dispatch (rest vars)
73                                                       (rest error-tags)
74                                                       (cdr case))))
75                       cases)
76             (t (go ,(first error-tags))))))
77       cases))
78
79 ) ; EVAL-WHEN
80
81 ;;; This is a vaguely case-like macro that does number cross-product
82 ;;; dispatches. The Vars are the variables we are dispatching off of.
83 ;;; The Type paired with each Var is used in the error message when no
84 ;;; case matches. Each case specifies a Type for each var, and is
85 ;;; executed when that signature holds. A type may be a list
86 ;;; (FOREACH Each-Type*), causing that case to be repeatedly
87 ;;; instantiated for every Each-Type. In the body of each case, any
88 ;;; list of the form (DISPATCH-TYPE Var-Name) is substituted with the
89 ;;; type of that var in that instance of the case.
90 ;;;
91 ;;; As an alternate to a case spec, there may be a form whose CAR is a
92 ;;; symbol. In this case, we apply the CAR of the form to the CDR and
93 ;;; treat the result of the call as a list of cases. This process is
94 ;;; not applied recursively.
95 (defmacro number-dispatch (var-specs &body cases)
96   (let ((res (list nil))
97         (vars (mapcar #'car var-specs))
98         (block (gensym)))
99     (dolist (case cases)
100       (if (symbolp (first case))
101           (let ((cases (apply (symbol-function (first case)) (rest case))))
102             (dolist (case cases)
103               (parse-number-dispatch vars res (first case) nil (rest case))))
104           (parse-number-dispatch vars res (first case) nil (rest case))))
105
106     (collect ((errors)
107               (error-tags))
108       (dolist (spec var-specs)
109         (let ((var (first spec))
110               (type (second spec))
111               (tag (gensym)))
112           (error-tags tag)
113           (errors tag)
114           (errors `(return-from
115                     ,block
116                     (error 'simple-type-error :datum ,var
117                            :expected-type ',type
118                            :format-control
119                            "~@<Argument ~A is not a ~S: ~2I~_~S~:>"
120                            :format-arguments
121                            (list ',var ',type ,var))))))
122
123       `(block ,block
124          (tagbody
125            (return-from ,block
126                         ,@(generate-number-dispatch vars (error-tags)
127                                                     (cdr res)))
128            ,@(errors))))))
129 \f
130 ;;;; binary operation dispatching utilities
131
132 (eval-when (:compile-toplevel :execute)
133
134 ;;; Return NUMBER-DISPATCH forms for rational X float.
135 (defun float-contagion (op x y &optional (rat-types '(fixnum bignum ratio)))
136   `(((single-float single-float) (,op ,x ,y))
137     (((foreach ,@rat-types)
138       (foreach single-float double-float #!+long-float long-float))
139      (,op (coerce ,x '(dispatch-type ,y)) ,y))
140     (((foreach single-float double-float #!+long-float long-float)
141       (foreach ,@rat-types))
142      (,op ,x (coerce ,y '(dispatch-type ,x))))
143     #!+long-float
144     (((foreach single-float double-float long-float) long-float)
145      (,op (coerce ,x 'long-float) ,y))
146     #!+long-float
147     ((long-float (foreach single-float double-float))
148      (,op ,x (coerce ,y 'long-float)))
149     (((foreach single-float double-float) double-float)
150      (,op (coerce ,x 'double-float) ,y))
151     ((double-float single-float)
152      (,op ,x (coerce ,y 'double-float)))))
153
154 ;;; Return NUMBER-DISPATCH forms for bignum X fixnum.
155 (defun bignum-cross-fixnum (fix-op big-op)
156   `(((fixnum fixnum) (,fix-op x y))
157     ((fixnum bignum)
158      (,big-op (make-small-bignum x) y))
159     ((bignum fixnum)
160      (,big-op x (make-small-bignum y)))
161     ((bignum bignum)
162      (,big-op x y))))
163
164 ) ; EVAL-WHEN
165 \f
166 ;;;; canonicalization utilities
167
168 ;;; If IMAGPART is 0, return REALPART, otherwise make a complex. This is
169 ;;; used when we know that REALPART and IMAGPART are the same type, but
170 ;;; rational canonicalization might still need to be done.
171 #!-sb-fluid (declaim (inline canonical-complex))
172 (defun canonical-complex (realpart imagpart)
173   (if (eql imagpart 0)
174       realpart
175       (cond #!+long-float
176             ((and (typep realpart 'long-float)
177                   (typep imagpart 'long-float))
178              (truly-the (complex long-float) (complex realpart imagpart)))
179             ((and (typep realpart 'double-float)
180                   (typep imagpart 'double-float))
181              (truly-the (complex double-float) (complex realpart imagpart)))
182             ((and (typep realpart 'single-float)
183                   (typep imagpart 'single-float))
184              (truly-the (complex single-float) (complex realpart imagpart)))
185             (t
186              (%make-complex realpart imagpart)))))
187
188 ;;; Given a numerator and denominator with the GCD already divided
189 ;;; out, make a canonical rational. We make the denominator positive,
190 ;;; and check whether it is 1.
191 #!-sb-fluid (declaim (inline build-ratio))
192 (defun build-ratio (num den)
193   (multiple-value-bind (num den)
194       (if (minusp den)
195           (values (- num) (- den))
196           (values num den))
197     (cond
198       ((eql den 0)
199        (error 'division-by-zero
200               :operands (list num den)
201               :operation 'build-ratio))
202       ((eql den 1) num)
203       (t (%make-ratio num den)))))
204
205 ;;; Truncate X and Y, but bum the case where Y is 1.
206 #!-sb-fluid (declaim (inline maybe-truncate))
207 (defun maybe-truncate (x y)
208   (if (eql y 1)
209       x
210       (truncate x y)))
211 \f
212 ;;;; COMPLEXes
213
214 (defun complex (realpart &optional (imagpart 0))
215   #!+sb-doc
216   "Return a complex number with the specified real and imaginary components."
217   (flet ((%%make-complex (realpart imagpart)
218            (cond #!+long-float
219                  ((and (typep realpart 'long-float)
220                        (typep imagpart 'long-float))
221                   (truly-the (complex long-float)
222                              (complex realpart imagpart)))
223                  ((and (typep realpart 'double-float)
224                        (typep imagpart 'double-float))
225                   (truly-the (complex double-float)
226                              (complex realpart imagpart)))
227                  ((and (typep realpart 'single-float)
228                        (typep imagpart 'single-float))
229                   (truly-the (complex single-float)
230                              (complex realpart imagpart)))
231                  (t
232                   (%make-complex realpart imagpart)))))
233   (number-dispatch ((realpart real) (imagpart real))
234     ((rational rational)
235      (canonical-complex realpart imagpart))
236     (float-contagion %%make-complex realpart imagpart (rational)))))
237
238 (defun realpart (number)
239   #!+sb-doc
240   "Extract the real part of a number."
241   (typecase number
242     #!+long-float
243     ((complex long-float)
244      (truly-the long-float (realpart number)))
245     ((complex double-float)
246      (truly-the double-float (realpart number)))
247     ((complex single-float)
248      (truly-the single-float (realpart number)))
249     ((complex rational)
250      (sb!kernel:%realpart number))
251     (t
252      number)))
253
254 (defun imagpart (number)
255   #!+sb-doc
256   "Extract the imaginary part of a number."
257   (typecase number
258     #!+long-float
259     ((complex long-float)
260      (truly-the long-float (imagpart number)))
261     ((complex double-float)
262      (truly-the double-float (imagpart number)))
263     ((complex single-float)
264      (truly-the single-float (imagpart number)))
265     ((complex rational)
266      (sb!kernel:%imagpart number))
267     (float
268      (* 0 number))
269     (t
270      0)))
271
272 (defun conjugate (number)
273   #!+sb-doc
274   "Return the complex conjugate of NUMBER. For non-complex numbers, this is
275   an identity."
276   (if (complexp number)
277       (complex (realpart number) (- (imagpart number)))
278       number))
279
280 (defun signum (number)
281   #!+sb-doc
282   "If NUMBER is zero, return NUMBER, else return (/ NUMBER (ABS NUMBER))."
283   (if (zerop number)
284       number
285       (if (rationalp number)
286           (if (plusp number) 1 -1)
287           (/ number (abs number)))))
288 \f
289 ;;;; ratios
290
291 (defun numerator (number)
292   #!+sb-doc
293   "Return the numerator of NUMBER, which must be rational."
294   (numerator number))
295
296 (defun denominator (number)
297   #!+sb-doc
298   "Return the denominator of NUMBER, which must be rational."
299   (denominator number))
300 \f
301 ;;;; arithmetic operations
302
303 (macrolet ((define-arith (op init doc)
304              #!-sb-doc (declare (ignore doc))
305              `(defun ,op (&rest args)
306                 #!+sb-doc ,doc
307                 (if (null args) ,init
308                     (do ((args (cdr args) (cdr args))
309                          (result (car args) (,op result (car args))))
310                         ((null args) result)
311                       ;; to signal TYPE-ERROR when exactly 1 arg of wrong type:
312                       (declare (type number result)))))))
313   (define-arith + 0
314     "Return the sum of its arguments. With no args, returns 0.")
315   (define-arith * 1
316     "Return the product of its arguments. With no args, returns 1."))
317
318 (defun - (number &rest more-numbers)
319   #!+sb-doc
320   "Subtract the second and all subsequent arguments from the first;
321   or with one argument, negate the first argument."
322   (if more-numbers
323       (do ((nlist more-numbers (cdr nlist))
324            (result number))
325           ((atom nlist) result)
326          (declare (list nlist))
327          (setq result (- result (car nlist))))
328       (- number)))
329
330 (defun / (number &rest more-numbers)
331   #!+sb-doc
332   "Divide the first argument by each of the following arguments, in turn.
333   With one argument, return reciprocal."
334   (if more-numbers
335       (do ((nlist more-numbers (cdr nlist))
336            (result number))
337           ((atom nlist) result)
338          (declare (list nlist))
339          (setq result (/ result (car nlist))))
340       (/ number)))
341
342 (defun 1+ (number)
343   #!+sb-doc
344   "Return NUMBER + 1."
345   (1+ number))
346
347 (defun 1- (number)
348   #!+sb-doc
349   "Return NUMBER - 1."
350   (1- number))
351
352 (eval-when (:compile-toplevel)
353
354 (sb!xc:defmacro two-arg-+/- (name op big-op)
355   `(defun ,name (x y)
356      (number-dispatch ((x number) (y number))
357        (bignum-cross-fixnum ,op ,big-op)
358        (float-contagion ,op x y)
359
360        ((complex complex)
361         (canonical-complex (,op (realpart x) (realpart y))
362                            (,op (imagpart x) (imagpart y))))
363        (((foreach bignum fixnum ratio single-float double-float
364                   #!+long-float long-float) complex)
365         (complex (,op x (realpart y)) (,op (imagpart y))))
366        ((complex (or rational float))
367         (complex (,op (realpart x) y) (imagpart x)))
368
369        (((foreach fixnum bignum) ratio)
370         (let* ((dy (denominator y))
371                (n (,op (* x dy) (numerator y))))
372           (%make-ratio n dy)))
373        ((ratio integer)
374         (let* ((dx (denominator x))
375                (n (,op (numerator x) (* y dx))))
376           (%make-ratio n dx)))
377        ((ratio ratio)
378         (let* ((nx (numerator x))
379                (dx (denominator x))
380                (ny (numerator y))
381                (dy (denominator y))
382                (g1 (gcd dx dy)))
383           (if (eql g1 1)
384               (%make-ratio (,op (* nx dy) (* dx ny)) (* dx dy))
385               (let* ((t1 (,op (* nx (truncate dy g1)) (* (truncate dx g1) ny)))
386                      (g2 (gcd t1 g1))
387                      (t2 (truncate dx g1)))
388                 (cond ((eql t1 0) 0)
389                       ((eql g2 1)
390                        (%make-ratio t1 (* t2 dy)))
391                       (t (let* ((nn (truncate t1 g2))
392                                 (t3 (truncate dy g2))
393                                 (nd (if (eql t2 1) t3 (* t2 t3))))
394                            (if (eql nd 1) nn (%make-ratio nn nd))))))))))))
395
396 ) ; EVAL-WHEN
397
398 (two-arg-+/- two-arg-+ + add-bignums)
399 (two-arg-+/- two-arg-- - subtract-bignum)
400
401 (defun two-arg-* (x y)
402   (flet ((integer*ratio (x y)
403            (if (eql x 0) 0
404                (let* ((ny (numerator y))
405                       (dy (denominator y))
406                       (gcd (gcd x dy)))
407                  (if (eql gcd 1)
408                      (%make-ratio (* x ny) dy)
409                      (let ((nn (* (truncate x gcd) ny))
410                            (nd (truncate dy gcd)))
411                        (if (eql nd 1)
412                            nn
413                            (%make-ratio nn nd)))))))
414          (complex*real (x y)
415            (canonical-complex (* (realpart x) y) (* (imagpart x) y))))
416     (number-dispatch ((x number) (y number))
417       (float-contagion * x y)
418
419       ((fixnum fixnum) (multiply-fixnums x y))
420       ((bignum fixnum) (multiply-bignum-and-fixnum x y))
421       ((fixnum bignum) (multiply-bignum-and-fixnum y x))
422       ((bignum bignum) (multiply-bignums x y))
423
424       ((complex complex)
425        (let* ((rx (realpart x))
426               (ix (imagpart x))
427               (ry (realpart y))
428               (iy (imagpart y)))
429          (canonical-complex (- (* rx ry) (* ix iy)) (+ (* rx iy) (* ix ry)))))
430       (((foreach bignum fixnum ratio single-float double-float
431                  #!+long-float long-float)
432         complex)
433        (complex*real y x))
434       ((complex (or rational float))
435        (complex*real x y))
436
437       (((foreach bignum fixnum) ratio) (integer*ratio x y))
438       ((ratio integer) (integer*ratio y x))
439       ((ratio ratio)
440        (let* ((nx (numerator x))
441               (dx (denominator x))
442               (ny (numerator y))
443               (dy (denominator y))
444               (g1 (gcd nx dy))
445               (g2 (gcd dx ny)))
446          (build-ratio (* (maybe-truncate nx g1)
447                          (maybe-truncate ny g2))
448                       (* (maybe-truncate dx g2)
449                          (maybe-truncate dy g1))))))))
450
451 ;;; Divide two integers, producing a canonical rational. If a fixnum,
452 ;;; we see whether they divide evenly before trying the GCD. In the
453 ;;; bignum case, we don't bother, since bignum division is expensive,
454 ;;; and the test is not very likely to succeed.
455 (defun integer-/-integer (x y)
456   (if (and (typep x 'fixnum) (typep y 'fixnum))
457       (multiple-value-bind (quo rem) (truncate x y)
458         (if (zerop rem)
459             quo
460             (let ((gcd (gcd x y)))
461               (declare (fixnum gcd))
462               (if (eql gcd 1)
463                   (build-ratio x y)
464                   (build-ratio (truncate x gcd) (truncate y gcd))))))
465       (let ((gcd (gcd x y)))
466         (if (eql gcd 1)
467             (build-ratio x y)
468             (build-ratio (truncate x gcd) (truncate y gcd))))))
469
470 (defun two-arg-/ (x y)
471   (number-dispatch ((x number) (y number))
472     (float-contagion / x y (ratio integer))
473
474     ((complex complex)
475      (let* ((rx (realpart x))
476             (ix (imagpart x))
477             (ry (realpart y))
478             (iy (imagpart y)))
479        (if (> (abs ry) (abs iy))
480            (let* ((r (/ iy ry))
481                   (dn (* ry (+ 1 (* r r)))))
482              (canonical-complex (/ (+ rx (* ix r)) dn)
483                                 (/ (- ix (* rx r)) dn)))
484            (let* ((r (/ ry iy))
485                   (dn (* iy (+ 1 (* r r)))))
486              (canonical-complex (/ (+ (* rx r) ix) dn)
487                                 (/ (- (* ix r) rx) dn))))))
488     (((foreach integer ratio single-float double-float) complex)
489      (let* ((ry (realpart y))
490             (iy (imagpart y)))
491        (if (> (abs ry) (abs iy))
492            (let* ((r (/ iy ry))
493                   (dn (* ry (+ 1 (* r r)))))
494              (canonical-complex (/ x dn)
495                                 (/ (- (* x r)) dn)))
496            (let* ((r (/ ry iy))
497                   (dn (* iy (+ 1 (* r r)))))
498              (canonical-complex (/ (* x r) dn)
499                                 (/ (- x) dn))))))
500     ((complex (or rational float))
501      (canonical-complex (/ (realpart x) y)
502                         (/ (imagpart x) y)))
503
504     ((ratio ratio)
505      (let* ((nx (numerator x))
506             (dx (denominator x))
507             (ny (numerator y))
508             (dy (denominator y))
509             (g1 (gcd nx ny))
510             (g2 (gcd dx dy)))
511        (build-ratio (* (maybe-truncate nx g1) (maybe-truncate dy g2))
512                     (* (maybe-truncate dx g2) (maybe-truncate ny g1)))))
513
514     ((integer integer)
515      (integer-/-integer x y))
516
517     ((integer ratio)
518      (if (zerop x)
519          0
520          (let* ((ny (numerator y))
521                 (dy (denominator y))
522                 (gcd (gcd x ny)))
523            (build-ratio (* (maybe-truncate x gcd) dy)
524                         (maybe-truncate ny gcd)))))
525
526     ((ratio integer)
527      (let* ((nx (numerator x))
528             (gcd (gcd nx y)))
529        (build-ratio (maybe-truncate nx gcd)
530                     (* (maybe-truncate y gcd) (denominator x)))))))
531
532 (defun %negate (n)
533   (number-dispatch ((n number))
534     (((foreach fixnum single-float double-float #!+long-float long-float))
535      (%negate n))
536     ((bignum)
537      (negate-bignum n))
538     ((ratio)
539      (%make-ratio (- (numerator n)) (denominator n)))
540     ((complex)
541      (complex (- (realpart n)) (- (imagpart n))))))
542 \f
543 ;;;; TRUNCATE and friends
544
545 (defun truncate (number &optional (divisor 1))
546   #!+sb-doc
547   "Return number (or number/divisor) as an integer, rounded toward 0.
548   The second returned value is the remainder."
549   (macrolet ((truncate-float (rtype)
550                `(let* ((float-div (coerce divisor ',rtype))
551                        (res (%unary-truncate (/ number float-div))))
552                   (values res
553                           (- number
554                              (* (coerce res ',rtype) float-div))))))
555     (number-dispatch ((number real) (divisor real))
556       ((fixnum fixnum) (truncate number divisor))
557       (((foreach fixnum bignum) ratio)
558        (let ((q (truncate (* number (denominator divisor))
559                           (numerator divisor))))
560          (values q (- number (* q divisor)))))
561       ((fixnum bignum)
562        (bignum-truncate (make-small-bignum number) divisor))
563       ((ratio (or float rational))
564        (let ((q (truncate (numerator number)
565                           (* (denominator number) divisor))))
566          (values q (- number (* q divisor)))))
567       ((bignum fixnum)
568        (bignum-truncate number (make-small-bignum divisor)))
569       ((bignum bignum)
570        (bignum-truncate number divisor))
571
572       (((foreach single-float double-float #!+long-float long-float)
573         (or rational single-float))
574        (if (eql divisor 1)
575            (let ((res (%unary-truncate number)))
576              (values res (- number (coerce res '(dispatch-type number)))))
577            (truncate-float (dispatch-type number))))
578       #!+long-float
579       ((long-float (or single-float double-float long-float))
580        (truncate-float long-float))
581       #!+long-float
582       (((foreach double-float single-float) long-float)
583        (truncate-float long-float))
584       ((double-float (or single-float double-float))
585        (truncate-float double-float))
586       ((single-float double-float)
587        (truncate-float double-float))
588       (((foreach fixnum bignum ratio)
589         (foreach single-float double-float #!+long-float long-float))
590        (truncate-float (dispatch-type divisor))))))
591
592 ;;; Declare these guys inline to let them get optimized a little.
593 ;;; ROUND and FROUND are not declared inline since they seem too
594 ;;; obscure and too big to inline-expand by default. Also, this gives
595 ;;; the compiler a chance to pick off the unary float case. Similarly,
596 ;;; CEILING and FLOOR are only maybe-inline for now, so that the
597 ;;; power-of-2 CEILING and FLOOR transforms get a chance.
598 #!-sb-fluid (declaim (inline rem mod fceiling ffloor ftruncate))
599 (declaim (maybe-inline ceiling floor))
600
601 (defun floor (number &optional (divisor 1))
602   #!+sb-doc
603   "Return the greatest integer not greater than number, or number/divisor.
604   The second returned value is (mod number divisor)."
605   ;; If the numbers do not divide exactly and the result of
606   ;; (/ NUMBER DIVISOR) would be negative then decrement the quotient
607   ;; and augment the remainder by the divisor.
608   (multiple-value-bind (tru rem) (truncate number divisor)
609     (if (and (not (zerop rem))
610              (if (minusp divisor)
611                  (plusp number)
612                  (minusp number)))
613         (values (1- tru) (+ rem divisor))
614         (values tru rem))))
615
616 (defun ceiling (number &optional (divisor 1))
617   #!+sb-doc
618   "Return the smallest integer not less than number, or number/divisor.
619   The second returned value is the remainder."
620   ;; If the numbers do not divide exactly and the result of
621   ;; (/ NUMBER DIVISOR) would be positive then increment the quotient
622   ;; and decrement the remainder by the divisor.
623   (multiple-value-bind (tru rem) (truncate number divisor)
624     (if (and (not (zerop rem))
625              (if (minusp divisor)
626                  (minusp number)
627                  (plusp number)))
628         (values (+ tru 1) (- rem divisor))
629         (values tru rem))))
630
631 (defun round (number &optional (divisor 1))
632   #!+sb-doc
633   "Rounds number (or number/divisor) to nearest integer.
634   The second returned value is the remainder."
635   (if (eql divisor 1)
636       (round number)
637       (multiple-value-bind (tru rem) (truncate number divisor)
638         (if (zerop rem)
639             (values tru rem)
640             (let ((thresh (/ (abs divisor) 2)))
641               (cond ((or (> rem thresh)
642                          (and (= rem thresh) (oddp tru)))
643                      (if (minusp divisor)
644                          (values (- tru 1) (+ rem divisor))
645                          (values (+ tru 1) (- rem divisor))))
646                     ((let ((-thresh (- thresh)))
647                        (or (< rem -thresh)
648                            (and (= rem -thresh) (oddp tru))))
649                      (if (minusp divisor)
650                          (values (+ tru 1) (- rem divisor))
651                          (values (- tru 1) (+ rem divisor))))
652                     (t (values tru rem))))))))
653
654 (defun rem (number divisor)
655   #!+sb-doc
656   "Return second result of TRUNCATE."
657   (multiple-value-bind (tru rem) (truncate number divisor)
658     (declare (ignore tru))
659     rem))
660
661 (defun mod (number divisor)
662   #!+sb-doc
663   "Return second result of FLOOR."
664   (let ((rem (rem number divisor)))
665     (if (and (not (zerop rem))
666              (if (minusp divisor)
667                  (plusp number)
668                  (minusp number)))
669         (+ rem divisor)
670         rem)))
671
672 (defmacro !define-float-rounding-function (name op doc)
673   `(defun ,name (number &optional (divisor 1))
674     ,doc
675     (multiple-value-bind (res rem) (,op number divisor)
676       (values (float res (if (floatp rem) rem 1.0)) rem))))
677
678 (defun ftruncate (number &optional (divisor 1))
679   #!+sb-doc
680   "Same as TRUNCATE, but returns first value as a float."
681   (macrolet ((ftruncate-float (rtype)
682                `(let* ((float-div (coerce divisor ',rtype))
683                        (res (%unary-ftruncate (/ number float-div))))
684                   (values res
685                           (- number
686                              (* (coerce res ',rtype) float-div))))))
687     (number-dispatch ((number real) (divisor real))
688       (((foreach fixnum bignum ratio) (or fixnum bignum ratio))
689        (multiple-value-bind (q r)
690            (truncate number divisor)
691          (values (float q) r)))
692       (((foreach single-float double-float #!+long-float long-float)
693         (or rational single-float))
694        (if (eql divisor 1)
695            (let ((res (%unary-ftruncate number)))
696              (values res (- number (coerce res '(dispatch-type number)))))
697            (ftruncate-float (dispatch-type number))))
698       #!+long-float
699       ((long-float (or single-float double-float long-float))
700        (ftruncate-float long-float))
701       #!+long-float
702       (((foreach double-float single-float) long-float)
703        (ftruncate-float long-float))
704       ((double-float (or single-float double-float))
705        (ftruncate-float double-float))
706       ((single-float double-float)
707        (ftruncate-float double-float))
708       (((foreach fixnum bignum ratio)
709         (foreach single-float double-float #!+long-float long-float))
710        (ftruncate-float (dispatch-type divisor))))))
711
712 (defun ffloor (number &optional (divisor 1))
713   "Same as FLOOR, but returns first value as a float."
714   (multiple-value-bind (tru rem) (ftruncate number divisor)
715     (if (and (not (zerop rem))
716              (if (minusp divisor)
717                  (plusp number)
718                  (minusp number)))
719         (values (1- tru) (+ rem divisor))
720         (values tru rem))))
721
722 (defun fceiling (number &optional (divisor 1))
723   "Same as CEILING, but returns first value as a float."
724   (multiple-value-bind (tru rem) (ftruncate number divisor)
725     (if (and (not (zerop rem))
726              (if (minusp divisor)
727                  (minusp number)
728                  (plusp number)))
729         (values (+ tru 1) (- rem divisor))
730         (values tru rem))))
731
732 ;;; FIXME: this probably needs treatment similar to the use of
733 ;;; %UNARY-FTRUNCATE for FTRUNCATE.
734 (defun fround (number &optional (divisor 1))
735   "Same as ROUND, but returns first value as a float."
736   (multiple-value-bind (res rem)
737       (round number divisor)
738     (values (float res (if (floatp rem) rem 1.0)) rem)))
739 \f
740 ;;;; comparisons
741
742 (defun = (number &rest more-numbers)
743   #!+sb-doc
744   "Return T if all of its arguments are numerically equal, NIL otherwise."
745   (declare (dynamic-extent more-numbers))
746   (the number number)
747   (do ((nlist more-numbers (cdr nlist)))
748       ((atom nlist) t)
749      (declare (list nlist))
750      (if (not (= (car nlist) number)) (return nil))))
751
752 (defun /= (number &rest more-numbers)
753   #!+sb-doc
754   "Return T if no two of its arguments are numerically equal, NIL otherwise."
755   (declare (dynamic-extent more-numbers))
756   (do* ((head (the number number) (car nlist))
757         (nlist more-numbers (cdr nlist)))
758        ((atom nlist) t)
759      (declare (list nlist))
760      (unless (do* ((nl nlist (cdr nl)))
761                   ((atom nl) t)
762                (declare (list nl))
763                (if (= head (car nl)) (return nil)))
764        (return nil))))
765
766 (defun < (number &rest more-numbers)
767   #!+sb-doc
768   "Return T if its arguments are in strictly increasing order, NIL otherwise."
769   (declare (dynamic-extent more-numbers))
770   (do* ((n (the number number) (car nlist))
771         (nlist more-numbers (cdr nlist)))
772        ((atom nlist) t)
773      (declare (list nlist))
774      (if (not (< n (car nlist))) (return nil))))
775
776 (defun > (number &rest more-numbers)
777   #!+sb-doc
778   "Return T if its arguments are in strictly decreasing order, NIL otherwise."
779   (declare (dynamic-extent more-numbers))
780   (do* ((n (the number number) (car nlist))
781         (nlist more-numbers (cdr nlist)))
782        ((atom nlist) t)
783      (declare (list nlist))
784      (if (not (> n (car nlist))) (return nil))))
785
786 (defun <= (number &rest more-numbers)
787   #!+sb-doc
788   "Return T if arguments are in strictly non-decreasing order, NIL otherwise."
789   (declare (dynamic-extent more-numbers))
790   (do* ((n (the number number) (car nlist))
791         (nlist more-numbers (cdr nlist)))
792        ((atom nlist) t)
793      (declare (list nlist))
794      (if (not (<= n (car nlist))) (return nil))))
795
796 (defun >= (number &rest more-numbers)
797   #!+sb-doc
798   "Return T if arguments are in strictly non-increasing order, NIL otherwise."
799   (declare (dynamic-extent more-numbers))
800   (do* ((n (the number number) (car nlist))
801         (nlist more-numbers (cdr nlist)))
802        ((atom nlist) t)
803      (declare (list nlist))
804      (if (not (>= n (car nlist))) (return nil))))
805
806 (defun max (number &rest more-numbers)
807   #!+sb-doc
808   "Return the greatest of its arguments; among EQUALP greatest, return
809 the first."
810   (declare (dynamic-extent more-numbers))
811   (do ((nlist more-numbers (cdr nlist))
812        (result number))
813       ((null nlist) (return result))
814      (declare (list nlist))
815      (declare (type real number result))
816      (if (> (car nlist) result) (setq result (car nlist)))))
817
818 (defun min (number &rest more-numbers)
819   #!+sb-doc
820   "Return the least of its arguments; among EQUALP least, return
821 the first."
822   (declare (dynamic-extent more-numbers))
823   (do ((nlist more-numbers (cdr nlist))
824        (result number))
825       ((null nlist) (return result))
826      (declare (list nlist))
827      (declare (type real number result))
828      (if (< (car nlist) result) (setq result (car nlist)))))
829
830 (eval-when (:compile-toplevel :execute)
831
832 ;;; The INFINITE-X-FINITE-Y and INFINITE-Y-FINITE-X args tell us how
833 ;;; to handle the case when X or Y is a floating-point infinity and
834 ;;; the other arg is a rational. (Section 12.1.4.1 of the ANSI spec
835 ;;; says that comparisons are done by converting the float to a
836 ;;; rational when comparing with a rational, but infinities can't be
837 ;;; converted to a rational, so we show some initiative and do it this
838 ;;; way instead.)
839 (defun basic-compare (op &key infinite-x-finite-y infinite-y-finite-x)
840   `(((fixnum fixnum) (,op x y))
841
842     ((single-float single-float) (,op x y))
843     #!+long-float
844     (((foreach single-float double-float long-float) long-float)
845      (,op (coerce x 'long-float) y))
846     #!+long-float
847     ((long-float (foreach single-float double-float))
848      (,op x (coerce y 'long-float)))
849     ((fixnum (foreach single-float double-float))
850      (if (float-infinity-p y)
851          ,infinite-y-finite-x
852          ;; If the fixnum has an exact float representation, do a
853          ;; float comparison. Otherwise do the slow float -> ratio
854          ;; conversion.
855          (multiple-value-bind (lo hi)
856              (case '(dispatch-type y)
857                ('single-float
858                 (values most-negative-exactly-single-float-fixnum
859                         most-positive-exactly-single-float-fixnum))
860                ('double-float
861                 (values most-negative-exactly-double-float-fixnum
862                         most-positive-exactly-double-float-fixnum)))
863            (if (<= lo y hi)
864                (,op (coerce x '(dispatch-type y)) y)
865                (,op x (rational y))))))
866     (((foreach single-float double-float) fixnum)
867      (if (eql y 0)
868          (,op x (coerce 0 '(dispatch-type x)))
869          (if (float-infinity-p x)
870              ,infinite-x-finite-y
871              ;; Likewise
872              (multiple-value-bind (lo hi)
873                  (case '(dispatch-type x)
874                    ('single-float
875                     (values most-negative-exactly-single-float-fixnum
876                             most-positive-exactly-single-float-fixnum))
877                    ('double-float
878                     (values most-negative-exactly-double-float-fixnum
879                             most-positive-exactly-double-float-fixnum)))
880                (if (<= lo y hi)
881                    (,op x (coerce y '(dispatch-type x)))
882                    (,op (rational x) y))))))
883     (((foreach single-float double-float) double-float)
884      (,op (coerce x 'double-float) y))
885     ((double-float single-float)
886      (,op x (coerce y 'double-float)))
887     (((foreach single-float double-float #!+long-float long-float) rational)
888      (if (eql y 0)
889          (,op x (coerce 0 '(dispatch-type x)))
890          (if (float-infinity-p x)
891              ,infinite-x-finite-y
892              (,op (rational x) y))))
893     (((foreach bignum fixnum ratio) float)
894      (if (float-infinity-p y)
895          ,infinite-y-finite-x
896          (,op x (rational y))))))
897 ) ; EVAL-WHEN
898
899 (macrolet ((def-two-arg-</> (name op ratio-arg1 ratio-arg2 &rest cases)
900              `(defun ,name (x y)
901                 (number-dispatch ((x real) (y real))
902                                  (basic-compare
903                                   ,op
904                                   :infinite-x-finite-y
905                                   (,op x (coerce 0 '(dispatch-type x)))
906                                   :infinite-y-finite-x
907                                   (,op (coerce 0 '(dispatch-type y)) y))
908                                  (((foreach fixnum bignum) ratio)
909                                   (,op x (,ratio-arg2 (numerator y)
910                                                       (denominator y))))
911                                  ((ratio integer)
912                                   (,op (,ratio-arg1 (numerator x)
913                                                     (denominator x))
914                                        y))
915                                  ((ratio ratio)
916                                   (,op (* (numerator   (truly-the ratio x))
917                                           (denominator (truly-the ratio y)))
918                                        (* (numerator   (truly-the ratio y))
919                                           (denominator (truly-the ratio x)))))
920                                  ,@cases))))
921   (def-two-arg-</> two-arg-< < floor ceiling
922     ((fixnum bignum)
923      (bignum-plus-p y))
924     ((bignum fixnum)
925      (not (bignum-plus-p x)))
926     ((bignum bignum)
927      (minusp (bignum-compare x y))))
928   (def-two-arg-</> two-arg-> > ceiling floor
929     ((fixnum bignum)
930      (not (bignum-plus-p y)))
931     ((bignum fixnum)
932      (bignum-plus-p x))
933     ((bignum bignum)
934      (plusp (bignum-compare x y)))))
935
936 (defun two-arg-= (x y)
937   (number-dispatch ((x number) (y number))
938     (basic-compare =
939                    ;; An infinite value is never equal to a finite value.
940                    :infinite-x-finite-y nil
941                    :infinite-y-finite-x nil)
942     ((fixnum (or bignum ratio)) nil)
943
944     ((bignum (or fixnum ratio)) nil)
945     ((bignum bignum)
946      (zerop (bignum-compare x y)))
947
948     ((ratio integer) nil)
949     ((ratio ratio)
950      (and (eql (numerator x) (numerator y))
951           (eql (denominator x) (denominator y))))
952
953     ((complex complex)
954      (and (= (realpart x) (realpart y))
955           (= (imagpart x) (imagpart y))))
956     (((foreach fixnum bignum ratio single-float double-float
957                #!+long-float long-float) complex)
958      (and (= x (realpart y))
959           (zerop (imagpart y))))
960     ((complex (or float rational))
961      (and (= (realpart x) y)
962           (zerop (imagpart x))))))
963 \f
964 ;;;; logicals
965
966 (defun logior (&rest integers)
967   #!+sb-doc
968   "Return the bit-wise or of its arguments. Args must be integers."
969   (declare (list integers))
970   (if integers
971       (do ((result (pop integers) (logior result (pop integers))))
972           ((null integers) result)
973         (declare (integer result)))
974       0))
975
976 (defun logxor (&rest integers)
977   #!+sb-doc
978   "Return the bit-wise exclusive or of its arguments. Args must be integers."
979   (declare (list integers))
980   (if integers
981       (do ((result (pop integers) (logxor result (pop integers))))
982           ((null integers) result)
983         (declare (integer result)))
984       0))
985
986 (defun logand (&rest integers)
987   #!+sb-doc
988   "Return the bit-wise and of its arguments. Args must be integers."
989   (declare (list integers))
990   (if integers
991       (do ((result (pop integers) (logand result (pop integers))))
992           ((null integers) result)
993         (declare (integer result)))
994       -1))
995
996 (defun logeqv (&rest integers)
997   #!+sb-doc
998   "Return the bit-wise equivalence of its arguments. Args must be integers."
999   (declare (list integers))
1000   (if integers
1001       (do ((result (pop integers) (logeqv result (pop integers))))
1002           ((null integers) result)
1003         (declare (integer result)))
1004       -1))
1005
1006 (defun lognot (number)
1007   #!+sb-doc
1008   "Return the bit-wise logical not of integer."
1009   (etypecase number
1010     (fixnum (lognot (truly-the fixnum number)))
1011     (bignum (bignum-logical-not number))))
1012
1013 (macrolet ((def (name op big-op &optional doc)
1014              `(defun ,name (integer1 integer2)
1015                 ,@(when doc
1016                     (list doc))
1017                 (let ((x integer1)
1018                       (y integer2))
1019                   (number-dispatch ((x integer) (y integer))
1020                     (bignum-cross-fixnum ,op ,big-op))))))
1021   (def two-arg-and logand bignum-logical-and)
1022   (def two-arg-ior logior bignum-logical-ior)
1023   (def two-arg-xor logxor bignum-logical-xor)
1024   ;; BIGNUM-LOGICAL-{AND,IOR,XOR} need not return a bignum, so must
1025   ;; call the generic LOGNOT...
1026   (def two-arg-eqv logeqv (lambda (x y) (lognot (bignum-logical-xor x y))))
1027   (def lognand lognand
1028        (lambda (x y) (lognot (bignum-logical-and x y)))
1029        #!+sb-doc "Complement the logical AND of INTEGER1 and INTEGER2.")
1030   (def lognor lognor
1031        (lambda (x y) (lognot (bignum-logical-ior x y)))
1032        #!+sb-doc "Complement the logical AND of INTEGER1 and INTEGER2.")
1033   ;; ... but BIGNUM-LOGICAL-NOT on a bignum will always return a bignum
1034   (def logandc1 logandc1
1035        (lambda (x y) (bignum-logical-and (bignum-logical-not x) y))
1036        #!+sb-doc "Bitwise AND (LOGNOT INTEGER1) with INTEGER2.")
1037   (def logandc2 logandc2
1038        (lambda (x y) (bignum-logical-and x (bignum-logical-not y)))
1039        #!+sb-doc "Bitwise AND INTEGER1 with (LOGNOT INTEGER2).")
1040   (def logorc1 logorc1
1041        (lambda (x y) (bignum-logical-ior (bignum-logical-not x) y))
1042        #!+sb-doc "Bitwise OR (LOGNOT INTEGER1) with INTEGER2.")
1043   (def logorc2 logorc2
1044        (lambda (x y) (bignum-logical-ior x (bignum-logical-not y)))
1045        #!+sb-doc "Bitwise OR INTEGER1 with (LOGNOT INTEGER2)."))
1046
1047 (defun logcount (integer)
1048   #!+sb-doc
1049   "Count the number of 1 bits if INTEGER is positive, and the number of 0 bits
1050   if INTEGER is negative."
1051   (etypecase integer
1052     (fixnum
1053      (logcount (truly-the (integer 0
1054                                    #.(max sb!xc:most-positive-fixnum
1055                                           (lognot sb!xc:most-negative-fixnum)))
1056                           (if (minusp (truly-the fixnum integer))
1057                               (lognot (truly-the fixnum integer))
1058                               integer))))
1059     (bignum
1060      (bignum-logcount integer))))
1061
1062 (defun logtest (integer1 integer2)
1063   #!+sb-doc
1064   "Predicate which returns T if logand of integer1 and integer2 is not zero."
1065   (logtest integer1 integer2))
1066
1067 (defun logbitp (index integer)
1068   #!+sb-doc
1069   "Predicate returns T if bit index of integer is a 1."
1070   (number-dispatch ((index integer) (integer integer))
1071     ((fixnum fixnum) (if (> index #.(- sb!vm:n-word-bits sb!vm:n-lowtag-bits))
1072                          (minusp integer)
1073                          (not (zerop (logand integer (ash 1 index))))))
1074     ((fixnum bignum) (bignum-logbitp index integer))
1075     ((bignum (foreach fixnum bignum)) (minusp integer))))
1076
1077 (defun ash (integer count)
1078   #!+sb-doc
1079   "Shifts integer left by count places preserving sign. - count shifts right."
1080   (declare (integer integer count))
1081   (etypecase integer
1082     (fixnum
1083      (cond ((zerop integer)
1084             0)
1085            ((fixnump count)
1086             (let ((length (integer-length (truly-the fixnum integer)))
1087                   (count (truly-the fixnum count)))
1088               (declare (fixnum length count))
1089               (cond ((and (plusp count)
1090                           (> (+ length count)
1091                              (integer-length most-positive-fixnum)))
1092                      (bignum-ashift-left (make-small-bignum integer) count))
1093                     (t
1094                      (truly-the fixnum
1095                                 (ash (truly-the fixnum integer) count))))))
1096            ((minusp count)
1097             (if (minusp integer) -1 0))
1098            (t
1099             (bignum-ashift-left (make-small-bignum integer) count))))
1100     (bignum
1101      (if (plusp count)
1102          (bignum-ashift-left integer count)
1103          (bignum-ashift-right integer (- count))))))
1104
1105 (defun integer-length (integer)
1106   #!+sb-doc
1107   "Return the number of non-sign bits in the twos-complement representation
1108   of INTEGER."
1109   (etypecase integer
1110     (fixnum
1111      (integer-length (truly-the fixnum integer)))
1112     (bignum
1113      (bignum-integer-length integer))))
1114 \f
1115 ;;;; BYTE, bytespecs, and related operations
1116
1117 (defun byte (size position)
1118   #!+sb-doc
1119   "Return a byte specifier which may be used by other byte functions
1120   (e.g. LDB)."
1121   (byte size position))
1122
1123 (defun byte-size (bytespec)
1124   #!+sb-doc
1125   "Return the size part of the byte specifier bytespec."
1126   (byte-size bytespec))
1127
1128 (defun byte-position (bytespec)
1129   #!+sb-doc
1130   "Return the position part of the byte specifier bytespec."
1131   (byte-position bytespec))
1132
1133 (defun ldb (bytespec integer)
1134   #!+sb-doc
1135   "Extract the specified byte from integer, and right justify result."
1136   (ldb bytespec integer))
1137
1138 (defun ldb-test (bytespec integer)
1139   #!+sb-doc
1140   "Return T if any of the specified bits in integer are 1's."
1141   (ldb-test bytespec integer))
1142
1143 (defun mask-field (bytespec integer)
1144   #!+sb-doc
1145   "Extract the specified byte from integer,  but do not right justify result."
1146   (mask-field bytespec integer))
1147
1148 (defun dpb (newbyte bytespec integer)
1149   #!+sb-doc
1150   "Return new integer with newbyte in specified position, newbyte is right justified."
1151   (dpb newbyte bytespec integer))
1152
1153 (defun deposit-field (newbyte bytespec integer)
1154   #!+sb-doc
1155   "Return new integer with newbyte in specified position, newbyte is not right justified."
1156   (deposit-field newbyte bytespec integer))
1157
1158 (defun %ldb (size posn integer)
1159   (logand (ash integer (- posn))
1160           (1- (ash 1 size))))
1161
1162 (defun %mask-field (size posn integer)
1163   (logand integer (ash (1- (ash 1 size)) posn)))
1164
1165 (defun %dpb (newbyte size posn integer)
1166   (let ((mask (1- (ash 1 size))))
1167     (logior (logand integer (lognot (ash mask posn)))
1168             (ash (logand newbyte mask) posn))))
1169
1170 (defun %deposit-field (newbyte size posn integer)
1171   (let ((mask (ash (ldb (byte size 0) -1) posn)))
1172     (logior (logand newbyte mask)
1173             (logand integer (lognot mask)))))
1174
1175 (defun sb!c::mask-signed-field (size integer)
1176   #!+sb-doc
1177   "Extract SIZE lower bits from INTEGER, considering them as a
1178 2-complement SIZE-bits representation of a signed integer."
1179   (cond ((zerop size)
1180          0)
1181         ((logbitp (1- size) integer)
1182          (dpb integer (byte size 0) -1))
1183         (t
1184          (ldb (byte size 0) integer))))
1185
1186 \f
1187 ;;;; BOOLE
1188
1189 ;;; The boole function dispaches to any logic operation depending on
1190 ;;;     the value of a variable. Presently, legal selector values are [0..15].
1191 ;;;     boole is open coded for calls with a constant selector. or with calls
1192 ;;;     using any of the constants declared below.
1193
1194 (defconstant boole-clr 0
1195   #!+sb-doc
1196   "Boole function op, makes BOOLE return 0.")
1197
1198 (defconstant boole-set 1
1199   #!+sb-doc
1200   "Boole function op, makes BOOLE return -1.")
1201
1202 (defconstant boole-1   2
1203   #!+sb-doc
1204   "Boole function op, makes BOOLE return integer1.")
1205
1206 (defconstant boole-2   3
1207   #!+sb-doc
1208   "Boole function op, makes BOOLE return integer2.")
1209
1210 (defconstant boole-c1  4
1211   #!+sb-doc
1212   "Boole function op, makes BOOLE return complement of integer1.")
1213
1214 (defconstant boole-c2  5
1215   #!+sb-doc
1216   "Boole function op, makes BOOLE return complement of integer2.")
1217
1218 (defconstant boole-and 6
1219   #!+sb-doc
1220   "Boole function op, makes BOOLE return logand of integer1 and integer2.")
1221
1222 (defconstant boole-ior 7
1223   #!+sb-doc
1224   "Boole function op, makes BOOLE return logior of integer1 and integer2.")
1225
1226 (defconstant boole-xor 8
1227   #!+sb-doc
1228   "Boole function op, makes BOOLE return logxor of integer1 and integer2.")
1229
1230 (defconstant boole-eqv 9
1231   #!+sb-doc
1232   "Boole function op, makes BOOLE return logeqv of integer1 and integer2.")
1233
1234 (defconstant boole-nand  10
1235   #!+sb-doc
1236   "Boole function op, makes BOOLE return log nand of integer1 and integer2.")
1237
1238 (defconstant boole-nor   11
1239   #!+sb-doc
1240   "Boole function op, makes BOOLE return lognor of integer1 and integer2.")
1241
1242 (defconstant boole-andc1 12
1243   #!+sb-doc
1244   "Boole function op, makes BOOLE return logandc1 of integer1 and integer2.")
1245
1246 (defconstant boole-andc2 13
1247   #!+sb-doc
1248   "Boole function op, makes BOOLE return logandc2 of integer1 and integer2.")
1249
1250 (defconstant boole-orc1  14
1251   #!+sb-doc
1252   "Boole function op, makes BOOLE return logorc1 of integer1 and integer2.")
1253
1254 (defconstant boole-orc2  15
1255   #!+sb-doc
1256   "Boole function op, makes BOOLE return logorc2 of integer1 and integer2.")
1257
1258 (defun boole (op integer1 integer2)
1259   #!+sb-doc
1260   "Bit-wise boolean function on two integers. Function chosen by OP:
1261         0       BOOLE-CLR
1262         1       BOOLE-SET
1263         2       BOOLE-1
1264         3       BOOLE-2
1265         4       BOOLE-C1
1266         5       BOOLE-C2
1267         6       BOOLE-AND
1268         7       BOOLE-IOR
1269         8       BOOLE-XOR
1270         9       BOOLE-EQV
1271         10      BOOLE-NAND
1272         11      BOOLE-NOR
1273         12      BOOLE-ANDC1
1274         13      BOOLE-ANDC2
1275         14      BOOLE-ORC1
1276         15      BOOLE-ORC2"
1277   (case op
1278     (0 (boole 0 integer1 integer2))
1279     (1 (boole 1 integer1 integer2))
1280     (2 (boole 2 integer1 integer2))
1281     (3 (boole 3 integer1 integer2))
1282     (4 (boole 4 integer1 integer2))
1283     (5 (boole 5 integer1 integer2))
1284     (6 (boole 6 integer1 integer2))
1285     (7 (boole 7 integer1 integer2))
1286     (8 (boole 8 integer1 integer2))
1287     (9 (boole 9 integer1 integer2))
1288     (10 (boole 10 integer1 integer2))
1289     (11 (boole 11 integer1 integer2))
1290     (12 (boole 12 integer1 integer2))
1291     (13 (boole 13 integer1 integer2))
1292     (14 (boole 14 integer1 integer2))
1293     (15 (boole 15 integer1 integer2))
1294     (t (error 'type-error :datum op :expected-type '(mod 16)))))
1295 \f
1296 ;;;; GCD and LCM
1297
1298 (defun gcd (&rest integers)
1299   #!+sb-doc
1300   "Return the greatest common divisor of the arguments, which must be
1301   integers. Gcd with no arguments is defined to be 0."
1302   (cond ((null integers) 0)
1303         ((null (cdr integers)) (abs (the integer (car integers))))
1304         (t
1305          (do ((gcd (the integer (car integers))
1306                    (gcd gcd (the integer (car rest))))
1307               (rest (cdr integers) (cdr rest)))
1308              ((null rest) gcd)
1309            (declare (integer gcd)
1310                     (list rest))))))
1311
1312 (defun lcm (&rest integers)
1313   #!+sb-doc
1314   "Return the least common multiple of one or more integers. LCM of no
1315   arguments is defined to be 1."
1316   (cond ((null integers) 1)
1317         ((null (cdr integers)) (abs (the integer (car integers))))
1318         (t
1319          (do ((lcm (the integer (car integers))
1320                    (lcm lcm (the integer (car rest))))
1321               (rest (cdr integers) (cdr rest)))
1322              ((null rest) lcm)
1323            (declare (integer lcm) (list rest))))))
1324
1325 (defun two-arg-lcm (n m)
1326   (declare (integer n m))
1327   (if (or (zerop n) (zerop m))
1328       0
1329       ;; KLUDGE: I'm going to assume that it was written this way
1330       ;; originally for a reason.  However, this is a somewhat
1331       ;; complicated way of writing the algorithm in the CLHS page for
1332       ;; LCM, and I don't know why.  To be investigated.  -- CSR,
1333       ;; 2003-09-11
1334       ;;
1335       ;;    It seems to me that this is written this way to avoid
1336       ;;    unnecessary bignumification of intermediate results.
1337       ;;        -- TCR, 2008-03-05
1338       (let ((m (abs m))
1339             (n (abs n)))
1340         (multiple-value-bind (max min)
1341             (if (> m n)
1342                 (values m n)
1343                 (values n m))
1344           (* (truncate max (gcd n m)) min)))))
1345
1346 ;;; Do the GCD of two integer arguments. With fixnum arguments, we use the
1347 ;;; binary GCD algorithm from Knuth's seminumerical algorithms (slightly
1348 ;;; structurified), otherwise we call BIGNUM-GCD. We pick off the special case
1349 ;;; of 0 before the dispatch so that the bignum code doesn't have to worry
1350 ;;; about "small bignum" zeros.
1351 (defun two-arg-gcd (u v)
1352   (cond ((eql u 0) (abs v))
1353         ((eql v 0) (abs u))
1354         (t
1355          (number-dispatch ((u integer) (v integer))
1356            ((fixnum fixnum)
1357             (locally
1358                 (declare (optimize (speed 3) (safety 0)))
1359               (do ((k 0 (1+ k))
1360                    (u (abs u) (ash u -1))
1361                    (v (abs v) (ash v -1)))
1362                   ((oddp (logior u v))
1363                    (do ((temp (if (oddp u) (- v) (ash u -1))
1364                               (ash temp -1)))
1365                        (nil)
1366                      (declare (fixnum temp))
1367                      (when (oddp temp)
1368                        (if (plusp temp)
1369                            (setq u temp)
1370                            (setq v (- temp)))
1371                        (setq temp (- u v))
1372                        (when (zerop temp)
1373                          (let ((res (ash u k)))
1374                            (declare (type sb!vm:signed-word res)
1375                                     (optimize (inhibit-warnings 3)))
1376                            (return res))))))
1377                 (declare (type (mod #.sb!vm:n-word-bits) k)
1378                          (type sb!vm:signed-word u v)))))
1379            ((bignum bignum)
1380             (bignum-gcd u v))
1381            ((bignum fixnum)
1382             (bignum-gcd u (make-small-bignum v)))
1383            ((fixnum bignum)
1384             (bignum-gcd (make-small-bignum u) v))))))
1385 \f
1386 ;;; From discussion on comp.lang.lisp and Akira Kurihara.
1387 (defun isqrt (n)
1388   #!+sb-doc
1389   "Return the root of the nearest integer less than n which is a perfect
1390    square."
1391   (declare (type unsigned-byte n) (values unsigned-byte))
1392   ;; Theoretically (> n 7), i.e., n-len-quarter > 0.
1393   (if (and (fixnump n) (<= n 24))
1394       (cond ((> n 15) 4)
1395             ((> n  8) 3)
1396             ((> n  3) 2)
1397             ((> n  0) 1)
1398             (t 0))
1399       (let* ((n-len-quarter (ash (integer-length n) -2))
1400              (n-half (ash n (- (ash n-len-quarter 1))))
1401              (n-half-isqrt (isqrt n-half))
1402              (init-value (ash (1+ n-half-isqrt) n-len-quarter)))
1403         (loop
1404           (let ((iterated-value
1405                  (ash (+ init-value (truncate n init-value)) -1)))
1406             (unless (< iterated-value init-value)
1407               (return init-value))
1408             (setq init-value iterated-value))))))
1409 \f
1410 ;;;; miscellaneous number predicates
1411
1412 (macrolet ((def (name doc)
1413              `(defun ,name (number) ,doc (,name number))))
1414   (def zerop "Is this number zero?")
1415   (def plusp "Is this real number strictly positive?")
1416   (def minusp "Is this real number strictly negative?")
1417   (def oddp "Is this integer odd?")
1418   (def evenp "Is this integer even?"))
1419 \f
1420 ;;;; modular functions
1421 #.
1422 (collect ((forms))
1423   (flet ((unsigned-definition (name lambda-list width)
1424            (let ((pattern (1- (ash 1 width))))
1425              `(defun ,name ,lambda-list
1426                (flet ((prepare-argument (x)
1427                         (declare (integer x))
1428                         (etypecase x
1429                           ((unsigned-byte ,width) x)
1430                           (fixnum (logand x ,pattern))
1431                           (bignum (logand x ,pattern)))))
1432                  (,name ,@(loop for arg in lambda-list
1433                                 collect `(prepare-argument ,arg)))))))
1434          (signed-definition (name lambda-list width)
1435            `(defun ,name ,lambda-list
1436               (flet ((prepare-argument (x)
1437                        (declare (integer x))
1438                        (etypecase x
1439                          ((signed-byte ,width) x)
1440                          (fixnum (sb!c::mask-signed-field ,width x))
1441                          (bignum (sb!c::mask-signed-field ,width x)))))
1442                 (,name ,@(loop for arg in lambda-list
1443                                collect `(prepare-argument ,arg)))))))
1444     (flet ((do-mfuns (class)
1445              (loop for infos being each hash-value of (sb!c::modular-class-funs class)
1446                    ;; FIXME: We need to process only "toplevel" functions
1447                    when (listp infos)
1448                    do (loop for info in infos
1449                             for name = (sb!c::modular-fun-info-name info)
1450                             and width = (sb!c::modular-fun-info-width info)
1451                             and signedp = (sb!c::modular-fun-info-signedp info)
1452                             and lambda-list = (sb!c::modular-fun-info-lambda-list info)
1453                             if signedp
1454                             do (forms (signed-definition name lambda-list width))
1455                             else
1456                             do (forms (unsigned-definition name lambda-list width))))))
1457       (do-mfuns sb!c::*untagged-unsigned-modular-class*)
1458       (do-mfuns sb!c::*untagged-signed-modular-class*)
1459       (do-mfuns sb!c::*tagged-modular-class*)))
1460   `(progn ,@(forms)))
1461
1462 ;;; KLUDGE: these out-of-line definitions can't use the modular
1463 ;;; arithmetic, as that is only (currently) defined for constant
1464 ;;; shifts.  See also the comment in (LOGAND OPTIMIZER) for more
1465 ;;; discussion of this hack.  -- CSR, 2003-10-09
1466 #!+#.(cl:if (cl:= sb!vm:n-machine-word-bits 32) '(and) '(or))
1467 (defun sb!vm::ash-left-mod32 (integer amount)
1468   (etypecase integer
1469     ((unsigned-byte 32) (ldb (byte 32 0) (ash integer amount)))
1470     (fixnum (ldb (byte 32 0) (ash (logand integer #xffffffff) amount)))
1471     (bignum (ldb (byte 32 0) (ash (logand integer #xffffffff) amount)))))
1472 #!+#.(cl:if (cl:= sb!vm:n-machine-word-bits 64) '(and) '(or))
1473 (defun sb!vm::ash-left-mod64 (integer amount)
1474   (etypecase integer
1475     ((unsigned-byte 64) (ldb (byte 64 0) (ash integer amount)))
1476     (fixnum (ldb (byte 64 0) (ash (logand integer #xffffffffffffffff) amount)))
1477     (bignum (ldb (byte 64 0)
1478                  (ash (logand integer #xffffffffffffffff) amount)))))
1479
1480 #!+x86
1481 (defun sb!vm::ash-left-smod30 (integer amount)
1482   (etypecase integer
1483     ((signed-byte 30) (sb!c::mask-signed-field 30 (ash integer amount)))
1484     (integer (sb!c::mask-signed-field 30 (ash (sb!c::mask-signed-field 30 integer) amount)))))
1485
1486 #!+x86-64
1487 (defun sb!vm::ash-left-smod61 (integer amount)
1488   (etypecase integer
1489     ((signed-byte 61) (sb!c::mask-signed-field 61 (ash integer amount)))
1490     (integer (sb!c::mask-signed-field 61 (ash (sb!c::mask-signed-field 61 integer) amount)))))