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