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