Signal floating-point-overflow from bignum-to-float.
[sbcl.git] / src / code / bignum.lisp
blobaded567df47241ae54f17a1ce68bda75323a18a1
1 ;;;; code to implement bignum support
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!BIGNUM")
14 ;;;; notes
16 ;;; comments from CMU CL:
17 ;;; These symbols define the interface to the number code:
18 ;;; add-bignums multiply-bignums negate-bignum subtract-bignum
19 ;;; multiply-bignum-and-fixnum multiply-fixnums
20 ;;; bignum-ashift-right bignum-ashift-left bignum-gcd
21 ;;; bignum-to-float bignum-integer-length
22 ;;; bignum-logical-and bignum-logical-ior bignum-logical-xor
23 ;;; bignum-logical-not bignum-load-byte
24 ;;; bignum-truncate bignum-plus-p bignum-compare make-small-bignum
25 ;;; bignum-logbitp bignum-logcount
26 ;;; These symbols define the interface to the compiler:
27 ;;; bignum-element-type bignum-index %allocate-bignum
28 ;;; %bignum-length %bignum-set-length %bignum-ref %bignum-set
29 ;;; %digit-0-or-plusp %add-with-carry %subtract-with-borrow
30 ;;; %multiply-and-add %multiply %lognot %logand %logior %logxor
31 ;;; %fixnum-to-digit %bigfloor %fixnum-digit-with-correct-sign %ashl
32 ;;; %ashr %digit-logical-shift-right))
34 ;;; The following interfaces will either be assembler routines or code
35 ;;; sequences expanded into the code as basic bignum operations:
36 ;;; General:
37 ;;; %BIGNUM-LENGTH
38 ;;; %ALLOCATE-BIGNUM
39 ;;; %BIGNUM-REF
40 ;;; %NORMALIZE-BIGNUM
41 ;;; %BIGNUM-SET-LENGTH
42 ;;; %FIXNUM-DIGIT-WITH-CORRECT-SIGN
43 ;;; %SIGN-DIGIT
44 ;;; %ASHR
45 ;;; %ASHL
46 ;;; %BIGNUM-0-OR-PLUSP
47 ;;; %DIGIT-LOGICAL-SHIFT-RIGHT
48 ;;; General (May not exist when done due to sole use in %-routines.)
49 ;;; %DIGIT-0-OR-PLUSP
50 ;;; Addition:
51 ;;; %ADD-WITH-CARRY
52 ;;; Subtraction:
53 ;;; %SUBTRACT-WITH-BORROW
54 ;;; Multiplication
55 ;;; %MULTIPLY
56 ;;; Negation
57 ;;; %LOGNOT
58 ;;; Shifting (in place)
59 ;;; %NORMALIZE-BIGNUM-BUFFER
60 ;;; Relational operators:
61 ;;; %LOGAND
62 ;;; %LOGIOR
63 ;;; %LOGXOR
64 ;;; LDB
65 ;;; %FIXNUM-TO-DIGIT
66 ;;; TRUNCATE
67 ;;; %BIGFLOOR
68 ;;;
69 ;;; Note: The floating routines know about the float representation.
70 ;;;
71 ;;; PROBLEM 1:
72 ;;; There might be a problem with various LET's and parameters that take a
73 ;;; digit value. We need to write these so those things stay in machine
74 ;;; registers and number stack slots. I bind locals to these values, and I
75 ;;; use function on them -- ZEROP, ASH, etc.
76 ;;;
77 ;;; PROBLEM 2:
78 ;;; In shifting and byte operations, I use masks and logical operations that
79 ;;; could result in intermediate bignums. This is hidden by the current system,
80 ;;; but I may need to write these in a way that keeps these masks and logical
81 ;;; operations from diving into the Lisp level bignum code.
82 ;;;
83 ;;; To do:
84 ;;; fixnums
85 ;;; logior, logxor, logand
86 ;;; depending on relationals, < (twice) and <= (twice)
87 ;;; or write compare thing (twice).
88 ;;; LDB on fixnum with bignum result.
89 ;;; DPB on fixnum with bignum result.
90 ;;; TRUNCATE returns zero or one as one value and fixnum or minus fixnum
91 ;;; for the other value when given (truncate fixnum bignum).
92 ;;; Returns (truncate bignum fixnum) otherwise.
93 ;;; addition
94 ;;; subtraction (twice)
95 ;;; multiply
96 ;;; GCD
97 ;;; Write MASK-FIELD and DEPOSIT-FIELD in terms of logical operations.
98 ;;; DIVIDE
99 ;;; IF (/ x y) with bignums:
100 ;;; do the truncate, and if rem is 0, return quotient.
101 ;;; if rem is non-0
102 ;;; gcd of x and y.
103 ;;; "truncate" each by gcd, ignoring remainder 0.
104 ;;; form ratio of each result, bottom is positive.
106 ;;;; What's a bignum?
108 (defconstant digit-size sb!vm:n-word-bits)
110 (defconstant all-ones-digit (1- (ash 1 sb!vm:n-word-bits)))
112 ;;;; internal inline routines
114 ;;; %ALLOCATE-BIGNUM must zero all elements.
115 (defun %allocate-bignum (length)
116 (declare (type bignum-length length))
117 (%allocate-bignum length))
119 ;;; Extract the length of the bignum.
120 (defun %bignum-length (bignum)
121 (declare (type bignum bignum))
122 (%bignum-length bignum))
124 ;;; %BIGNUM-REF needs to access bignums as obviously as possible, and it needs
125 ;;; to be able to return the digit somewhere no one looks for real objects.
126 (defun %bignum-ref (bignum i)
127 (declare (type bignum bignum)
128 (type bignum-index i))
129 (%bignum-ref bignum i))
130 (defun %bignum-set (bignum i value)
131 (declare (type bignum bignum)
132 (type bignum-index i)
133 (type bignum-element-type value))
134 (%bignum-set bignum i value))
136 ;;; Return T if digit is positive, or NIL if negative.
137 (defun %digit-0-or-plusp (digit)
138 (declare (type bignum-element-type digit))
139 (not (logbitp (1- digit-size) digit)))
141 #!-sb-fluid (declaim (inline %bignum-0-or-plusp))
142 (defun %bignum-0-or-plusp (bignum len)
143 (declare (type bignum bignum)
144 (type bignum-length len))
145 (%digit-0-or-plusp (%bignum-ref bignum (1- len))))
147 ;;; This should be in assembler, and should not cons intermediate
148 ;;; results. It returns a bignum digit and a carry resulting from adding
149 ;;; together a, b, and an incoming carry.
150 (defun %add-with-carry (a b carry)
151 (declare (type bignum-element-type a b)
152 (type (mod 2) carry))
153 (%add-with-carry a b carry))
155 ;;; This should be in assembler, and should not cons intermediate
156 ;;; results. It returns a bignum digit and a borrow resulting from
157 ;;; subtracting b from a, and subtracting a possible incoming borrow.
159 ;;; We really do: a - b - 1 + borrow, where borrow is either 0 or 1.
160 (defun %subtract-with-borrow (a b borrow)
161 (declare (type bignum-element-type a b)
162 (type (mod 2) borrow))
163 (%subtract-with-borrow a b borrow))
165 ;;; Multiply two digit-size numbers, returning a 2*digit-size result
166 ;;; split into two digit-size quantities.
167 (defun %multiply (x y)
168 (declare (type bignum-element-type x y))
169 (%multiply x y))
171 ;;; This multiplies x-digit and y-digit, producing high and low digits
172 ;;; manifesting the result. Then it adds the low digit, res-digit, and
173 ;;; carry-in-digit. Any carries (note, you still have to add two digits
174 ;;; at a time possibly producing two carries) from adding these three
175 ;;; digits get added to the high digit from the multiply, producing the
176 ;;; next carry digit. Res-digit is optional since two uses of this
177 ;;; primitive multiplies a single digit bignum by a multiple digit
178 ;;; bignum, and in this situation there is no need for a result buffer
179 ;;; accumulating partial results which is where the res-digit comes
180 ;;; from.
181 (defun %multiply-and-add (x-digit y-digit carry-in-digit
182 &optional (res-digit 0))
183 (declare (type bignum-element-type x-digit y-digit res-digit carry-in-digit))
184 (%multiply-and-add x-digit y-digit carry-in-digit res-digit))
186 (defun %lognot (digit)
187 (declare (type bignum-element-type digit))
188 (%lognot digit))
190 ;;; Each of these does the digit-size unsigned op.
191 (declaim (inline %logand %logior %logxor))
192 (defun %logand (a b)
193 (declare (type bignum-element-type a b))
194 (logand a b))
195 (defun %logior (a b)
196 (declare (type bignum-element-type a b))
197 (logior a b))
198 (defun %logxor (a b)
199 (declare (type bignum-element-type a b))
200 (logxor a b))
202 ;;; This takes a fixnum and sets it up as an unsigned digit-size
203 ;;; quantity.
204 (defun %fixnum-to-digit (x)
205 (declare (fixnum x))
206 (logand x (1- (ash 1 digit-size))))
208 #!-32x16-divide
209 ;;; This takes three digits and returns the FLOOR'ed result of
210 ;;; dividing the first two as a 2*digit-size integer by the third.
212 ;;; Do weird LET and SETQ stuff to bamboozle the compiler into allowing
213 ;;; the %BIGFLOOR transform to expand into pseudo-assembler for which the
214 ;;; compiler can later correctly allocate registers.
215 (defun %bigfloor (a b c)
216 (let ((a a) (b b) (c c))
217 (declare (type bignum-element-type a b c))
218 (setq a a b b c c)
219 (%bigfloor a b c)))
221 ;;; Convert the digit to a regular integer assuming that the digit is signed.
222 (defun %fixnum-digit-with-correct-sign (digit)
223 (declare (type bignum-element-type digit))
224 (if (logbitp (1- digit-size) digit)
225 (logior digit (ash -1 digit-size))
226 digit))
228 ;;; Do an arithmetic shift right of data even though bignum-element-type is
229 ;;; unsigned.
230 (defun %ashr (data count)
231 (declare (type bignum-element-type data)
232 (type (mod #.sb!vm:n-word-bits) count))
233 (%ashr data count))
235 ;;; This takes a digit-size quantity and shifts it to the left,
236 ;;; returning a digit-size quantity.
237 (defun %ashl (data count)
238 (declare (type bignum-element-type data)
239 (type (mod #.sb!vm:n-word-bits) count))
240 (%ashl data count))
242 ;;; Do an unsigned (logical) right shift of a digit by Count.
243 (defun %digit-logical-shift-right (data count)
244 (declare (type bignum-element-type data)
245 (type (mod #.sb!vm:n-word-bits) count))
246 (%digit-logical-shift-right data count))
248 ;;; Change the length of bignum to be newlen. Newlen must be the same or
249 ;;; smaller than the old length, and any elements beyond newlen must be zeroed.
250 (defun %bignum-set-length (bignum newlen)
251 (declare (type bignum bignum)
252 (type bignum-length newlen))
253 (%bignum-set-length bignum newlen))
255 ;;; This returns 0 or "-1" depending on whether the bignum is positive. This
256 ;;; is suitable for infinite sign extension to complete additions,
257 ;;; subtractions, negations, etc. This cannot return a -1 represented as
258 ;;; a negative fixnum since it would then have to low zeros.
259 #!-sb-fluid (declaim (inline %sign-digit))
260 (defun %sign-digit (bignum len)
261 (declare (type bignum bignum)
262 (type bignum-length len))
263 (%ashr (%bignum-ref bignum (1- len)) (1- digit-size)))
265 (declaim (inline bignum-plus-p))
266 (defun bignum-plus-p (bignum)
267 (declare (type bignum bignum))
268 (%bignum-0-or-plusp bignum (%bignum-length bignum)))
270 (declaim (optimize (speed 3) (safety 0)))
272 ;;;; addition
274 (defun add-bignums (a b)
275 (declare (type bignum a b))
276 (declare (muffle-conditions compiler-note)) ; returns lispobj, so what.
277 (let ((len-a (%bignum-length a))
278 (len-b (%bignum-length b)))
279 (multiple-value-bind (a len-a b len-b)
280 (if (> len-a len-b)
281 (values a len-a b len-b)
282 (values b len-b a len-a))
283 (declare (type bignum a b)
284 (type bignum-length len-a len-b))
285 (let* ((len-res (1+ len-a))
286 (res (%allocate-bignum len-res))
287 (carry 0))
288 (declare (type bignum-length len-res)
289 (type bignum res)
290 (type (mod 2) carry))
291 (dotimes (i len-b)
292 (declare (type bignum-index i))
293 (multiple-value-bind (v k)
294 (%add-with-carry (%bignum-ref a i) (%bignum-ref b i) carry)
295 (declare (type bignum-element-type v)
296 (type (mod 2) k))
297 (setf (%bignum-ref res i) v)
298 (setf carry k)))
299 (if (/= len-a len-b)
300 (finish-add a res carry (%sign-digit b len-b) len-b len-a)
301 (setf (%bignum-ref res len-a)
302 (%add-with-carry (%sign-digit a len-a)
303 (%sign-digit b len-b)
304 carry)))
305 (%normalize-bignum res len-res)))))
307 ;;; This takes the longer of two bignums and propagates the carry through its
308 ;;; remaining high order digits.
309 (defun finish-add (a res carry sign-digit-b start end)
310 (declare (type bignum a res)
311 (type (mod 2) carry)
312 (type bignum-element-type sign-digit-b)
313 (type bignum-index start)
314 (type bignum-length end))
315 (do ((i start (1+ i)))
316 ((= i end)
317 (setf (%bignum-ref res end)
318 (%add-with-carry (%sign-digit a end) sign-digit-b carry)))
319 (declare (type bignum-index i))
320 (multiple-value-bind (v k)
321 (%add-with-carry (%bignum-ref a i) sign-digit-b carry)
322 (setf (%bignum-ref res i) v)
323 (setf carry k)))
324 (values))
326 ;;;; subtraction
328 (eval-when (:compile-toplevel :execute)
330 ;;; This subtracts b from a plugging result into res. Return-fun is the
331 ;;; function to call that fixes up the result returning any useful values, such
332 ;;; as the result. This macro may evaluate its arguments more than once.
333 (sb!xc:defmacro subtract-bignum-loop (a len-a b len-b res len-res return-fun)
334 (with-unique-names (borrow a-digit a-sign b-digit b-sign i v k)
335 `(let* ((,borrow 1)
336 (,a-sign (%sign-digit ,a ,len-a))
337 (,b-sign (%sign-digit ,b ,len-b)))
338 (declare (type bignum-element-type ,a-sign ,b-sign))
339 (dotimes (,i ,len-res)
340 (declare (type bignum-index ,i))
341 (let ((,a-digit (if (< ,i ,len-a) (%bignum-ref ,a ,i) ,a-sign))
342 (,b-digit (if (< ,i ,len-b) (%bignum-ref ,b ,i) ,b-sign)))
343 (declare (type bignum-element-type ,a-digit ,b-digit))
344 (multiple-value-bind (,v ,k)
345 (%subtract-with-borrow ,a-digit ,b-digit ,borrow)
346 (setf (%bignum-ref ,res ,i) ,v)
347 (setf ,borrow ,k))))
348 (,return-fun ,res ,len-res))))
350 ) ;EVAL-WHEN
352 (defun subtract-bignum (a b)
353 (declare (type bignum a b))
354 (let* ((len-a (%bignum-length a))
355 (len-b (%bignum-length b))
356 (len-res (1+ (max len-a len-b)))
357 (res (%allocate-bignum len-res)))
358 (declare (type bignum-length len-a len-b len-res)) ;Test len-res for bounds?
359 (subtract-bignum-loop a len-a b len-b res len-res %normalize-bignum)))
361 ;;; Operations requiring a subtraction without the overhead of intermediate
362 ;;; results, such as GCD, use this. It assumes Result is big enough for the
363 ;;; result.
364 (defun subtract-bignum-buffers-with-len (a len-a b len-b result len-res)
365 (declare (type bignum a b result)
366 (type bignum-length len-a len-b len-res))
367 (subtract-bignum-loop a len-a b len-b result len-res
368 %normalize-bignum-buffer))
370 (defun subtract-bignum-buffers (a len-a b len-b result)
371 (declare (type bignum a b result)
372 (type bignum-length len-a len-b))
373 (subtract-bignum-loop a len-a b len-b result (max len-a len-b)
374 %normalize-bignum-buffer))
376 ;;;; multiplication
378 (defun multiply-bignums (a b)
379 (declare (type bignum a b))
380 (let* ((a-plusp (bignum-plus-p a))
381 (b-plusp (bignum-plus-p b))
382 (a (if a-plusp a (negate-bignum a)))
383 (b (if b-plusp b (negate-bignum b)))
384 (len-a (%bignum-length a))
385 (len-b (%bignum-length b))
386 (len-res (+ len-a len-b))
387 (res (%allocate-bignum len-res))
388 (negate-res (not (eq a-plusp b-plusp))))
389 (declare (type bignum-length len-a len-b len-res))
390 (dotimes (i len-a)
391 (declare (type bignum-index i))
392 (let ((carry-digit 0)
393 (x (%bignum-ref a i))
394 (k i))
395 (declare (type bignum-index k)
396 (type bignum-element-type carry-digit x))
397 (dotimes (j len-b)
398 (multiple-value-bind (big-carry res-digit)
399 (%multiply-and-add x
400 (%bignum-ref b j)
401 (%bignum-ref res k)
402 carry-digit)
403 (declare (type bignum-element-type big-carry res-digit))
404 (setf (%bignum-ref res k) res-digit)
405 (setf carry-digit big-carry)
406 (incf k)))
407 (setf (%bignum-ref res k) carry-digit)))
408 (when negate-res (negate-bignum-in-place res))
409 (%normalize-bignum res len-res)))
411 (defun multiply-bignum-and-fixnum (bignum fixnum)
412 (declare (type bignum bignum) (type fixnum fixnum))
413 (let* ((bignum-plus-p (bignum-plus-p bignum))
414 (fixnum-plus-p (not (minusp fixnum)))
415 (bignum (if bignum-plus-p bignum (negate-bignum bignum)))
416 (bignum-len (%bignum-length bignum))
417 (fixnum (if fixnum-plus-p fixnum (- fixnum)))
418 (result (%allocate-bignum (1+ bignum-len)))
419 (carry-digit 0))
420 (declare (type bignum bignum result)
421 (type bignum-element-type fixnum carry-digit))
422 (dotimes (index bignum-len)
423 (declare (type bignum-index index))
424 (multiple-value-bind (next-digit low)
425 (%multiply-and-add (%bignum-ref bignum index) fixnum carry-digit)
426 (declare (type bignum-element-type next-digit low))
427 (setf carry-digit next-digit)
428 (setf (%bignum-ref result index) low)))
429 (setf (%bignum-ref result bignum-len) carry-digit)
430 (unless (eq bignum-plus-p fixnum-plus-p)
431 (negate-bignum-in-place result))
432 (%normalize-bignum result (1+ bignum-len))))
434 (defun multiply-fixnums (a b)
435 (declare (fixnum a b))
436 (declare (muffle-conditions compiler-note)) ; returns lispobj, so what.
437 (let* ((a-minusp (minusp a))
438 (b-minusp (minusp b)))
439 (multiple-value-bind (high low)
440 (%multiply (if a-minusp (- a) a)
441 (if b-minusp (- b) b))
442 (declare (type bignum-element-type high low))
443 (if (and (zerop high)
444 (%digit-0-or-plusp low))
445 (let ((low (truly-the (unsigned-byte #.(1- sb!vm:n-word-bits))
446 (%fixnum-digit-with-correct-sign low))))
447 (if (eq a-minusp b-minusp)
449 (- low)))
450 (let ((res (%allocate-bignum 2)))
451 (%bignum-set res 0 low)
452 (%bignum-set res 1 high)
453 (unless (eq a-minusp b-minusp) (negate-bignum-in-place res))
454 (%normalize-bignum res 2))))))
456 ;;;; BIGNUM-REPLACE and WITH-BIGNUM-BUFFERS
458 (eval-when (:compile-toplevel :execute)
460 (sb!xc:defmacro bignum-replace (dest
462 &key
463 (start1 '0)
464 end1
465 (start2 '0)
466 end2
467 from-end)
468 (once-only ((n-dest dest)
469 (n-src src))
470 (with-unique-names (n-start1 n-end1 n-start2 n-end2 i1 i2)
471 (let ((end1 (or end1 `(%bignum-length ,n-dest)))
472 (end2 (or end2 `(%bignum-length ,n-src))))
473 (if from-end
474 `(let ((,n-start1 ,start1)
475 (,n-start2 ,start2))
476 (do ((,i1 (1- ,end1) (1- ,i1))
477 (,i2 (1- ,end2) (1- ,i2)))
478 ((or (< ,i1 ,n-start1) (< ,i2 ,n-start2)))
479 (declare (fixnum ,i1 ,i2))
480 (%bignum-set ,n-dest ,i1 (%bignum-ref ,n-src ,i2))))
481 (if (eql start1 start2)
482 `(let ((,n-end1 (min ,end1 ,end2)))
483 (do ((,i1 ,start1 (1+ ,i1)))
484 ((>= ,i1 ,n-end1))
485 (declare (type bignum-index ,i1))
486 (%bignum-set ,n-dest ,i1 (%bignum-ref ,n-src ,i1))))
487 `(let ((,n-end1 ,end1)
488 (,n-end2 ,end2))
489 (do ((,i1 ,start1 (1+ ,i1))
490 (,i2 ,start2 (1+ ,i2)))
491 ((or (>= ,i1 ,n-end1) (>= ,i2 ,n-end2)))
492 (declare (type bignum-index ,i1 ,i2))
493 (%bignum-set ,n-dest ,i1 (%bignum-ref ,n-src ,i2))))))))))
495 (sb!xc:defmacro with-bignum-buffers (specs &body body)
496 "WITH-BIGNUM-BUFFERS ({(var size [init])}*) Form*"
497 (collect ((binds) (inits))
498 (dolist (spec specs)
499 (let ((name (first spec))
500 (size (second spec)))
501 (binds `(,name (%allocate-bignum ,size)))
502 (let ((init (third spec)))
503 (when init
504 (inits `(bignum-replace ,name ,init))))))
505 `(let* ,(binds)
506 ,@(inits)
507 ,@body)))
509 ) ;EVAL-WHEN
511 ;;;; GCD
513 (eval-when (:compile-toplevel :load-toplevel :execute)
514 ;; The asserts in the GCD implementation are way too expensive to
515 ;; check in normal use, and are disabled here.
516 (sb!xc:defmacro gcd-assert (&rest args)
517 (declare (ignore args))
518 #+sb-bignum-assertions `(assert ,@args))
519 ;; We'll be doing a lot of modular arithmetic.
520 (sb!xc:defmacro modularly (form)
521 `(logand all-ones-digit ,form)))
523 ;;; I'm not sure why I need this FTYPE declaration. Compiled by the
524 ;;; target compiler, it can deduce the return type fine, but without
525 ;;; it, we pay a heavy price in BIGNUM-GCD when compiled by the
526 ;;; cross-compiler. -- CSR, 2004-07-19
527 (declaim (ftype (sfunction (bignum bignum-length bignum bignum-length)
528 (and unsigned-byte fixnum))
529 bignum-factors-of-two))
530 (defun bignum-factors-of-two (a len-a b len-b)
531 (declare (type bignum-length len-a len-b) (type bignum a b))
532 (do ((i 0 (1+ i))
533 (end (min len-a len-b)))
534 ((= i end) (error "Unexpected zero bignums?"))
535 (declare (type bignum-index i)
536 (type bignum-length end))
537 (let ((or-digits (%logior (%bignum-ref a i) (%bignum-ref b i))))
538 (unless (zerop or-digits)
539 (return (do ((j 0 (1+ j))
540 (or-digits or-digits (%ashr or-digits 1)))
541 ((oddp or-digits) (+ (* i digit-size) j))
542 (declare (type (mod #.sb!vm:n-word-bits) j))))))))
544 ;;; Multiply a bignum buffer with a fixnum or a digit, storing the
545 ;;; result in another bignum buffer, and without using any
546 ;;; temporaries. Inlined to avoid boxing smallnum if it's actually a
547 ;;; digit. Needed by GCD, should possibly OAOO with
548 ;;; MULTIPLY-BIGNUM-AND-FIXNUM.
549 (declaim (inline multiply-bignum-buffer-and-smallnum-to-buffer))
550 (defun multiply-bignum-buffer-and-smallnum-to-buffer (bignum bignum-len
551 smallnum res)
552 (declare (type bignum bignum))
553 (let* ((bignum-plus-p (%bignum-0-or-plusp bignum bignum-len))
554 (smallnum-plus-p (not (minusp smallnum)))
555 (smallnum (if smallnum-plus-p smallnum (- smallnum)))
556 (carry-digit 0))
557 (declare (type bignum bignum res)
558 (type bignum-length bignum-len)
559 (type bignum-element-type smallnum carry-digit))
560 (unless bignum-plus-p
561 (negate-bignum-buffer-in-place bignum bignum-len))
562 (dotimes (index bignum-len)
563 (declare (type bignum-index index))
564 (multiple-value-bind (next-digit low)
565 (%multiply-and-add (%bignum-ref bignum index)
566 smallnum
567 carry-digit)
568 (declare (type bignum-element-type next-digit low))
569 (setf carry-digit next-digit)
570 (setf (%bignum-ref res index) low)))
571 (setf (%bignum-ref res bignum-len) carry-digit)
572 (unless bignum-plus-p
573 (negate-bignum-buffer-in-place bignum bignum-len))
574 (let ((res-len (%normalize-bignum-buffer res (1+ bignum-len))))
575 (unless (eq bignum-plus-p smallnum-plus-p)
576 (negate-bignum-buffer-in-place res res-len))
577 res-len)))
579 ;;; Given U and V, return U / V mod 2^32. Implements the algorithm in the
580 ;;; paper, but uses some clever bit-twiddling nicked from Nickle to do it.
581 (declaim (inline bmod))
582 (defun bmod (u v)
583 (declare (muffle-conditions compiler-note)) ; returns lispobj, so what.
584 (let ((ud (%bignum-ref u 0))
585 (vd (%bignum-ref v 0))
586 (umask 0)
587 (imask 1)
588 (m 0))
589 (declare (type (unsigned-byte #.sb!vm:n-word-bits) ud vd umask imask m))
590 (dotimes (i digit-size)
591 (setf umask (logior umask imask))
592 (when (logtest ud umask)
593 (setf ud (modularly (- ud vd)))
594 (setf m (modularly (logior m imask))))
595 (setf imask (modularly (ash imask 1)))
596 (setf vd (modularly (ash vd 1))))
599 (defun dmod (u u-len v v-len tmp1)
600 (loop while (> (bignum-buffer-integer-length u u-len)
601 (+ (bignum-buffer-integer-length v v-len)
602 digit-size))
604 (unless (zerop (%bignum-ref u 0))
605 (let* ((bmod (bmod u v))
606 (tmp1-len (multiply-bignum-buffer-and-smallnum-to-buffer v v-len
607 bmod
608 tmp1)))
609 (setf u-len (subtract-bignum-buffers u u-len
610 tmp1 tmp1-len
612 (bignum-abs-buffer u u-len)))
613 (gcd-assert (zerop (%bignum-ref u 0)))
614 (setf u-len (bignum-buffer-ashift-right u u-len digit-size)))
615 (let* ((d (+ 1 (- (bignum-buffer-integer-length u u-len)
616 (bignum-buffer-integer-length v v-len))))
617 (n (1- (ash 1 d))))
618 (declare (type (unsigned-byte #.(integer-length #.sb!vm:n-word-bits)) d)
619 (type (unsigned-byte #.sb!vm:n-word-bits) n))
620 (gcd-assert (>= d 0))
621 (when (logtest (%bignum-ref u 0) n)
622 (let ((tmp1-len
623 (multiply-bignum-buffer-and-smallnum-to-buffer v v-len
624 (logand n (bmod u
626 tmp1)))
627 (setf u-len (subtract-bignum-buffers u u-len
628 tmp1 tmp1-len
630 (bignum-abs-buffer u u-len)))
631 u-len))
633 (defconstant lower-ones-digit (1- (ash 1 (truncate sb!vm:n-word-bits 2))))
635 ;;; Find D and N such that (LOGAND ALL-ONES-DIGIT (- (* D X) (* N Y))) is 0,
636 ;;; (< 0 N LOWER-ONES-DIGIT) and (< 0 (ABS D) LOWER-ONES-DIGIT).
637 (defun reduced-ratio-mod (x y)
638 (let* ((c (bmod x y))
639 (n1 c)
640 (d1 1)
641 (n2 (modularly (1+ (modularly (lognot n1)))))
642 (d2 (modularly -1)))
643 (declare (type (unsigned-byte #.sb!vm:n-word-bits) n1 d1 n2 d2))
644 (loop while (> n2 (expt 2 (truncate digit-size 2))) do
645 (loop for i of-type (mod #.sb!vm:n-word-bits)
646 downfrom (- (integer-length n1) (integer-length n2))
647 while (>= n1 n2) do
648 (when (>= n1 (modularly (ash n2 i)))
649 (psetf n1 (modularly (- n1 (modularly (ash n2 i))))
650 d1 (modularly (- d1 (modularly (ash d2 i)))))))
651 (psetf n1 n2
652 d1 d2
653 n2 n1
654 d2 d1))
655 (values n2 (if (>= d2 (expt 2 (1- digit-size)))
656 (lognot (logand most-positive-fixnum (lognot d2)))
657 (logand lower-ones-digit d2)))))
660 (defun copy-bignum (a &optional (len (%bignum-length a)))
661 (let ((b (%allocate-bignum len)))
662 (bignum-replace b a)
663 (%bignum-set-length b len)
666 ;;; Allocate a single word bignum that holds fixnum. This is useful when
667 ;;; we are trying to mix fixnum and bignum operands.
668 #!-sb-fluid (declaim (inline make-small-bignum))
669 (defun make-small-bignum (fixnum)
670 (let ((res (%allocate-bignum 1)))
671 (setf (%bignum-ref res 0) (%fixnum-to-digit fixnum))
672 res))
674 ;; When the larger number is less than this many bignum digits long, revert
675 ;; to old algorithm.
676 (defparameter *accelerated-gcd-cutoff* 3)
678 ;;; Alternate between k-ary reduction with the help of
679 ;;; REDUCED-RATIO-MOD and digit modulus reduction via DMOD. Once the
680 ;;; arguments get small enough, drop through to BIGNUM-MOD-GCD (since
681 ;;; k-ary reduction can introduce spurious factors, which need to be
682 ;;; filtered out). Reference: Kenneth Weber, "The accelerated integer
683 ;;; GCD algorithm", ACM Transactions on Mathematical Software, volume
684 ;;; 21, number 1, March 1995, epp. 111-122.
685 (defun bignum-gcd (u0 v0)
686 (declare (type bignum u0 v0))
687 (let* ((u1 (if (bignum-plus-p u0)
689 (negate-bignum u0 nil)))
690 (v1 (if (bignum-plus-p v0)
692 (negate-bignum v0 nil))))
693 (if (zerop v1)
694 (return-from bignum-gcd u1))
695 (when (> u1 v1)
696 (rotatef u1 v1))
697 (let ((n (mod v1 u1)))
698 (setf v1 (if (fixnump n)
699 (make-small-bignum n)
700 n)))
701 (if (and (= 1 (%bignum-length v1))
702 (zerop (%bignum-ref v1 0)))
703 (return-from bignum-gcd (%normalize-bignum u1
704 (%bignum-length u1))))
705 (let* ((buffer-len (+ 2 (%bignum-length u1)))
706 (u (%allocate-bignum buffer-len))
707 (u-len (%bignum-length u1))
708 (v (%allocate-bignum buffer-len))
709 (v-len (%bignum-length v1))
710 (tmp1 (%allocate-bignum buffer-len))
711 (tmp1-len 0)
712 (tmp2 (%allocate-bignum buffer-len))
713 (tmp2-len 0)
714 (factors-of-two
715 (bignum-factors-of-two u1 (%bignum-length u1)
716 v1 (%bignum-length v1))))
717 (declare (type (or null bignum-length)
718 buffer-len u-len v-len tmp1-len tmp2-len))
719 (bignum-replace u u1)
720 (bignum-replace v v1)
721 (setf u-len
722 (make-gcd-bignum-odd u
723 (bignum-buffer-ashift-right u u-len
724 factors-of-two)))
725 (setf v-len
726 (make-gcd-bignum-odd v
727 (bignum-buffer-ashift-right v v-len
728 factors-of-two)))
729 (loop until (or (< u-len *accelerated-gcd-cutoff*)
730 (not v-len)
731 (zerop v-len)
732 (and (= 1 v-len)
733 (zerop (%bignum-ref v 0))))
735 (gcd-assert (= buffer-len (%bignum-length u)
736 (%bignum-length v)
737 (%bignum-length tmp1)
738 (%bignum-length tmp2)))
739 (if (> (bignum-buffer-integer-length u u-len)
740 (+ #.(truncate sb!vm:n-word-bits 4)
741 (bignum-buffer-integer-length v v-len)))
742 (setf u-len (dmod u u-len
743 v v-len
744 tmp1))
745 (multiple-value-bind (n d) (reduced-ratio-mod u v)
746 (setf tmp1-len
747 (multiply-bignum-buffer-and-smallnum-to-buffer v v-len
748 n tmp1))
749 (setf tmp2-len
750 (multiply-bignum-buffer-and-smallnum-to-buffer u u-len
751 d tmp2))
752 (gcd-assert (= (copy-bignum tmp2 tmp2-len)
753 (* (copy-bignum u u-len) d)))
754 (gcd-assert (= (copy-bignum tmp1 tmp1-len)
755 (* (copy-bignum v v-len) n)))
756 (setf u-len
757 (subtract-bignum-buffers-with-len tmp1 tmp1-len
758 tmp2 tmp2-len
760 (1+ (max tmp1-len
761 tmp2-len))))
762 (gcd-assert (or (zerop (- (copy-bignum tmp1 tmp1-len)
763 (copy-bignum tmp2 tmp2-len)))
764 (= (copy-bignum u u-len)
765 (- (copy-bignum tmp1 tmp1-len)
766 (copy-bignum tmp2 tmp2-len)))))
767 (bignum-abs-buffer u u-len)
768 (gcd-assert (zerop (modularly u)))))
769 (setf u-len (make-gcd-bignum-odd u u-len))
770 (rotatef u v)
771 (rotatef u-len v-len))
772 (bignum-abs-buffer u u-len)
773 (setf u (copy-bignum u u-len))
774 (let ((n (bignum-mod-gcd v1 u)))
775 (ash (bignum-mod-gcd u1 (if (fixnump n)
776 (make-small-bignum n)
778 factors-of-two)))))
780 (defun bignum-mod-gcd (a b)
781 (declare (type bignum a b))
782 (when (< a b)
783 (rotatef a b))
784 ;; While the length difference of A and B is sufficiently large,
785 ;; reduce using MOD (slowish, but it should equalize the sizes of
786 ;; A and B pretty quickly). After that, use the binary GCD
787 ;; algorithm to handle the rest.
788 (loop until (and (= (%bignum-length b) 1) (zerop (%bignum-ref b 0))) do
789 (when (<= (%bignum-length a) (1+ (%bignum-length b)))
790 (return-from bignum-mod-gcd (bignum-binary-gcd a b)))
791 (let ((rem (mod a b)))
792 (if (fixnump rem)
793 (setf a (make-small-bignum rem))
794 (setf a rem))
795 (rotatef a b)))
796 (if (= (%bignum-length a) 1)
797 (%normalize-bignum a 1)
800 (defun bignum-binary-gcd (a b)
801 (declare (type bignum a b))
802 (let* ((len-a (%bignum-length a))
803 (len-b (%bignum-length b)))
804 (with-bignum-buffers ((a-buffer len-a a)
805 (b-buffer len-b b)
806 (res-buffer (max len-a len-b)))
807 (let* ((factors-of-two
808 (bignum-factors-of-two a-buffer len-a
809 b-buffer len-b))
810 (len-a (make-gcd-bignum-odd
811 a-buffer
812 (bignum-buffer-ashift-right a-buffer len-a
813 factors-of-two)))
814 (len-b (make-gcd-bignum-odd
815 b-buffer
816 (bignum-buffer-ashift-right b-buffer len-b
817 factors-of-two))))
818 (declare (type bignum-length len-a len-b))
819 (let ((x a-buffer)
820 (len-x len-a)
821 (y b-buffer)
822 (len-y len-b)
823 (z res-buffer))
824 (loop
825 (multiple-value-bind (u v len-v r len-r)
826 (bignum-gcd-order-and-subtract x len-x y len-y z)
827 (declare (type bignum-length len-v len-r))
828 (when (and (= len-r 1) (zerop (%bignum-ref r 0)))
829 (if (zerop factors-of-two)
830 (let ((ret (%allocate-bignum len-v)))
831 (dotimes (i len-v)
832 (setf (%bignum-ref ret i) (%bignum-ref v i)))
833 (return (%normalize-bignum ret len-v)))
834 (return (bignum-ashift-left v factors-of-two len-v))))
835 (setf x v len-x len-v)
836 (setf y r len-y (make-gcd-bignum-odd r len-r))
837 (setf z u))))))))
839 (defun bignum-gcd-order-and-subtract (a len-a b len-b res)
840 (declare (type bignum-length len-a len-b) (type bignum a b))
841 (cond ((= len-a len-b)
842 (do ((i (1- len-a) (1- i)))
843 ((= i -1)
844 (setf (%bignum-ref res 0) 0)
845 (values a b len-b res 1))
846 (let ((a-digit (%bignum-ref a i))
847 (b-digit (%bignum-ref b i)))
848 (cond ((= a-digit b-digit))
849 ((> a-digit b-digit)
850 (return
851 (values a b len-b res
852 (subtract-bignum-buffers a len-a b len-b
853 res))))
855 (return
856 (values b a len-a res
857 (subtract-bignum-buffers b len-b
858 a len-a
859 res))))))))
860 ((> len-a len-b)
861 (values a b len-b res
862 (subtract-bignum-buffers a len-a b len-b res)))
864 (values b a len-a res
865 (subtract-bignum-buffers b len-b a len-a res)))))
867 (defun make-gcd-bignum-odd (a len-a)
868 (declare (type bignum a) (type bignum-length len-a))
869 (dotimes (index len-a)
870 (declare (type bignum-index index))
871 (do ((digit (%bignum-ref a index) (%ashr digit 1))
872 (increment 0 (1+ increment)))
873 ((zerop digit))
874 (declare (type (mod #.sb!vm:n-word-bits) increment))
875 (when (oddp digit)
876 (return-from make-gcd-bignum-odd
877 (bignum-buffer-ashift-right a len-a
878 (+ (* index digit-size)
879 increment)))))))
882 ;;;; negation
884 (eval-when (:compile-toplevel :execute)
886 ;;; This negates bignum-len digits of bignum, storing the resulting digits into
887 ;;; result (possibly EQ to bignum) and returning whatever end-carry there is.
888 (sb!xc:defmacro bignum-negate-loop
889 (bignum bignum-len &optional (result nil resultp))
890 (with-unique-names (carry end value last)
891 `(let* (,@(if (not resultp) `(,last))
892 (,carry
893 (multiple-value-bind (,value ,carry)
894 (%add-with-carry (%lognot (%bignum-ref ,bignum 0)) 1 0)
895 ,(if resultp
896 `(setf (%bignum-ref ,result 0) ,value)
897 `(setf ,last ,value))
898 ,carry))
899 (i 1)
900 (,end ,bignum-len))
901 (declare (type bit ,carry)
902 (type bignum-index i)
903 (type bignum-length ,end))
904 (loop
905 (when (= i ,end) (return))
906 (multiple-value-bind (,value temp)
907 (%add-with-carry (%lognot (%bignum-ref ,bignum i)) 0 ,carry)
908 ,(if resultp
909 `(setf (%bignum-ref ,result i) ,value)
910 `(setf ,last ,value))
911 (setf ,carry temp))
912 (incf i))
913 ,(if resultp carry `(values ,carry ,last)))))
915 ) ; EVAL-WHEN
917 ;;; Fully-normalize is an internal optional. It cause this to always return
918 ;;; a bignum, without any extraneous digits, and it never returns a fixnum.
919 (defun negate-bignum (x &optional (fully-normalize t))
920 (declare (type bignum x))
921 (let* ((len-x (%bignum-length x))
922 (len-res (1+ len-x))
923 (res (%allocate-bignum len-res)))
924 (declare (type bignum-length len-x len-res)) ;Test len-res for range?
925 (let ((carry (bignum-negate-loop x len-x res)))
926 (setf (%bignum-ref res len-x)
927 (%add-with-carry (%lognot (%sign-digit x len-x)) 0 carry)))
928 (if fully-normalize
929 (%normalize-bignum res len-res)
930 (%mostly-normalize-bignum res len-res))))
932 ;;; This assumes bignum is positive; that is, the result of negating it will
933 ;;; stay in the provided allocated bignum.
934 (declaim (maybe-inline negate-bignum-buffer-in-place))
935 (defun negate-bignum-buffer-in-place (bignum bignum-len)
936 (bignum-negate-loop bignum bignum-len bignum)
937 bignum)
939 (defun negate-bignum-in-place (bignum)
940 (declare (inline negate-bignum-buffer-in-place))
941 (negate-bignum-buffer-in-place bignum (%bignum-length bignum)))
943 (defun bignum-abs-buffer (bignum len)
944 (unless (%bignum-0-or-plusp bignum len)
945 (negate-bignum-buffer-in-place bignum len)))
947 ;;;; shifting
949 (eval-when (:compile-toplevel :execute)
951 ;;; This macro is used by BIGNUM-ASHIFT-RIGHT, BIGNUM-BUFFER-ASHIFT-RIGHT, and
952 ;;; BIGNUM-LDB-BIGNUM-RES. They supply a termination form that references
953 ;;; locals established by this form. Source is the source bignum. Start-digit
954 ;;; is the first digit in source from which we pull bits. Start-pos is the
955 ;;; first bit we want. Res-len-form is the form that computes the length of
956 ;;; the resulting bignum. Termination is a DO termination form with a test and
957 ;;; body. When result is supplied, it is the variable to which this binds a
958 ;;; newly allocated bignum.
960 ;;; Given start-pos, 1-31 inclusively, of shift, we form the j'th resulting
961 ;;; digit from high bits of the i'th source digit and the start-pos number of
962 ;;; bits from the i+1'th source digit.
963 (sb!xc:defmacro shift-right-unaligned (source
964 start-digit
965 start-pos
966 res-len-form
967 termination
968 &optional result)
969 `(let* ((high-bits-in-first-digit (- digit-size ,start-pos))
970 (res-len ,res-len-form)
971 (res-len-1 (1- res-len))
972 ,@(if result `((,result (%allocate-bignum res-len)))))
973 (declare (type bignum-length res-len res-len-1))
974 (do ((i ,start-digit (1+ i))
975 (j 0 (1+ j)))
976 ,termination
977 (declare (type bignum-index i j))
978 (setf (%bignum-ref ,(if result result source) j)
979 (%logior (%digit-logical-shift-right (%bignum-ref ,source i)
980 ,start-pos)
981 (%ashl (%bignum-ref ,source (1+ i))
982 high-bits-in-first-digit))))))
984 ) ; EVAL-WHEN
986 ;;; First compute the number of whole digits to shift, shifting them by
987 ;;; skipping them when we start to pick up bits, and the number of bits to
988 ;;; shift the remaining digits into place. If the number of digits is greater
989 ;;; than the length of the bignum, then the result is either 0 or -1. If we
990 ;;; shift on a digit boundary (that is, n-bits is zero), then we just copy
991 ;;; digits. The last branch handles the general case which uses a macro that a
992 ;;; couple other routines use. The fifth argument to the macro references
993 ;;; locals established by the macro.
994 (defun bignum-ashift-right (bignum count)
995 (declare (type bignum bignum)
996 (type unsigned-byte count))
997 (let ((bignum-len (%bignum-length bignum)))
998 (cond ((fixnump count)
999 (multiple-value-bind (digits n-bits) (truncate count digit-size)
1000 (declare (type bignum-length digits))
1001 (cond
1002 ((>= digits bignum-len)
1003 (if (%bignum-0-or-plusp bignum bignum-len) 0 -1))
1004 ((zerop n-bits)
1005 (bignum-ashift-right-digits bignum digits))
1007 (shift-right-unaligned bignum digits n-bits (- bignum-len digits)
1008 ((= j res-len-1)
1009 (setf (%bignum-ref res j)
1010 (%ashr (%bignum-ref bignum i) n-bits))
1011 (%normalize-bignum res res-len))
1012 res)))))
1013 ((> count bignum-len)
1014 (if (%bignum-0-or-plusp bignum bignum-len) 0 -1))
1015 ;; Since a FIXNUM should be big enough to address anything in
1016 ;; memory, including arrays of bits, and since arrays of bits
1017 ;; take up about the same space as corresponding fixnums, there
1018 ;; should be no way that we fall through to this case: any shift
1019 ;; right by a bignum should give zero. But let's check anyway:
1020 (t (error "bignum overflow: can't shift right by ~S" count)))))
1022 (defun bignum-ashift-right-digits (bignum digits)
1023 (declare (type bignum bignum)
1024 (type bignum-length digits))
1025 (let* ((res-len (- (%bignum-length bignum) digits))
1026 (res (%allocate-bignum res-len)))
1027 (declare (type bignum-length res-len)
1028 (type bignum res))
1029 (bignum-replace res bignum :start2 digits)
1030 (%normalize-bignum res res-len)))
1032 ;;; GCD uses this for an in-place shifting operation. This is different enough
1033 ;;; from BIGNUM-ASHIFT-RIGHT that it isn't worth folding the bodies into a
1034 ;;; macro, but they share the basic algorithm. This routine foregoes a first
1035 ;;; test for digits being greater than or equal to bignum-len since that will
1036 ;;; never happen for its uses in GCD. We did fold the last branch into a macro
1037 ;;; since it was duplicated a few times, and the fifth argument to it
1038 ;;; references locals established by the macro.
1039 (defun bignum-buffer-ashift-right (bignum bignum-len x)
1040 (declare (type bignum-length bignum-len) (fixnum x))
1041 (multiple-value-bind (digits n-bits) (truncate x digit-size)
1042 (declare (type bignum-length digits))
1043 (cond
1044 ((zerop n-bits)
1045 (let ((new-end (- bignum-len digits)))
1046 (bignum-replace bignum bignum :end1 new-end :start2 digits
1047 :end2 bignum-len)
1048 (%normalize-bignum-buffer bignum new-end)))
1050 (shift-right-unaligned bignum digits n-bits (- bignum-len digits)
1051 ((= j res-len-1)
1052 (setf (%bignum-ref bignum j)
1053 (%ashr (%bignum-ref bignum i) n-bits))
1054 (%normalize-bignum-buffer bignum res-len)))))))
1056 ;;; This handles shifting a bignum buffer to provide fresh bignum data for some
1057 ;;; internal routines. We know bignum is safe when called with bignum-len.
1058 ;;; First we compute the number of whole digits to shift, shifting them
1059 ;;; starting to store farther along the result bignum. If we shift on a digit
1060 ;;; boundary (that is, n-bits is zero), then we just copy digits. The last
1061 ;;; branch handles the general case.
1062 (defun bignum-ashift-left (bignum x &optional bignum-len)
1063 (declare (type bignum bignum)
1064 (type unsigned-byte x)
1065 (type (or null bignum-length) bignum-len))
1066 (if (fixnump x)
1067 (multiple-value-bind (digits n-bits) (truncate x digit-size)
1068 (let* ((bignum-len (or bignum-len (%bignum-length bignum)))
1069 (res-len (+ digits bignum-len 1)))
1070 (when (> res-len sb!kernel:maximum-bignum-length)
1071 (error "can't represent result of left shift"))
1072 (if (zerop n-bits)
1073 (bignum-ashift-left-digits bignum bignum-len digits)
1074 (bignum-ashift-left-unaligned bignum digits n-bits res-len))))
1075 ;; Left shift by a number too big to be represented as a fixnum
1076 ;; would exceed our memory capacity, since a fixnum is big enough
1077 ;; to index any array, including a bit array.
1078 (error "can't represent result of left shift")))
1080 (defun bignum-ashift-left-digits (bignum bignum-len digits)
1081 (declare (type bignum-length bignum-len digits))
1082 (let* ((res-len (+ bignum-len digits))
1083 (res (%allocate-bignum res-len)))
1084 (declare (type bignum-length res-len))
1085 (bignum-replace res bignum :start1 digits :end1 res-len :end2 bignum-len
1086 :from-end t)
1087 res))
1089 ;;; BIGNUM-TRUNCATE uses this to store into a bignum buffer by supplying res.
1090 ;;; When res comes in non-nil, then this foregoes allocating a result, and it
1091 ;;; normalizes the buffer instead of the would-be allocated result.
1093 ;;; We start storing into one digit higher than digits, storing a whole result
1094 ;;; digit from parts of two contiguous digits from bignum. When the loop
1095 ;;; finishes, we store the remaining bits from bignum's first digit in the
1096 ;;; first non-zero result digit, digits. We also grab some left over high
1097 ;;; bits from the last digit of bignum.
1098 (defun bignum-ashift-left-unaligned (bignum digits n-bits res-len
1099 &optional (res nil resp))
1100 (declare (type bignum-length digits res-len)
1101 (type (mod #.digit-size) n-bits))
1102 (let* ((remaining-bits (- digit-size n-bits))
1103 (res-len-1 (1- res-len))
1104 (res (or res (%allocate-bignum res-len))))
1105 (declare (type bignum-length res-len res-len-1))
1106 (do ((i 0 (1+ i))
1107 (j (1+ digits) (1+ j)))
1108 ((= j res-len-1)
1109 (setf (%bignum-ref res digits)
1110 (%ashl (%bignum-ref bignum 0) n-bits))
1111 (setf (%bignum-ref res j)
1112 (%ashr (%bignum-ref bignum i) remaining-bits))
1113 (if resp
1114 (%normalize-bignum-buffer res res-len)
1115 (%normalize-bignum res res-len)))
1116 (declare (type bignum-index i j))
1117 (setf (%bignum-ref res j)
1118 (%logior (%digit-logical-shift-right (%bignum-ref bignum i)
1119 remaining-bits)
1120 (%ashl (%bignum-ref bignum (1+ i)) n-bits))))))
1122 ;;; FIXNUM is assumed to be non-zero and the result of the shift should be a bignum
1123 (defun bignum-ashift-left-fixnum (fixnum count)
1124 (declare (bignum-length count)
1125 (fixnum fixnum))
1126 (multiple-value-bind (right-zero-digits remaining)
1127 (truncate count digit-size)
1128 (let* ((right-half (ldb (byte digit-size 0)
1129 (ash fixnum remaining)))
1130 (sign-bit-p
1131 (logbitp (1- digit-size) right-half))
1132 (left-half (ash fixnum
1133 (- remaining digit-size)))
1134 ;; Even if the left-half is 0 or -1 it might need to be sign
1135 ;; extended based on the left-most bit of the right-half
1136 (left-half-p (if sign-bit-p
1137 (/= left-half -1)
1138 (/= left-half 0)))
1139 (length (+ right-zero-digits
1140 (if left-half-p 2 1)))
1141 (result (%allocate-bignum length)))
1142 (setf (%bignum-ref result right-zero-digits) right-half)
1143 (when left-half-p
1144 (setf (%bignum-ref result (1+ right-zero-digits))
1145 (ldb (byte digit-size 0) left-half)))
1146 result)))
1148 ;;;; relational operators
1150 ;;; This compares two bignums returning -1, 0, or 1, depending on
1151 ;;; whether a is less than, equal to, or greater than b.
1152 (declaim (ftype (function (bignum bignum) (integer -1 1)) bignum-compare))
1153 (defun bignum-compare (a b)
1154 (declare (type bignum a b))
1155 (let* ((len-a (%bignum-length a))
1156 (len-b (%bignum-length b))
1157 (a-plusp (%bignum-0-or-plusp a len-a))
1158 (b-plusp (%bignum-0-or-plusp b len-b)))
1159 (declare (type bignum-length len-a len-b))
1160 (cond ((not (eq a-plusp b-plusp))
1161 (if a-plusp 1 -1))
1162 ((= len-a len-b)
1163 (do ((i (1- len-a) (1- i)))
1164 (())
1165 (declare (type bignum-index i))
1166 (let ((a-digit (%bignum-ref a i))
1167 (b-digit (%bignum-ref b i)))
1168 (declare (type bignum-element-type a-digit b-digit))
1169 (when (> a-digit b-digit)
1170 (return 1))
1171 (when (> b-digit a-digit)
1172 (return -1)))
1173 (when (zerop i) (return 0))))
1174 ((> len-a len-b)
1175 (if a-plusp 1 -1))
1176 (t (if a-plusp -1 1)))))
1178 ;;;; float conversion
1180 ;;; Make a single or double float with the specified significand,
1181 ;;; exponent and sign.
1182 (defun single-float-from-bits (bits exp plusp)
1183 (declare (fixnum exp))
1184 (declare (optimize #-sb-xc-host (inhibit-warnings 3)))
1185 (let ((res (dpb exp
1186 sb!vm:single-float-exponent-byte
1187 (logandc2 (logand #xffffffff
1188 (%bignum-ref bits 1))
1189 sb!vm:single-float-hidden-bit))))
1190 (make-single-float
1191 (if plusp
1193 (logior res (ash -1 sb!vm:float-sign-shift))))))
1194 (defun double-float-from-bits (bits exp plusp)
1195 (declare (fixnum exp))
1196 (declare (optimize #-sb-xc-host (inhibit-warnings 3)))
1197 (let ((hi (dpb exp
1198 sb!vm:double-float-exponent-byte
1199 (logandc2 (ecase sb!vm::n-word-bits
1200 (32 (%bignum-ref bits 2))
1201 (64 (ash (%bignum-ref bits 1) -32)))
1202 sb!vm:double-float-hidden-bit)))
1203 (lo (logand #xffffffff (%bignum-ref bits 1))))
1204 (make-double-float (if plusp
1206 (logior hi (ash -1 sb!vm:float-sign-shift)))
1207 lo)))
1208 #!+(and long-float x86)
1209 (defun long-float-from-bits (bits exp plusp)
1210 (declare (fixnum exp))
1211 (declare (optimize #-sb-xc-host (inhibit-warnings 3)))
1212 (make-long-float
1213 (if plusp
1215 (logior exp (ash 1 15)))
1216 (%bignum-ref bits 2)
1217 (%bignum-ref bits 1)))
1219 ;;; Convert Bignum to a float in the specified Format, rounding to the best
1220 ;;; approximation.
1221 (defun bignum-to-float (bignum format)
1222 (let* ((plusp (bignum-plus-p bignum))
1223 (x (if plusp bignum (negate-bignum bignum)))
1224 (len (bignum-integer-length x))
1225 (digits (float-format-digits format))
1226 (keep (+ digits digit-size))
1227 (shift (- keep len))
1228 (shifted (if (minusp shift)
1229 (bignum-ashift-right x (- shift))
1230 (bignum-ashift-left x shift)))
1231 (low (%bignum-ref shifted 0))
1232 (round-bit (ash 1 (1- digit-size))))
1233 (declare (type bignum-length len digits keep) (fixnum shift))
1234 (labels ((round-up ()
1235 (let ((rounded (add-bignums shifted round-bit)))
1236 (if (> (integer-length rounded) keep)
1237 (float-from-bits (bignum-ashift-right rounded 1)
1238 (1+ len))
1239 (float-from-bits rounded len))))
1240 (float-from-bits (bits len)
1241 (declare (type bignum-length len))
1242 (ecase format
1243 (single-float
1244 (single-float-from-bits
1245 bits
1246 (check-exponent len sb!vm:single-float-bias
1247 sb!vm:single-float-normal-exponent-max)
1248 plusp))
1249 (double-float
1250 (double-float-from-bits
1251 bits
1252 (check-exponent len sb!vm:double-float-bias
1253 sb!vm:double-float-normal-exponent-max)
1254 plusp))
1255 #!+long-float
1256 (long-float
1257 (long-float-from-bits
1258 bits
1259 (check-exponent len sb!vm:long-float-bias
1260 sb!vm:long-float-normal-exponent-max)
1261 plusp))))
1262 (check-exponent (exp bias max)
1263 (declare (type bignum-length len))
1264 (let ((exp (+ exp bias)))
1265 (when (> exp max)
1266 (error 'floating-point-overflow
1267 :operation 'float
1268 :operands (list x format)))
1269 exp)))
1271 (cond
1272 ;; Round down if round bit is 0.
1273 ((not (logtest round-bit low))
1274 (float-from-bits shifted len))
1275 ;; If only round bit is set, then round to even.
1276 ((and (= low round-bit)
1277 (dotimes (i (- (%bignum-length x) (ceiling keep digit-size))
1279 (unless (zerop (%bignum-ref x i)) (return nil))))
1280 (let ((next (%bignum-ref shifted 1)))
1281 (if (oddp next)
1282 (round-up)
1283 (float-from-bits shifted len))))
1284 ;; Otherwise, round up.
1286 (round-up))))))
1288 ;;;; integer length and logbitp/logcount
1290 (defun bignum-buffer-integer-length (bignum len)
1291 (declare (type bignum bignum))
1292 (let* ((len-1 (1- len))
1293 (digit (%bignum-ref bignum len-1)))
1294 (declare (type bignum-length len len-1)
1295 (type bignum-element-type digit))
1296 (+ (integer-length (%fixnum-digit-with-correct-sign digit))
1297 (* len-1 digit-size))))
1299 (defun bignum-integer-length (bignum)
1300 (declare (type bignum bignum))
1301 (bignum-buffer-integer-length bignum (%bignum-length bignum)))
1303 (defun bignum-logbitp (index bignum)
1304 (declare (type bignum bignum)
1305 (type bignum-index index))
1306 (let ((len (%bignum-length bignum)))
1307 (declare (type bignum-length len))
1308 (multiple-value-bind (word-index bit-index)
1309 (floor index digit-size)
1310 (if (>= word-index len)
1311 (not (bignum-plus-p bignum))
1312 (logbitp bit-index (%bignum-ref bignum word-index))))))
1314 (defun bignum-logcount (bignum)
1315 (declare (type bignum bignum)
1316 (optimize speed))
1317 (declare (muffle-conditions compiler-note)) ; returns lispobj, so what.
1318 (let ((length (%bignum-length bignum))
1319 (result 0))
1320 (declare (type bignum-length length)
1321 (fixnum result))
1322 (do ((index 0 (1+ index)))
1323 ((= index length)
1324 (if (%bignum-0-or-plusp bignum length)
1325 result
1326 (- (* length digit-size) result)))
1327 (let ((digit (%bignum-ref bignum index)))
1328 (declare (type bignum-element-type digit))
1329 (incf result (logcount digit))))))
1331 ;;;; logical operations
1333 ;;;; NOT
1335 (defun bignum-logical-not (a)
1336 (declare (type bignum a))
1337 (let* ((len (%bignum-length a))
1338 (res (%allocate-bignum len)))
1339 (declare (type bignum-length len))
1340 (dotimes (i len res)
1341 (declare (type bignum-index i))
1342 (setf (%bignum-ref res i) (%lognot (%bignum-ref a i))))))
1344 ;;;; AND
1346 (defun bignum-logical-and (a b)
1347 (declare (type bignum a b))
1348 (let* ((len-a (%bignum-length a))
1349 (len-b (%bignum-length b))
1350 (a-plusp (%bignum-0-or-plusp a len-a))
1351 (b-plusp (%bignum-0-or-plusp b len-b)))
1352 (declare (type bignum-length len-a len-b))
1353 (cond
1354 ((< len-a len-b)
1355 (if a-plusp
1356 (logand-shorter-positive a len-a b (%allocate-bignum len-a))
1357 (logand-shorter-negative a len-a b len-b (%allocate-bignum len-b))))
1358 ((< len-b len-a)
1359 (if b-plusp
1360 (logand-shorter-positive b len-b a (%allocate-bignum len-b))
1361 (logand-shorter-negative b len-b a len-a (%allocate-bignum len-a))))
1362 (t (logand-shorter-positive a len-a b (%allocate-bignum len-a))))))
1364 ;;; This takes a shorter bignum, a and len-a, that is positive. Because this
1365 ;;; is AND, we don't care about any bits longer than a's since its infinite 0
1366 ;;; sign bits will mask the other bits out of b. The result is len-a big.
1367 (defun logand-shorter-positive (a len-a b res)
1368 (declare (type bignum a b res)
1369 (type bignum-length len-a))
1370 (dotimes (i len-a)
1371 (declare (type bignum-index i))
1372 (setf (%bignum-ref res i)
1373 (%logand (%bignum-ref a i) (%bignum-ref b i))))
1374 (%normalize-bignum res len-a))
1376 ;;; This takes a shorter bignum, a and len-a, that is negative. Because this
1377 ;;; is AND, we just copy any bits longer than a's since its infinite 1 sign
1378 ;;; bits will include any bits from b. The result is len-b big.
1379 (defun logand-shorter-negative (a len-a b len-b res)
1380 (declare (type bignum a b res)
1381 (type bignum-length len-a len-b))
1382 (dotimes (i len-a)
1383 (declare (type bignum-index i))
1384 (setf (%bignum-ref res i)
1385 (%logand (%bignum-ref a i) (%bignum-ref b i))))
1386 (do ((i len-a (1+ i)))
1387 ((= i len-b))
1388 (declare (type bignum-index i))
1389 (setf (%bignum-ref res i) (%bignum-ref b i)))
1390 (%normalize-bignum res len-b))
1392 ;;;; IOR
1394 (defun bignum-logical-ior (a b)
1395 (declare (type bignum a b))
1396 (let* ((len-a (%bignum-length a))
1397 (len-b (%bignum-length b))
1398 (a-plusp (%bignum-0-or-plusp a len-a))
1399 (b-plusp (%bignum-0-or-plusp b len-b)))
1400 (declare (type bignum-length len-a len-b))
1401 (cond
1402 ((< len-a len-b)
1403 (if a-plusp
1404 (logior-shorter-positive a len-a b len-b (%allocate-bignum len-b))
1405 (logior-shorter-negative a len-a b len-b (%allocate-bignum len-b))))
1406 ((< len-b len-a)
1407 (if b-plusp
1408 (logior-shorter-positive b len-b a len-a (%allocate-bignum len-a))
1409 (logior-shorter-negative b len-b a len-a (%allocate-bignum len-a))))
1410 (t (logior-shorter-positive a len-a b len-b (%allocate-bignum len-a))))))
1412 ;;; This takes a shorter bignum, a and len-a, that is positive. Because this
1413 ;;; is IOR, we don't care about any bits longer than a's since its infinite
1414 ;;; 0 sign bits will mask the other bits out of b out to len-b. The result
1415 ;;; is len-b long.
1416 (defun logior-shorter-positive (a len-a b len-b res)
1417 (declare (type bignum a b res)
1418 (type bignum-length len-a len-b))
1419 (dotimes (i len-a)
1420 (declare (type bignum-index i))
1421 (setf (%bignum-ref res i)
1422 (%logior (%bignum-ref a i) (%bignum-ref b i))))
1423 (do ((i len-a (1+ i)))
1424 ((= i len-b))
1425 (declare (type bignum-index i))
1426 (setf (%bignum-ref res i) (%bignum-ref b i)))
1427 (%normalize-bignum res len-b))
1429 ;;; This takes a shorter bignum, a and len-a, that is negative. Because this
1430 ;;; is IOR, we just copy any bits longer than a's since its infinite 1 sign
1431 ;;; bits will include any bits from b. The result is len-b long.
1432 (defun logior-shorter-negative (a len-a b len-b res)
1433 (declare (type bignum a b res)
1434 (type bignum-length len-a len-b))
1435 (dotimes (i len-a)
1436 (declare (type bignum-index i))
1437 (setf (%bignum-ref res i)
1438 (%logior (%bignum-ref a i) (%bignum-ref b i))))
1439 (do ((i len-a (1+ i))
1440 (sign (%sign-digit a len-a)))
1441 ((= i len-b))
1442 (declare (type bignum-index i))
1443 (setf (%bignum-ref res i) sign))
1444 (%normalize-bignum res len-b))
1446 ;;;; XOR
1448 (defun bignum-logical-xor (a b)
1449 (declare (type bignum a b))
1450 (let ((len-a (%bignum-length a))
1451 (len-b (%bignum-length b)))
1452 (declare (type bignum-length len-a len-b))
1453 (if (< len-a len-b)
1454 (bignum-logical-xor-aux a len-a b len-b (%allocate-bignum len-b))
1455 (bignum-logical-xor-aux b len-b a len-a (%allocate-bignum len-a)))))
1457 ;;; This takes the shorter of two bignums in a and len-a. Res is len-b
1458 ;;; long. Do the XOR.
1459 (defun bignum-logical-xor-aux (a len-a b len-b res)
1460 (declare (type bignum a b res)
1461 (type bignum-length len-a len-b))
1462 (dotimes (i len-a)
1463 (declare (type bignum-index i))
1464 (setf (%bignum-ref res i)
1465 (%logxor (%bignum-ref a i) (%bignum-ref b i))))
1466 (do ((i len-a (1+ i))
1467 (sign (%sign-digit a len-a)))
1468 ((= i len-b))
1469 (declare (type bignum-index i))
1470 (setf (%bignum-ref res i) (%logxor sign (%bignum-ref b i))))
1471 (%normalize-bignum res len-b))
1473 ;;;; There used to be a bunch of code to implement "efficient" versions of LDB
1474 ;;;; and DPB here. But it apparently was never used, so it's been deleted.
1475 ;;;; --njf, 2007-02-04
1477 ;; This could be used by way of a transform, though for now it's specifically
1478 ;; a helper for %LDB in the limited case that it recognizes as non-consing.
1479 (defun ldb-bignum=>fixnum (byte-size byte-pos bignum)
1480 (declare (type (integer 0 #.sb!vm:n-positive-fixnum-bits) byte-size)
1481 (type bit-index byte-pos))
1482 (multiple-value-bind (word-index bit-index) (floor byte-pos digit-size)
1483 (let ((n-digits (%bignum-length bignum)))
1484 (cond ((>= word-index n-digits) ; load from the infinitely extended sign word
1485 (ldb (byte byte-size 0) (%sign-digit bignum n-digits)))
1486 ((<= (+ bit-index byte-size) digit-size) ; contained in one word
1487 ;; This case takes care of byte-size = 0 also.
1488 (ldb (byte byte-size bit-index) (%bignum-ref bignum word-index)))
1490 ;; At least one bit is obtained from each of two words,
1491 ;; and not more than two words.
1492 (let* ((low-part-size
1493 (truly-the (integer 1 #.(1- sb!vm:n-positive-fixnum-bits))
1494 (- digit-size bit-index)))
1495 (high-part-size
1496 (truly-the (integer 1 #.(1- sb!vm:n-positive-fixnum-bits))
1497 (- byte-size low-part-size))))
1498 (logior (truly-the (and fixnum unsigned-byte) ; high part
1499 (let ((word-index (1+ word-index)))
1500 (if (< word-index n-digits) ; next word exists
1501 (ash (ldb (byte high-part-size 0)
1502 (%bignum-ref bignum word-index))
1503 low-part-size)
1504 (mask-field (byte high-part-size low-part-size)
1505 (%sign-digit bignum n-digits)))))
1506 (ldb (byte low-part-size bit-index) ; low part
1507 (%bignum-ref bignum word-index)))))))))
1509 ;;;; TRUNCATE
1511 ;;; This is the original sketch of the algorithm from which I implemented this
1512 ;;; TRUNCATE, assuming both operands are bignums. I should modify this to work
1513 ;;; with the documentation on my functions, as a general introduction. I've
1514 ;;; left this here just in case someone needs it in the future. Don't look at
1515 ;;; this unless reading the functions' comments leaves you at a loss. Remember
1516 ;;; this comes from Knuth, so the book might give you the right general
1517 ;;; overview.
1519 ;;; (truncate x y):
1521 ;;; If X's magnitude is less than Y's, then result is 0 with remainder X.
1523 ;;; Make x and y positive, copying x if it is already positive.
1525 ;;; Shift y left until there's a 1 in the 30'th bit (most significant, non-sign
1526 ;;; digit)
1527 ;;; Just do most sig digit to determine how much to shift whole number.
1528 ;;; Shift x this much too.
1529 ;;; Remember this initial shift count.
1531 ;;; Allocate q to be len-x minus len-y quantity plus 1.
1533 ;;; i = last digit of x.
1534 ;;; k = last digit of q.
1536 ;;; LOOP
1538 ;;; j = last digit of y.
1540 ;;; compute guess.
1541 ;;; if x[i] = y[j] then g = (1- (ash 1 digit-size))
1542 ;;; else g = x[i]x[i-1]/y[j].
1544 ;;; check guess.
1545 ;;; %UNSIGNED-MULTIPLY returns b and c defined below.
1546 ;;; a = x[i-1] - (logand (* g y[j]) #xFFFFFFFF).
1547 ;;; Use %UNSIGNED-MULTIPLY taking low-order result.
1548 ;;; b = (logand (ash (* g y[j-1]) (- digit-size)) (1- (ash 1 digit-size))).
1549 ;;; c = (logand (* g y[j-1]) (1- (ash 1 digit-size))).
1550 ;;; if a < b, okay.
1551 ;;; if a > b, guess is too high
1552 ;;; g = g - 1; go back to "check guess".
1553 ;;; if a = b and c > x[i-2], guess is too high
1554 ;;; g = g - 1; go back to "check guess".
1555 ;;; GUESS IS 32-BIT NUMBER, SO USE THING TO KEEP IN SPECIAL REGISTER
1556 ;;; SAME FOR A, B, AND C.
1558 ;;; Subtract g * y from x[i - len-y+1]..x[i]. See paper for doing this in step.
1559 ;;; If x[i] < 0, guess is screwed up.
1560 ;;; negative g, then add 1
1561 ;;; zero or positive g, then subtract 1
1562 ;;; AND add y back into x[len-y+1..i].
1564 ;;; q[k] = g.
1565 ;;; i = i - 1.
1566 ;;; k = k - 1.
1568 ;;; If k>=0, goto LOOP.
1570 ;;; Now quotient is good, but remainder is not.
1571 ;;; Shift x right by saved initial left shifting count.
1573 ;;; Check quotient and remainder signs.
1574 ;;; x pos y pos --> q pos r pos
1575 ;;; x pos y neg --> q neg r pos
1576 ;;; x neg y pos --> q neg r neg
1577 ;;; x neg y neg --> q pos r neg
1579 ;;; Normalize quotient and remainder. Cons result if necessary.
1582 ;;; This used to be split into multiple functions, which shared state
1583 ;;; in special variables *TRUNCATE-X* and *TRUNCATE-Y*. Having so many
1584 ;;; special variable accesses in tight inner loops was having a large
1585 ;;; effect on performance, so the helper functions have now been
1586 ;;; refactored into local functions and the special variables into
1587 ;;; lexicals. There was also a lot of boxing and unboxing of
1588 ;;; (UNSIGNED-BYTE 32)'s going on, which this refactoring
1589 ;;; eliminated. This improves the performance on some CL-BENCH tests
1590 ;;; by up to 50%, which is probably signigicant enough to justify the
1591 ;;; reduction in readability that was introduced. --JES, 2004-08-07
1592 (defun bignum-truncate (x y)
1593 (declare (type bignum x y))
1594 (declare (muffle-conditions compiler-note)) ; returns lispobj, so what.
1595 (let (truncate-x truncate-y)
1596 (labels
1597 ;;; Divide X by Y when Y is a single bignum digit. BIGNUM-TRUNCATE
1598 ;;; fixes up the quotient and remainder with respect to sign and
1599 ;;; normalization.
1601 ;;; We don't have to worry about shifting Y to make its most
1602 ;;; significant digit sufficiently large for %BIGFLOOR to return
1603 ;;; digit-size quantities for the q-digit and r-digit. If Y is
1604 ;;; a single digit bignum, it is already large enough for
1605 ;;; %BIGFLOOR. That is, it has some bits on pretty high in the
1606 ;;; digit.
1607 ((bignum-truncate-single-digit (x len-x y)
1608 (declare (type bignum-length len-x))
1609 (let ((y (%bignum-ref y 0)))
1610 (declare (type bignum-element-type y))
1611 (if (not (logtest y (1- y)))
1612 ;; Y is a power of two.
1613 ;; SHIFT-RIGHT-UNALIGNED won't do the right thing
1614 ;; with a shift count of 0 or -1, so special case this.
1615 (cond ((= y 0)
1616 (error 'division-by-zero :operation 'truncate
1617 :operands (list x y)))
1618 ((= y 1)
1619 ;; We could probably get away with (VALUES X 0)
1620 ;; here, but it's not clear that some of the
1621 ;; normalization logic further down would avoid
1622 ;; mutilating X. Just go ahead and cons, consing's
1623 ;; cheap.
1624 (values (copy-bignum x len-x) 0))
1626 (let ((n-bits (1- (integer-length y))))
1627 (values
1628 (shift-right-unaligned x 0 n-bits len-x
1629 ((= j res-len-1)
1630 (setf (%bignum-ref res j)
1631 (%ashr (%bignum-ref x i) n-bits))
1632 res)
1633 res)
1634 (logand (%bignum-ref x 0) (1- y))))))
1635 (do ((i (1- len-x) (1- i))
1636 (q (%allocate-bignum len-x))
1637 (r 0))
1638 ((minusp i)
1639 (let ((rem (%allocate-bignum 1)))
1640 (setf (%bignum-ref rem 0) r)
1641 (values q rem)))
1642 (declare (type bignum-element-type r))
1643 (multiple-value-bind (q-digit r-digit)
1644 (%bigfloor r (%bignum-ref x i) y)
1645 (declare (type bignum-element-type q-digit r-digit))
1646 (setf (%bignum-ref q i) q-digit)
1647 (setf r r-digit))))))
1648 ;;; This returns a guess for the next division step. Y1 is the
1649 ;;; highest y digit, and y2 is the second to highest y
1650 ;;; digit. The x... variables are the three highest x digits
1651 ;;; for the next division step.
1653 ;;; From Knuth, our guess is either all ones or x-i and x-i-1
1654 ;;; divided by y1, depending on whether x-i and y1 are the
1655 ;;; same. We test this guess by determining whether guess*y2
1656 ;;; is greater than the three high digits of x minus guess*y1
1657 ;;; shifted left one digit:
1658 ;;; ------------------------------
1659 ;;; | x-i | x-i-1 | x-i-2 |
1660 ;;; ------------------------------
1661 ;;; ------------------------------
1662 ;;; - | g*y1 high | g*y1 low | 0 |
1663 ;;; ------------------------------
1664 ;;; ... < guess*y2 ???
1665 ;;; If guess*y2 is greater, then we decrement our guess by one
1666 ;;; and try again. This returns a guess that is either
1667 ;;; correct or one too large.
1668 (bignum-truncate-guess (y1 y2 x-i x-i-1 x-i-2)
1669 (declare (type bignum-element-type y1 y2 x-i x-i-1 x-i-2))
1670 (let ((guess (if (= x-i y1)
1671 all-ones-digit
1672 (%bigfloor x-i x-i-1 y1))))
1673 (declare (type bignum-element-type guess))
1674 (loop
1675 (multiple-value-bind (high-guess*y1 low-guess*y1)
1676 (%multiply guess y1)
1677 (declare (type bignum-element-type low-guess*y1
1678 high-guess*y1))
1679 (multiple-value-bind (high-guess*y2 low-guess*y2)
1680 (%multiply guess y2)
1681 (declare (type bignum-element-type high-guess*y2
1682 low-guess*y2))
1683 (multiple-value-bind (middle-digit borrow)
1684 (%subtract-with-borrow x-i-1 low-guess*y1 1)
1685 (declare (type bignum-element-type middle-digit)
1686 (fixnum borrow))
1687 ;; Supplying borrow of 1 means there was no
1688 ;; borrow, and we know x-i-2 minus 0 requires
1689 ;; no borrow.
1690 (let ((high-digit (%subtract-with-borrow x-i
1691 high-guess*y1
1692 borrow)))
1693 (declare (type bignum-element-type high-digit))
1694 (if (and (= high-digit 0)
1695 (or (> high-guess*y2 middle-digit)
1696 (and (= middle-digit high-guess*y2)
1697 (> low-guess*y2 x-i-2))))
1698 (setf guess (%subtract-with-borrow guess 1 1))
1699 (return guess)))))))))
1700 ;;; Divide TRUNCATE-X by TRUNCATE-Y, returning the quotient
1701 ;;; and destructively modifying TRUNCATE-X so that it holds
1702 ;;; the remainder.
1704 ;;; LEN-X and LEN-Y tell us how much of the buffers we care about.
1706 ;;; TRUNCATE-X definitely has at least three digits, and it has one
1707 ;;; more than TRUNCATE-Y. This keeps i, i-1, i-2, and low-x-digit
1708 ;;; happy. Thanks to SHIFT-AND-STORE-TRUNCATE-BUFFERS.
1709 (return-quotient-leaving-remainder (len-x len-y)
1710 (declare (type bignum-length len-x len-y))
1711 (let* ((len-q (- len-x len-y))
1712 ;; Add one for extra sign digit in case high bit is on.
1713 (q (%allocate-bignum (1+ len-q)))
1714 (k (1- len-q))
1715 (y1 (%bignum-ref truncate-y (1- len-y)))
1716 (y2 (%bignum-ref truncate-y (- len-y 2)))
1717 (i (1- len-x))
1718 (i-1 (1- i))
1719 (i-2 (1- i-1))
1720 (low-x-digit (- i len-y)))
1721 (declare (type bignum-length len-q)
1722 (type bignum-index k i i-1 i-2 low-x-digit)
1723 (type bignum-element-type y1 y2))
1724 (loop
1725 (setf (%bignum-ref q k)
1726 (try-bignum-truncate-guess
1727 ;; This modifies TRUNCATE-X. Must access
1728 ;; elements each pass.
1729 (bignum-truncate-guess y1 y2
1730 (%bignum-ref truncate-x i)
1731 (%bignum-ref truncate-x i-1)
1732 (%bignum-ref truncate-x i-2))
1733 len-y low-x-digit))
1734 (cond ((zerop k) (return))
1735 (t (decf k)
1736 (decf low-x-digit)
1737 (shiftf i i-1 i-2 (1- i-2)))))
1739 ;;; This takes a digit guess, multiplies it by TRUNCATE-Y for a
1740 ;;; result one greater in length than LEN-Y, and subtracts this result
1741 ;;; from TRUNCATE-X. LOW-X-DIGIT is the first digit of X to start
1742 ;;; the subtraction, and we know X is long enough to subtract a LEN-Y
1743 ;;; plus one length bignum from it. Next we check the result of the
1744 ;;; subtraction, and if the high digit in X became negative, then our
1745 ;;; guess was one too big. In this case, return one less than GUESS
1746 ;;; passed in, and add one value of Y back into X to account for
1747 ;;; subtracting one too many. Knuth shows that the guess is wrong on
1748 ;;; the order of 3/b, where b is the base (2 to the digit-size power)
1749 ;;; -- pretty rarely.
1750 (try-bignum-truncate-guess (guess len-y low-x-digit)
1751 (declare (type bignum-index low-x-digit)
1752 (type bignum-length len-y)
1753 (type bignum-element-type guess))
1754 (let ((carry-digit 0)
1755 (borrow 1)
1756 (i low-x-digit))
1757 (declare (type bignum-element-type carry-digit)
1758 (type bignum-index i)
1759 (fixnum borrow))
1760 ;; Multiply guess and divisor, subtracting from dividend
1761 ;; simultaneously.
1762 (dotimes (j len-y)
1763 (multiple-value-bind (high-digit low-digit)
1764 (%multiply-and-add guess
1765 (%bignum-ref truncate-y j)
1766 carry-digit)
1767 (declare (type bignum-element-type high-digit low-digit))
1768 (setf carry-digit high-digit)
1769 (multiple-value-bind (x temp-borrow)
1770 (%subtract-with-borrow (%bignum-ref truncate-x i)
1771 low-digit
1772 borrow)
1773 (declare (type bignum-element-type x)
1774 (fixnum temp-borrow))
1775 (setf (%bignum-ref truncate-x i) x)
1776 (setf borrow temp-borrow)))
1777 (incf i))
1778 (setf (%bignum-ref truncate-x i)
1779 (%subtract-with-borrow (%bignum-ref truncate-x i)
1780 carry-digit borrow))
1781 ;; See whether guess is off by one, adding one
1782 ;; Y back in if necessary.
1783 (cond ((%digit-0-or-plusp (%bignum-ref truncate-x i))
1784 guess)
1786 ;; If subtraction has negative result, add one
1787 ;; divisor value back in. The guess was one too
1788 ;; large in magnitude.
1789 (let ((i low-x-digit)
1790 (carry 0))
1791 (dotimes (j len-y)
1792 (multiple-value-bind (v k)
1793 (%add-with-carry (%bignum-ref truncate-y j)
1794 (%bignum-ref truncate-x i)
1795 carry)
1796 (declare (type bignum-element-type v))
1797 (setf (%bignum-ref truncate-x i) v)
1798 (setf carry k))
1799 (incf i))
1800 (setf (%bignum-ref truncate-x i)
1801 (%add-with-carry (%bignum-ref truncate-x i)
1802 0 carry)))
1803 (%subtract-with-borrow guess 1 1)))))
1804 ;;; This returns the amount to shift y to place a one in the
1805 ;;; second highest bit. Y must be positive. If the last digit
1806 ;;; of y is zero, then y has a one in the previous digit's
1807 ;;; sign bit, so we know it will take one less than digit-size
1808 ;;; to get a one where we want. Otherwise, we count how many
1809 ;;; right shifts it takes to get zero; subtracting this value
1810 ;;; from digit-size tells us how many high zeros there are
1811 ;;; which is one more than the shift amount sought.
1813 ;;; Note: This is exactly the same as one less than the
1814 ;;; integer-length of the last digit subtracted from the
1815 ;;; digit-size.
1817 ;;; We shift y to make it sufficiently large that doing the
1818 ;;; 2*digit-size by digit-size %BIGFLOOR calls ensures the quotient and
1819 ;;; remainder fit in digit-size.
1820 (shift-y-for-truncate (y)
1821 (let* ((len (%bignum-length y))
1822 (last (%bignum-ref y (1- len))))
1823 (declare (type bignum-length len)
1824 (type bignum-element-type last))
1825 (- digit-size (integer-length last) 1)))
1826 ;;; Stores two bignums into the truncation bignum buffers,
1827 ;;; shifting them on the way in. This assumes x and y are
1828 ;;; positive and at least two in length, and it assumes
1829 ;;; truncate-x and truncate-y are one digit longer than x and
1830 ;;; y.
1831 (shift-and-store-truncate-buffers (x len-x y len-y shift)
1832 (declare (type bignum-length len-x len-y)
1833 (type (integer 0 (#.digit-size)) shift))
1834 (cond ((zerop shift)
1835 (bignum-replace truncate-x x :end1 len-x)
1836 (bignum-replace truncate-y y :end1 len-y))
1838 (bignum-ashift-left-unaligned x 0 shift (1+ len-x)
1839 truncate-x)
1840 (bignum-ashift-left-unaligned y 0 shift (1+ len-y)
1841 truncate-y))))) ;; LABELS
1842 ;;; Divide X by Y returning the quotient and remainder. In the
1843 ;;; general case, we shift Y to set up for the algorithm, and we
1844 ;;; use two buffers to save consing intermediate values. X gets
1845 ;;; destructively modified to become the remainder, and we have
1846 ;;; to shift it to account for the initial Y shift. After we
1847 ;;; multiple bind q and r, we first fix up the signs and then
1848 ;;; return the normalized results.
1849 (let* ((x-plusp (bignum-plus-p x))
1850 (y-plusp (bignum-plus-p y))
1851 (x (if x-plusp x (negate-bignum x nil)))
1852 (y (if y-plusp y (negate-bignum y nil)))
1853 (len-x (%bignum-length x))
1854 (len-y (%bignum-length y)))
1855 (multiple-value-bind (q r)
1856 (cond ((< len-y 2)
1857 (bignum-truncate-single-digit x len-x y))
1858 ((plusp (bignum-compare y x))
1859 (let ((res (%allocate-bignum len-x)))
1860 (dotimes (i len-x)
1861 (setf (%bignum-ref res i) (%bignum-ref x i)))
1862 (values 0 res)))
1864 (let ((len-x+1 (1+ len-x)))
1865 (setf truncate-x (%allocate-bignum len-x+1))
1866 (setf truncate-y (%allocate-bignum (1+ len-y)))
1867 (let ((y-shift (shift-y-for-truncate y)))
1868 (shift-and-store-truncate-buffers x len-x y
1869 len-y y-shift)
1870 (values (return-quotient-leaving-remainder len-x+1
1871 len-y)
1872 ;; Now that RETURN-QUOTIENT-LEAVING-REMAINDER
1873 ;; has executed, we just tidy up the remainder
1874 ;; (in TRUNCATE-X) and return it.
1875 (cond
1876 ((zerop y-shift)
1877 (let ((res (%allocate-bignum len-y)))
1878 (declare (type bignum res))
1879 (bignum-replace res truncate-x :end2 len-y)
1880 (%normalize-bignum res len-y)))
1882 (shift-right-unaligned
1883 truncate-x 0 y-shift len-y
1884 ((= j res-len-1)
1885 (setf (%bignum-ref res j)
1886 (%ashr (%bignum-ref truncate-x i)
1887 y-shift))
1888 (%normalize-bignum res res-len))
1889 res))))))))
1890 (let ((quotient (cond ((eq x-plusp y-plusp) q)
1891 ((typep q 'fixnum) (the fixnum (- q)))
1892 (t (negate-bignum-in-place q))))
1893 (rem (cond (x-plusp r)
1894 ((typep r 'fixnum) (the fixnum (- r)))
1895 (t (negate-bignum-in-place r)))))
1896 (values (if (typep quotient 'fixnum)
1897 quotient
1898 (%normalize-bignum quotient (%bignum-length quotient)))
1899 (if (typep rem 'fixnum)
1901 (%normalize-bignum rem (%bignum-length rem))))))))))
1904 ;;;; There used to be a pile of code for implementing division for bignum digits
1905 ;;;; for machines that don't have a 2*digit-size by digit-size divide instruction.
1906 ;;;; This happens to be most machines, but all the SBCL ports seem to be content
1907 ;;;; to implement SB-BIGNUM:%BIGFLOOR as a VOP rather than using the code here.
1908 ;;;; So it's been deleted. --njf, 2007-02-04
1910 ;;;; general utilities
1912 ;;; Internal in-place operations use this to fixup remaining digits in the
1913 ;;; incoming data, such as in-place shifting. This is basically the same as
1914 ;;; the first form in %NORMALIZE-BIGNUM, but we return the length of the buffer
1915 ;;; instead of shrinking the bignum.
1916 #!-sb-fluid (declaim (maybe-inline %normalize-bignum-buffer))
1917 (defun %normalize-bignum-buffer (result len)
1918 (declare (type bignum result)
1919 (type bignum-length len))
1920 (unless (= len 1)
1921 (do ((next-digit (%bignum-ref result (- len 2))
1922 (%bignum-ref result (- len 2)))
1923 (sign-digit (%bignum-ref result (1- len)) next-digit))
1924 ((not (zerop (logxor sign-digit (%ashr next-digit (1- digit-size))))))
1925 (decf len)
1926 (setf (%bignum-ref result len) 0)
1927 (when (= len 1)
1928 (return))))
1929 len)
1931 ;;; This drops the last digit if it is unnecessary sign information. It repeats
1932 ;;; this as needed, possibly ending with a fixnum. If the resulting length from
1933 ;;; shrinking is one, see whether our one word is a fixnum. Shift the possible
1934 ;;; fixnum bits completely out of the word, and compare this with shifting the
1935 ;;; sign bit all the way through. If the bits are all 1's or 0's in both words,
1936 ;;; then there are just sign bits between the fixnum bits and the sign bit. If
1937 ;;; we do have a fixnum, shift it over for the two low-tag bits.
1938 (defun %normalize-bignum (result len)
1939 (declare (type bignum result)
1940 (type bignum-length len)
1941 (muffle-conditions compiler-note)
1942 #!-sb-fluid (inline %normalize-bignum-buffer))
1943 (let ((newlen (%normalize-bignum-buffer result len)))
1944 (declare (type bignum-length newlen))
1945 (unless (= newlen len)
1946 (%bignum-set-length result newlen))
1947 (if (= newlen 1)
1948 (let ((digit (%bignum-ref result 0)))
1949 (if (= (%ashr digit sb!vm:n-positive-fixnum-bits)
1950 (%ashr digit (1- digit-size)))
1951 (%fixnum-digit-with-correct-sign digit)
1952 result))
1953 result)))
1955 ;;; This drops the last digit if it is unnecessary sign information. It
1956 ;;; repeats this as needed, possibly ending with a fixnum magnitude but never
1957 ;;; returning a fixnum.
1958 (defun %mostly-normalize-bignum (result len)
1959 (declare (type bignum result)
1960 (type bignum-length len)
1961 #!-sb-fluid (inline %normalize-bignum-buffer))
1962 (let ((newlen (%normalize-bignum-buffer result len)))
1963 (declare (type bignum-length newlen))
1964 (unless (= newlen len)
1965 (%bignum-set-length result newlen))
1966 result))
1968 ;;;; hashing
1970 ;;; the bignum case of the SXHASH function
1971 (defun sxhash-bignum (x)
1972 (let ((result 316495330))
1973 (declare (type fixnum result))
1974 (dotimes (i (%bignum-length x))
1975 (declare (type index i))
1976 (let ((xi (%bignum-ref x i)))
1977 (mixf result
1978 (logand most-positive-fixnum
1979 (logxor xi
1980 (ash xi -7))))))
1981 result))