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