1 ;;;; code to implement bignum support
3 ;;;; This software is part of the SBCL system. See the README file for
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")
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 bignum-deposit-byte
24 ;;; bignum-truncate bignum-plus-p bignum-compare make-small-bignum
26 ;;; These symbols define the interface to the compiler:
27 ;;; bignum-type 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 %floor %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:
41 ;;; %BIGNUM-SET-LENGTH
42 ;;; %FIXNUM-DIGIT-WITH-CORRECT-SIGN
46 ;;; %BIGNUM-0-OR-PLUSP
47 ;;; %DIGIT-LOGICAL-SHIFT-RIGHT
48 ;;; General (May not exist when done due to sole use in %-routines.)
53 ;;; %SUBTRACT-WITH-BORROW
58 ;;; Shifting (in place)
59 ;;; %NORMALIZE-BIGNUM-BUFFER
60 ;;; GCD/Relational operators:
63 ;;; Relational operators:
72 ;;; Note: The floating routines know about the float representation.
75 ;;; There might be a problem with various LET's and parameters that take a
76 ;;; digit value. We need to write these so those things stay in 32-bit
77 ;;; registers and number stack slots. I bind locals to these values, and I
78 ;;; use function on them -- ZEROP, ASH, etc.
81 ;;; In shifting and byte operations, I use masks and logical operations that
82 ;;; could result in intermediate bignums. This is hidden by the current system,
83 ;;; but I may need to write these in a way that keeps these masks and logical
84 ;;; operations from diving into the Lisp level bignum code.
88 ;;; logior, logxor, logand
89 ;;; depending on relationals, < (twice) and <= (twice)
90 ;;; or write compare thing (twice).
91 ;;; LDB on fixnum with bignum result.
92 ;;; DPB on fixnum with bignum result.
93 ;;; TRUNCATE returns zero or one as one value and fixnum or minus fixnum
94 ;;; for the other value when given (truncate fixnum bignum).
95 ;;; Returns (truncate bignum fixnum) otherwise.
97 ;;; subtraction (twice)
100 ;;; Write MASK-FIELD and DEPOSIT-FIELD in terms of logical operations.
102 ;;; IF (/ x y) with bignums:
103 ;;; do the truncate, and if rem is 0, return quotient.
106 ;;; "truncate" each by gcd, ignoring remainder 0.
107 ;;; form ratio of each result, bottom is positive.
109 ;;;; What's a bignum?
111 (defconstant digit-size 32)
113 (defconstant maximum-bignum-length (1- (ash 1 (- 32 sb!vm:n-widetag-bits))))
115 ;;;; internal inline routines
117 ;;; %ALLOCATE-BIGNUM must zero all elements.
118 (defun %allocate-bignum (length)
119 (declare (type bignum-index length))
120 (%allocate-bignum length))
122 ;;; Extract the length of the bignum.
123 (defun %bignum-length (bignum)
124 (declare (type bignum-type bignum))
125 (%bignum-length bignum))
127 ;;; %BIGNUM-REF needs to access bignums as obviously as possible, and it needs
128 ;;; to be able to return 32 bits somewhere no one looks for real objects.
129 (defun %bignum-ref (bignum i)
130 (declare (type bignum-type bignum)
131 (type bignum-index i))
132 (%bignum-ref bignum i))
133 (defun %bignum-set (bignum i value)
134 (declare (type bignum-type bignum)
135 (type bignum-index i)
136 (type bignum-element-type value))
137 (%bignum-set bignum i value))
139 ;;; Return T if digit is positive, or NIL if negative.
140 (defun %digit-0-or-plusp (digit)
141 (declare (type bignum-element-type digit))
142 (not (logbitp (1- digit-size) digit)))
144 #!-sb-fluid (declaim (inline %bignum-0-or-plusp))
145 (defun %bignum-0-or-plusp (bignum len)
146 (declare (type bignum-type bignum)
147 (type bignum-index len))
148 (%digit-0-or-plusp (%bignum-ref bignum (1- len))))
150 ;;; This should be in assembler, and should not cons intermediate results. It
151 ;;; returns a 32bit digit and a carry resulting from adding together a, b, and
152 ;;; an incoming carry.
153 (defun %add-with-carry (a b carry)
154 (declare (type bignum-element-type a b)
155 (type (mod 2) carry))
156 (%add-with-carry a b carry))
158 ;;; This should be in assembler, and should not cons intermediate results. It
159 ;;; returns a 32bit digit and a borrow resulting from subtracting b from a, and
160 ;;; subtracting a possible incoming borrow.
162 ;;; We really do: a - b - 1 + borrow, where borrow is either 0 or 1.
163 (defun %subtract-with-borrow (a b borrow)
164 (declare (type bignum-element-type a b)
165 (type (mod 2) borrow))
166 (%subtract-with-borrow a b borrow))
168 ;;; Multiply two digit-size (32-bit) numbers, returning a 64-bit result
169 ;;; split into two 32-bit quantities.
170 (defun %multiply (x y)
171 (declare (type bignum-element-type x y))
174 ;;; This multiplies x-digit and y-digit, producing high and low digits
175 ;;; manifesting the result. Then it adds the low digit, res-digit, and
176 ;;; carry-in-digit. Any carries (note, you still have to add two digits at a
177 ;;; time possibly producing two carries) from adding these three digits get
178 ;;; added to the high digit from the multiply, producing the next carry digit.
179 ;;; Res-digit is optional since two uses of this primitive multiplies a single
180 ;;; digit bignum by a multiple digit bignum, and in this situation there is no
181 ;;; need for a result buffer accumulating partial results which is where the
182 ;;; res-digit comes from.
183 (defun %multiply-and-add (x-digit y-digit carry-in-digit
184 &optional (res-digit 0))
185 (declare (type bignum-element-type x-digit y-digit res-digit carry-in-digit))
186 (%multiply-and-add x-digit y-digit carry-in-digit res-digit))
188 (defun %lognot (digit)
189 (declare (type bignum-element-type digit))
192 ;;; Each of these does the 32-bit unsigned op.
193 #!-sb-fluid (declaim (inline %logand %logior %logxor))
195 (declare (type bignum-element-type a b))
198 (declare (type bignum-element-type a b))
201 (declare (type bignum-element-type a b))
204 ;;; This takes a fixnum and sets it up as an unsigned 32-bit quantity. In
205 ;;; the new system this will mean shifting it right two bits.
206 (defun %fixnum-to-digit (x)
208 (logand x (1- (ash 1 digit-size))))
211 ;;; This takes three digits and returns the FLOOR'ed result of
212 ;;; dividing the first two as a 64-bit integer by the third.
214 ;;; Do weird LET and SETQ stuff to bamboozle the compiler into allowing
215 ;;; the %FLOOR transform to expand into pseudo-assembler for which the
216 ;;; compiler can later correctly allocate registers.
217 (defun %floor (a b c)
218 (let ((a a) (b b) (c c))
219 (declare (type bignum-element-type a b c))
223 ;;; Convert the digit to a regular integer assuming that the digit is signed.
224 (defun %fixnum-digit-with-correct-sign (digit)
225 (declare (type bignum-element-type digit))
226 (if (logbitp (1- digit-size) digit)
227 (logior digit (ash -1 digit-size))
230 ;;; Do an arithmetic shift right of data even though bignum-element-type is
232 (defun %ashr (data count)
233 (declare (type bignum-element-type data)
234 (type (mod 32) count))
237 ;;; This takes a 32-bit quantity and shifts it to the left, returning a 32-bit
239 (defun %ashl (data count)
240 (declare (type bignum-element-type data)
241 (type (mod 32) count))
244 ;;; Do an unsigned (logical) right shift of a digit by Count.
245 (defun %digit-logical-shift-right (data count)
246 (declare (type bignum-element-type data)
247 (type (mod 32) count))
248 (%digit-logical-shift-right data count))
250 ;;; Change the length of bignum to be newlen. Newlen must be the same or
251 ;;; smaller than the old length, and any elements beyond newlen must be zeroed.
252 (defun %bignum-set-length (bignum newlen)
253 (declare (type bignum-type bignum)
254 (type bignum-index newlen))
255 (%bignum-set-length bignum newlen))
257 ;;; This returns 0 or "-1" depending on whether the bignum is positive. This
258 ;;; is suitable for infinite sign extension to complete additions,
259 ;;; subtractions, negations, etc. This cannot return a -1 represented as
260 ;;; a negative fixnum since it would then have to low zeros.
261 #!-sb-fluid (declaim (inline %sign-digit))
262 (defun %sign-digit (bignum len)
263 (declare (type bignum-type bignum)
264 (type bignum-index len))
265 (%ashr (%bignum-ref bignum (1- len)) (1- digit-size)))
267 ;;; These take two 32 bit quantities and compare or contrast them without
268 ;;; wasting time with incorrect type checking.
269 #!-sb-fluid (declaim (inline %digit-compare %digit-greater))
270 (defun %digit-compare (x y)
272 (defun %digit-greater (x y)
275 (declaim (optimize (speed 3) (safety 0)))
279 (defun add-bignums (a b)
280 (declare (type bignum-type a b))
281 (let ((len-a (%bignum-length a))
282 (len-b (%bignum-length b)))
283 (declare (type bignum-index len-a len-b))
284 (multiple-value-bind (a len-a b len-b)
286 (values a len-a b len-b)
287 (values b len-b a len-a))
288 (declare (type bignum-type a b)
289 (type bignum-index len-a len-b))
290 (let* ((len-res (1+ len-a))
291 (res (%allocate-bignum len-res))
293 (declare (type bignum-index len-res)
294 (type bignum-type res)
295 (type (mod 2) carry))
297 (declare (type bignum-index i))
298 (multiple-value-bind (v k)
299 (%add-with-carry (%bignum-ref a i) (%bignum-ref b i) carry)
300 (declare (type bignum-element-type v)
302 (setf (%bignum-ref res i) v)
305 (finish-add a res carry (%sign-digit b len-b) len-b len-a)
306 (setf (%bignum-ref res len-a)
307 (%add-with-carry (%sign-digit a len-a)
308 (%sign-digit b len-b)
310 (%normalize-bignum res len-res)))))
312 ;;; This takes the longer of two bignums and propagates the carry through its
313 ;;; remaining high order digits.
314 (defun finish-add (a res carry sign-digit-b start end)
315 (declare (type bignum-type a res)
317 (type bignum-element-type sign-digit-b)
318 (type bignum-index start end))
319 (do ((i start (1+ i)))
321 (setf (%bignum-ref res end)
322 (%add-with-carry (%sign-digit a end) sign-digit-b carry)))
323 (declare (type bignum-index i))
324 (multiple-value-bind (v k)
325 (%add-with-carry (%bignum-ref a i) sign-digit-b carry)
326 (setf (%bignum-ref res i) v)
332 (eval-when (:compile-toplevel :execute)
334 ;;; This subtracts b from a plugging result into res. Return-fun is the
335 ;;; function to call that fixes up the result returning any useful values, such
336 ;;; as the result. This macro may evaluate its arguments more than once.
337 (sb!xc:defmacro subtract-bignum-loop (a len-a b len-b res len-res return-fun)
338 (let ((borrow (gensym))
347 (,a-sign (%sign-digit ,a ,len-a))
348 (,b-sign (%sign-digit ,b ,len-b)))
349 (declare (type bignum-element-type ,a-sign ,b-sign))
350 (dotimes (,i ,len-res)
351 (declare (type bignum-index ,i))
352 (let ((,a-digit (if (< ,i ,len-a) (%bignum-ref ,a ,i) ,a-sign))
353 (,b-digit (if (< ,i ,len-b) (%bignum-ref ,b ,i) ,b-sign)))
354 (declare (type bignum-element-type ,a-digit ,b-digit))
355 (multiple-value-bind (,v ,k)
356 (%subtract-with-borrow ,a-digit ,b-digit ,borrow)
357 (setf (%bignum-ref ,res ,i) ,v)
359 (,return-fun ,res ,len-res))))
363 (defun subtract-bignum (a b)
364 (declare (type bignum-type a b))
365 (let* ((len-a (%bignum-length a))
366 (len-b (%bignum-length b))
367 (len-res (1+ (max len-a len-b)))
368 (res (%allocate-bignum len-res)))
369 (declare (type bignum-index len-a len-b len-res)) ;Test len-res for bounds?
370 (subtract-bignum-loop a len-a b len-b res len-res %normalize-bignum)))
372 ;;; Operations requiring a subtraction without the overhead of intermediate
373 ;;; results, such as GCD, use this. It assumes Result is big enough for the
375 (defun subtract-bignum-buffers (a len-a b len-b result)
376 (declare (type bignum-type a b)
377 (type bignum-index len-a len-b))
378 (let ((len-res (max len-a len-b)))
379 (subtract-bignum-loop a len-a b len-b result len-res
380 %normalize-bignum-buffer)))
384 (defun multiply-bignums (a b)
385 (declare (type bignum-type a b))
386 (let* ((a-plusp (%bignum-0-or-plusp a (%bignum-length a)))
387 (b-plusp (%bignum-0-or-plusp b (%bignum-length b)))
388 (a (if a-plusp a (negate-bignum a)))
389 (b (if b-plusp b (negate-bignum b)))
390 (len-a (%bignum-length a))
391 (len-b (%bignum-length b))
392 (len-res (+ len-a len-b))
393 (res (%allocate-bignum len-res))
394 (negate-res (not (eq a-plusp b-plusp))))
395 (declare (type bignum-index len-a len-b len-res))
397 (declare (type bignum-index i))
398 (let ((carry-digit 0)
399 (x (%bignum-ref a i))
401 (declare (type bignum-index k)
402 (type bignum-element-type carry-digit x))
404 (multiple-value-bind (big-carry res-digit)
409 (declare (type bignum-element-type big-carry res-digit))
410 (setf (%bignum-ref res k) res-digit)
411 (setf carry-digit big-carry)
413 (setf (%bignum-ref res k) carry-digit)))
414 (when negate-res (negate-bignum-in-place res))
415 (%normalize-bignum res len-res)))
417 (defun multiply-bignum-and-fixnum (bignum fixnum)
418 (declare (type bignum-type bignum) (type fixnum fixnum))
419 (let* ((bignum-plus-p (%bignum-0-or-plusp bignum (%bignum-length bignum)))
420 (fixnum-plus-p (not (minusp fixnum)))
421 (bignum (if bignum-plus-p bignum (negate-bignum bignum)))
422 (bignum-len (%bignum-length bignum))
423 (fixnum (if fixnum-plus-p fixnum (- fixnum)))
424 (result (%allocate-bignum (1+ bignum-len)))
426 (declare (type bignum-type bignum result)
427 (type bignum-index bignum-len)
428 (type bignum-element-type fixnum carry-digit))
429 (dotimes (index bignum-len)
430 (declare (type bignum-index index))
431 (multiple-value-bind (next-digit low)
432 (%multiply-and-add (%bignum-ref bignum index) fixnum carry-digit)
433 (declare (type bignum-element-type next-digit low))
434 (setf carry-digit next-digit)
435 (setf (%bignum-ref result index) low)))
436 (setf (%bignum-ref result bignum-len) carry-digit)
437 (unless (eq bignum-plus-p fixnum-plus-p)
438 (negate-bignum-in-place result))
439 (%normalize-bignum result (1+ bignum-len))))
441 (defun multiply-fixnums (a b)
442 (declare (fixnum a b))
443 (let* ((a-minusp (minusp a))
444 (b-minusp (minusp b)))
445 (multiple-value-bind (high low)
446 (%multiply (if a-minusp (- a) a)
447 (if b-minusp (- b) b))
448 (declare (type bignum-element-type high low))
449 (if (and (zerop high)
450 (%digit-0-or-plusp low))
451 (let ((low (sb!ext:truly-the (unsigned-byte 31)
452 (%fixnum-digit-with-correct-sign low))))
453 (if (eq a-minusp b-minusp)
456 (let ((res (%allocate-bignum 2)))
457 (%bignum-set res 0 low)
458 (%bignum-set res 1 high)
459 (unless (eq a-minusp b-minusp) (negate-bignum-in-place res))
460 (%normalize-bignum res 2))))))
462 ;;;; BIGNUM-REPLACE and WITH-BIGNUM-BUFFERS
464 (eval-when (:compile-toplevel :execute)
466 (sb!xc:defmacro bignum-replace (dest
474 (sb!int:once-only ((n-dest dest)
476 (let ((n-start1 (gensym))
482 (end1 (or end1 `(%bignum-length ,n-dest)))
483 (end2 (or end2 `(%bignum-length ,n-src))))
485 `(let ((,n-start1 ,start1)
487 (do ((,i1 (1- ,end1) (1- ,i1))
488 (,i2 (1- ,end2) (1- ,i2)))
489 ((or (< ,i1 ,n-start1) (< ,i2 ,n-start2)))
490 (declare (fixnum ,i1 ,i2))
491 (%bignum-set ,n-dest ,i1
492 (%bignum-ref ,n-src ,i2))))
493 `(let ((,n-end1 ,end1)
495 (do ((,i1 ,start1 (1+ ,i1))
496 (,i2 ,start2 (1+ ,i2)))
497 ((or (>= ,i1 ,n-end1) (>= ,i2 ,n-end2)))
498 (declare (type bignum-index ,i1 ,i2))
499 (%bignum-set ,n-dest ,i1
500 (%bignum-ref ,n-src ,i2))))))))
502 (sb!xc:defmacro with-bignum-buffers (specs &body body)
504 "WITH-BIGNUM-BUFFERS ({(var size [init])}*) Form*"
505 (sb!int:collect ((binds)
508 (let ((name (first spec))
509 (size (second spec)))
510 (binds `(,name (%allocate-bignum ,size)))
511 (let ((init (third spec)))
513 (inits `(bignum-replace ,name ,init))))))
522 (defun bignum-gcd (a b)
523 (declare (type bignum-type a b))
524 (let* ((a (if (%bignum-0-or-plusp a (%bignum-length a))
526 (negate-bignum a nil)))
527 (b (if (%bignum-0-or-plusp b (%bignum-length b))
529 (negate-bignum b nil)))
530 (len-a (%bignum-length a))
531 (len-b (%bignum-length b)))
532 (declare (type bignum-index len-a len-b))
533 (with-bignum-buffers ((a-buffer len-a a)
535 (res-buffer (max len-a len-b)))
536 (let* ((factors-of-two
537 (bignum-factors-of-two a-buffer len-a
539 (len-a (make-gcd-bignum-odd
541 (bignum-buffer-ashift-right a-buffer len-a
543 (len-b (make-gcd-bignum-odd
545 (bignum-buffer-ashift-right b-buffer len-b
547 (declare (type bignum-index len-a len-b))
554 (multiple-value-bind (u v len-v r len-r)
555 (bignum-gcd-order-and-subtract x len-x y len-y z)
556 (declare (type bignum-index len-v len-r))
557 (when (and (= len-r 1) (zerop (%bignum-ref r 0)))
558 (if (zerop factors-of-two)
559 (let ((ret (%allocate-bignum len-v)))
561 (setf (%bignum-ref ret i) (%bignum-ref v i)))
562 (return (%normalize-bignum ret len-v)))
563 (return (bignum-ashift-left v factors-of-two len-v))))
564 (setf x v len-x len-v)
565 (setf y r len-y (make-gcd-bignum-odd r len-r))
568 (defun bignum-gcd-order-and-subtract (a len-a b len-b res)
569 (declare (type bignum-index len-a len-b) (type bignum-type a b))
570 (cond ((= len-a len-b)
571 (do ((i (1- len-a) (1- i)))
573 (setf (%bignum-ref res 0) 0)
574 (values a b len-b res 1))
575 (let ((a-digit (%bignum-ref a i))
576 (b-digit (%bignum-ref b i)))
577 (cond ((%digit-compare a-digit b-digit))
578 ((%digit-greater a-digit b-digit)
580 (values a b len-b res
581 (subtract-bignum-buffers a len-a b len-b res))))
584 (values b a len-a res
585 (subtract-bignum-buffers b len-b
589 (values a b len-b res
590 (subtract-bignum-buffers a len-a b len-b res)))
592 (values b a len-a res
593 (subtract-bignum-buffers b len-b a len-a res)))))
595 (defun make-gcd-bignum-odd (a len-a)
596 (declare (type bignum-type a) (type bignum-index len-a))
597 (dotimes (index len-a)
598 (declare (type bignum-index index))
599 (do ((digit (%bignum-ref a index) (%ashr digit 1))
600 (increment 0 (1+ increment)))
602 (declare (type (mod 32) increment))
604 (return-from make-gcd-bignum-odd
605 (bignum-buffer-ashift-right a len-a
606 (+ (* index digit-size)
609 (defun bignum-factors-of-two (a len-a b len-b)
610 (declare (type bignum-index len-a len-b) (type bignum-type a))
612 (end (min len-a len-b)))
613 ((= i end) (error "Unexpected zero bignums?"))
614 (declare (type bignum-index i end))
615 (let ((or-digits (%logior (%bignum-ref a i) (%bignum-ref b i))))
616 (unless (zerop or-digits)
617 (return (do ((j 0 (1+ j))
618 (or-digits or-digits (%ashr or-digits 1)))
619 ((oddp or-digits) (+ (* i digit-size) j))
620 (declare (type (mod 32) j))))))))
624 (eval-when (:compile-toplevel :execute)
626 ;;; This negates bignum-len digits of bignum, storing the resulting digits into
627 ;;; result (possibly EQ to bignum) and returning whatever end-carry there is.
628 (sb!xc:defmacro bignum-negate-loop (bignum
630 &optional (result nil resultp))
631 (let ((carry (gensym))
635 `(let* (,@(if (not resultp) `(,last))
637 (multiple-value-bind (,value ,carry)
638 (%add-with-carry (%lognot (%bignum-ref ,bignum 0)) 1 0)
640 `(setf (%bignum-ref ,result 0) ,value)
641 `(setf ,last ,value))
645 (declare (type bit ,carry)
646 (type bignum-index i ,end))
648 (when (= i ,end) (return))
649 (multiple-value-bind (,value temp)
650 (%add-with-carry (%lognot (%bignum-ref ,bignum i)) 0 ,carry)
652 `(setf (%bignum-ref ,result i) ,value)
653 `(setf ,last ,value))
656 ,(if resultp carry `(values ,carry ,last)))))
660 ;;; Fully-normalize is an internal optional. It cause this to always return
661 ;;; a bignum, without any extraneous digits, and it never returns a fixnum.
662 (defun negate-bignum (x &optional (fully-normalize t))
663 (declare (type bignum-type x))
664 (let* ((len-x (%bignum-length x))
666 (res (%allocate-bignum len-res)))
667 (declare (type bignum-index len-x len-res)) ;Test len-res for range?
668 (let ((carry (bignum-negate-loop x len-x res)))
669 (setf (%bignum-ref res len-x)
670 (%add-with-carry (%lognot (%sign-digit x len-x)) 0 carry)))
672 (%normalize-bignum res len-res)
673 (%mostly-normalize-bignum res len-res))))
675 ;;; This assumes bignum is positive; that is, the result of negating it will
676 ;;; stay in the provided allocated bignum.
677 (defun negate-bignum-in-place (bignum)
678 (bignum-negate-loop bignum (%bignum-length bignum) bignum)
683 (defconstant all-ones-digit #xFFFFFFFF)
685 (eval-when (:compile-toplevel :execute)
687 ;;; This macro is used by BIGNUM-ASHIFT-RIGHT, BIGNUM-BUFFER-ASHIFT-RIGHT, and
688 ;;; BIGNUM-LDB-BIGNUM-RES. They supply a termination form that references
689 ;;; locals established by this form. Source is the source bignum. Start-digit
690 ;;; is the first digit in source from which we pull bits. Start-pos is the
691 ;;; first bit we want. Res-len-form is the form that computes the length of
692 ;;; the resulting bignum. Termination is a DO termination form with a test and
693 ;;; body. When result is supplied, it is the variable to which this binds a
694 ;;; newly allocated bignum.
696 ;;; Given start-pos, 1-31 inclusively, of shift, we form the j'th resulting
697 ;;; digit from high bits of the i'th source digit and the start-pos number of
698 ;;; bits from the i+1'th source digit.
699 (sb!xc:defmacro shift-right-unaligned (source
705 `(let* ((high-bits-in-first-digit (- digit-size ,start-pos))
706 (res-len ,res-len-form)
707 (res-len-1 (1- res-len))
708 ,@(if result `((,result (%allocate-bignum res-len)))))
709 (declare (type bignum-index res-len res-len-1))
710 (do ((i ,start-digit i+1)
711 (i+1 (1+ ,start-digit) (1+ i+1))
714 (declare (type bignum-index i i+1 j))
715 (setf (%bignum-ref ,(if result result source) j)
716 (%logior (%digit-logical-shift-right (%bignum-ref ,source i)
718 (%ashl (%bignum-ref ,source i+1)
719 high-bits-in-first-digit))))))
723 ;;; First compute the number of whole digits to shift, shifting them by
724 ;;; skipping them when we start to pick up bits, and the number of bits to
725 ;;; shift the remaining digits into place. If the number of digits is greater
726 ;;; than the length of the bignum, then the result is either 0 or -1. If we
727 ;;; shift on a digit boundary (that is, n-bits is zero), then we just copy
728 ;;; digits. The last branch handles the general case which uses a macro that a
729 ;;; couple other routines use. The fifth argument to the macro references
730 ;;; locals established by the macro.
731 (defun bignum-ashift-right (bignum count)
732 (declare (type bignum-type bignum)
733 (type unsigned-byte count))
734 (let ((bignum-len (%bignum-length bignum)))
735 (declare (type bignum-index bignum-len))
736 (cond ((fixnump count)
737 (multiple-value-bind (digits n-bits) (truncate count digit-size)
738 (declare (type bignum-index digits))
740 ((>= digits bignum-len)
741 (if (%bignum-0-or-plusp bignum bignum-len) 0 -1))
743 (bignum-ashift-right-digits bignum digits))
745 (shift-right-unaligned bignum digits n-bits (- bignum-len digits)
747 (setf (%bignum-ref res j)
748 (%ashr (%bignum-ref bignum i) n-bits))
749 (%normalize-bignum res res-len))
751 ((> count bignum-len)
753 ;; Since a FIXNUM should be big enough to address anything in
754 ;; memory, including arrays of bits, and since arrays of bits
755 ;; take up about the same space as corresponding fixnums, there
756 ;; should be no way that we fall through to this case: any shift
757 ;; right by a bignum should give zero. But let's check anyway:
758 (t (error "bignum overflow: can't shift right by ~S")))))
760 (defun bignum-ashift-right-digits (bignum digits)
761 (declare (type bignum-type bignum)
762 (type bignum-index digits))
763 (let* ((res-len (- (%bignum-length bignum) digits))
764 (res (%allocate-bignum res-len)))
765 (declare (type bignum-index res-len)
766 (type bignum-type res))
767 (bignum-replace res bignum :start2 digits)
768 (%normalize-bignum res res-len)))
770 ;;; GCD uses this for an in-place shifting operation. This is different enough
771 ;;; from BIGNUM-ASHIFT-RIGHT that it isn't worth folding the bodies into a
772 ;;; macro, but they share the basic algorithm. This routine foregoes a first
773 ;;; test for digits being greater than or equal to bignum-len since that will
774 ;;; never happen for its uses in GCD. We did fold the last branch into a macro
775 ;;; since it was duplicated a few times, and the fifth argument to it
776 ;;; references locals established by the macro.
777 (defun bignum-buffer-ashift-right (bignum bignum-len x)
778 (declare (type bignum-index bignum-len) (fixnum x))
779 (multiple-value-bind (digits n-bits) (truncate x digit-size)
780 (declare (type bignum-index digits))
783 (let ((new-end (- bignum-len digits)))
784 (bignum-replace bignum bignum :end1 new-end :start2 digits
786 (%normalize-bignum-buffer bignum new-end)))
788 (shift-right-unaligned bignum digits n-bits (- bignum-len digits)
790 (setf (%bignum-ref bignum j)
791 (%ashr (%bignum-ref bignum i) n-bits))
792 (%normalize-bignum-buffer bignum res-len)))))))
794 ;;; This handles shifting a bignum buffer to provide fresh bignum data for some
795 ;;; internal routines. We know bignum is safe when called with bignum-len.
796 ;;; First we compute the number of whole digits to shift, shifting them
797 ;;; starting to store farther along the result bignum. If we shift on a digit
798 ;;; boundary (that is, n-bits is zero), then we just copy digits. The last
799 ;;; branch handles the general case.
800 (defun bignum-ashift-left (bignum x &optional bignum-len)
801 (declare (type bignum-type bignum)
802 (type unsigned-byte x)
803 (type (or null bignum-index) bignum-len))
805 (multiple-value-bind (digits n-bits) (truncate x digit-size)
806 (let* ((bignum-len (or bignum-len (%bignum-length bignum)))
807 (res-len (+ digits bignum-len 1)))
808 (when (> res-len maximum-bignum-length)
809 (error "can't represent result of left shift"))
811 (bignum-ashift-left-digits bignum bignum-len digits)
812 (bignum-ashift-left-unaligned bignum digits n-bits res-len))))
813 ;; Left shift by a number too big to be represented as a fixnum
814 ;; would exceed our memory capacity, since a fixnum is big enough
815 ;; to index any array, including a bit array.
816 (error "can't represent result of left shift")))
818 (defun bignum-ashift-left-digits (bignum bignum-len digits)
819 (declare (type bignum-index bignum-len digits))
820 (let* ((res-len (+ bignum-len digits))
821 (res (%allocate-bignum res-len)))
822 (declare (type bignum-index res-len))
823 (bignum-replace res bignum :start1 digits :end1 res-len :end2 bignum-len
827 ;;; BIGNUM-TRUNCATE uses this to store into a bignum buffer by supplying res.
828 ;;; When res comes in non-nil, then this foregoes allocating a result, and it
829 ;;; normalizes the buffer instead of the would-be allocated result.
831 ;;; We start storing into one digit higher than digits, storing a whole result
832 ;;; digit from parts of two contiguous digits from bignum. When the loop
833 ;;; finishes, we store the remaining bits from bignum's first digit in the
834 ;;; first non-zero result digit, digits. We also grab some left over high
835 ;;; bits from the last digit of bignum.
836 (defun bignum-ashift-left-unaligned (bignum digits n-bits res-len
837 &optional (res nil resp))
838 (declare (type bignum-index digits res-len)
839 (type (mod #.digit-size) n-bits))
840 (let* ((remaining-bits (- digit-size n-bits))
841 (res-len-1 (1- res-len))
842 (res (or res (%allocate-bignum res-len))))
843 (declare (type bignum-index res-len res-len-1))
846 (j (1+ digits) (1+ j)))
848 (setf (%bignum-ref res digits)
849 (%ashl (%bignum-ref bignum 0) n-bits))
850 (setf (%bignum-ref res j)
851 (%ashr (%bignum-ref bignum i) remaining-bits))
853 (%normalize-bignum-buffer res res-len)
854 (%normalize-bignum res res-len)))
855 (declare (type bignum-index i i+1 j))
856 (setf (%bignum-ref res j)
857 (%logior (%digit-logical-shift-right (%bignum-ref bignum i)
859 (%ashl (%bignum-ref bignum i+1) n-bits))))))
861 ;;;; relational operators
863 ;;; Return T iff bignum is positive.
864 (defun bignum-plus-p (bignum)
865 (declare (type bignum-type bignum))
866 (%bignum-0-or-plusp bignum (%bignum-length bignum)))
868 ;;; This compares two bignums returning -1, 0, or 1, depending on
869 ;;; whether a is less than, equal to, or greater than b.
870 (declaim (ftype (function (bignum bignum) (integer -1 1)) bignum-compare))
871 (defun bignum-compare (a b)
872 (declare (type bignum-type a b))
873 (let* ((len-a (%bignum-length a))
874 (len-b (%bignum-length b))
875 (a-plusp (%bignum-0-or-plusp a len-a))
876 (b-plusp (%bignum-0-or-plusp b len-b)))
877 (declare (type bignum-index len-a len-b))
878 (cond ((not (eq a-plusp b-plusp))
881 (do ((i (1- len-a) (1- i)))
883 (declare (type bignum-index i))
884 (let ((a-digit (%bignum-ref a i))
885 (b-digit (%bignum-ref b i)))
886 (declare (type bignum-element-type a-digit b-digit))
887 (when (%digit-greater a-digit b-digit)
889 (when (%digit-greater b-digit a-digit)
891 (when (zerop i) (return 0))))
894 (t (if a-plusp -1 1)))))
896 ;;;; float conversion
898 ;;; Make a single or double float with the specified significand,
899 ;;; exponent and sign.
900 (defun single-float-from-bits (bits exp plusp)
901 (declare (fixnum exp))
902 (declare (optimize #-sb-xc-host (sb!ext:inhibit-warnings 3)))
904 sb!vm:single-float-exponent-byte
905 (logandc2 (sb!ext:truly-the (unsigned-byte 31)
906 (%bignum-ref bits 1))
907 sb!vm:single-float-hidden-bit))))
911 (logior res (ash -1 sb!vm:float-sign-shift))))))
912 (defun double-float-from-bits (bits exp plusp)
913 (declare (fixnum exp))
914 (declare (optimize #-sb-xc-host (sb!ext:inhibit-warnings 3)))
916 sb!vm:double-float-exponent-byte
917 (logandc2 (sb!ext:truly-the (unsigned-byte 31)
918 (%bignum-ref bits 2))
919 sb!vm:double-float-hidden-bit))))
923 (logior hi (ash -1 sb!vm:float-sign-shift)))
924 (%bignum-ref bits 1))))
925 #!+(and long-float x86)
926 (defun long-float-from-bits (bits exp plusp)
927 (declare (fixnum exp))
928 (declare (optimize #-sb-xc-host (sb!ext:inhibit-warnings 3)))
932 (logior exp (ash 1 15)))
934 (%bignum-ref bits 1)))
936 ;;; Convert Bignum to a float in the specified Format, rounding to the best
938 (defun bignum-to-float (bignum format)
939 (let* ((plusp (bignum-plus-p bignum))
940 (x (if plusp bignum (negate-bignum bignum)))
941 (len (bignum-integer-length x))
942 (digits (float-format-digits format))
943 (keep (+ digits digit-size))
945 (shifted (if (minusp shift)
946 (bignum-ashift-right x (- shift))
947 (bignum-ashift-left x shift)))
948 (low (%bignum-ref shifted 0))
949 (round-bit (ash 1 (1- digit-size))))
950 (declare (type bignum-index len digits keep) (fixnum shift))
951 (labels ((round-up ()
952 (let ((rounded (add-bignums shifted round-bit)))
953 (if (> (integer-length rounded) keep)
954 (float-from-bits (bignum-ashift-right rounded 1)
956 (float-from-bits rounded len))))
957 (float-from-bits (bits len)
958 (declare (type bignum-index len))
961 (single-float-from-bits
963 (check-exponent len sb!vm:single-float-bias
964 sb!vm:single-float-normal-exponent-max)
967 (double-float-from-bits
969 (check-exponent len sb!vm:double-float-bias
970 sb!vm:double-float-normal-exponent-max)
974 (long-float-from-bits
976 (check-exponent len sb!vm:long-float-bias
977 sb!vm:long-float-normal-exponent-max)
979 (check-exponent (exp bias max)
980 (declare (type bignum-index len))
981 (let ((exp (+ exp bias)))
983 ;; Why a SIMPLE-TYPE-ERROR? Well, this is mainly
984 ;; called by COERCE, which requires an error of
985 ;; TYPE-ERROR if the conversion can't happen
986 ;; (except in certain circumstances when we are
987 ;; coercing to a FUNCTION) -- CSR, 2002-09-18
988 (error 'simple-type-error
989 :format-control "Too large to be represented as a ~S:~% ~S"
990 :format-arguments (list format x)
991 :expected-type format
996 ;; Round down if round bit is 0.
997 ((zerop (logand round-bit low))
998 (float-from-bits shifted len))
999 ;; If only round bit is set, then round to even.
1000 ((and (= low round-bit)
1001 (dotimes (i (- (%bignum-length x) (ceiling keep digit-size))
1003 (unless (zerop (%bignum-ref x i)) (return nil))))
1004 (let ((next (%bignum-ref shifted 1)))
1007 (float-from-bits shifted len))))
1008 ;; Otherwise, round up.
1012 ;;;; integer length and logcount
1014 (defun bignum-integer-length (bignum)
1015 (declare (type bignum-type bignum))
1016 (let* ((len (%bignum-length bignum))
1018 (digit (%bignum-ref bignum len-1)))
1019 (declare (type bignum-index len len-1)
1020 (type bignum-element-type digit))
1021 (+ (integer-length (%fixnum-digit-with-correct-sign digit))
1022 (* len-1 digit-size))))
1024 (defun bignum-logcount (bignum)
1025 (declare (type bignum-type bignum))
1026 (let* ((length (%bignum-length bignum))
1027 (plusp (%bignum-0-or-plusp bignum length))
1029 (declare (type bignum-index length)
1031 (do ((index 0 (1+ index)))
1032 ((= index length) result)
1033 (let ((digit (%bignum-ref bignum index)))
1034 (declare (type bignum-element-type digit))
1035 (incf result (logcount (if plusp digit (%lognot digit))))))))
1037 ;;;; logical operations
1041 (defun bignum-logical-not (a)
1042 (declare (type bignum-type a))
1043 (let* ((len (%bignum-length a))
1044 (res (%allocate-bignum len)))
1045 (declare (type bignum-index len))
1046 (dotimes (i len res)
1047 (declare (type bignum-index i))
1048 (setf (%bignum-ref res i) (%lognot (%bignum-ref a i))))))
1052 (defun bignum-logical-and (a b)
1053 (declare (type bignum-type a b))
1054 (let* ((len-a (%bignum-length a))
1055 (len-b (%bignum-length b))
1056 (a-plusp (%bignum-0-or-plusp a len-a))
1057 (b-plusp (%bignum-0-or-plusp b len-b)))
1058 (declare (type bignum-index len-a len-b))
1062 (logand-shorter-positive a len-a b (%allocate-bignum len-a))
1063 (logand-shorter-negative a len-a b len-b (%allocate-bignum len-b))))
1066 (logand-shorter-positive b len-b a (%allocate-bignum len-b))
1067 (logand-shorter-negative b len-b a len-a (%allocate-bignum len-a))))
1068 (t (logand-shorter-positive a len-a b (%allocate-bignum len-a))))))
1070 ;;; This takes a shorter bignum, a and len-a, that is positive. Because this
1071 ;;; is AND, we don't care about any bits longer than a's since its infinite 0
1072 ;;; sign bits will mask the other bits out of b. The result is len-a big.
1073 (defun logand-shorter-positive (a len-a b res)
1074 (declare (type bignum-type a b res)
1075 (type bignum-index len-a))
1077 (declare (type bignum-index i))
1078 (setf (%bignum-ref res i)
1079 (%logand (%bignum-ref a i) (%bignum-ref b i))))
1080 (%normalize-bignum res len-a))
1082 ;;; This takes a shorter bignum, a and len-a, that is negative. Because this
1083 ;;; is AND, we just copy any bits longer than a's since its infinite 1 sign
1084 ;;; bits will include any bits from b. The result is len-b big.
1085 (defun logand-shorter-negative (a len-a b len-b res)
1086 (declare (type bignum-type a b res)
1087 (type bignum-index len-a len-b))
1089 (declare (type bignum-index i))
1090 (setf (%bignum-ref res i)
1091 (%logand (%bignum-ref a i) (%bignum-ref b i))))
1092 (do ((i len-a (1+ i)))
1094 (declare (type bignum-index i))
1095 (setf (%bignum-ref res i) (%bignum-ref b i)))
1096 (%normalize-bignum res len-b))
1100 (defun bignum-logical-ior (a b)
1101 (declare (type bignum-type a b))
1102 (let* ((len-a (%bignum-length a))
1103 (len-b (%bignum-length b))
1104 (a-plusp (%bignum-0-or-plusp a len-a))
1105 (b-plusp (%bignum-0-or-plusp b len-b)))
1106 (declare (type bignum-index len-a len-b))
1110 (logior-shorter-positive a len-a b len-b (%allocate-bignum len-b))
1111 (logior-shorter-negative a len-a b len-b (%allocate-bignum len-b))))
1114 (logior-shorter-positive b len-b a len-a (%allocate-bignum len-a))
1115 (logior-shorter-negative b len-b a len-a (%allocate-bignum len-a))))
1116 (t (logior-shorter-positive a len-a b len-b (%allocate-bignum len-a))))))
1118 ;;; This takes a shorter bignum, a and len-a, that is positive. Because this
1119 ;;; is IOR, we don't care about any bits longer than a's since its infinite
1120 ;;; 0 sign bits will mask the other bits out of b out to len-b. The result
1122 (defun logior-shorter-positive (a len-a b len-b res)
1123 (declare (type bignum-type a b res)
1124 (type bignum-index len-a len-b))
1126 (declare (type bignum-index i))
1127 (setf (%bignum-ref res i)
1128 (%logior (%bignum-ref a i) (%bignum-ref b i))))
1129 (do ((i len-a (1+ i)))
1131 (declare (type bignum-index i))
1132 (setf (%bignum-ref res i) (%bignum-ref b i)))
1133 (%normalize-bignum res len-b))
1135 ;;; This takes a shorter bignum, a and len-a, that is negative. Because this
1136 ;;; is IOR, we just copy any bits longer than a's since its infinite 1 sign
1137 ;;; bits will include any bits from b. The result is len-b long.
1138 (defun logior-shorter-negative (a len-a b len-b res)
1139 (declare (type bignum-type a b res)
1140 (type bignum-index len-a len-b))
1142 (declare (type bignum-index i))
1143 (setf (%bignum-ref res i)
1144 (%logior (%bignum-ref a i) (%bignum-ref b i))))
1145 (do ((i len-a (1+ i))
1146 (sign (%sign-digit a len-a)))
1148 (declare (type bignum-index i))
1149 (setf (%bignum-ref res i) sign))
1150 (%normalize-bignum res len-b))
1154 (defun bignum-logical-xor (a b)
1155 (declare (type bignum-type a b))
1156 (let ((len-a (%bignum-length a))
1157 (len-b (%bignum-length b)))
1158 (declare (type bignum-index len-a len-b))
1160 (bignum-logical-xor-aux a len-a b len-b (%allocate-bignum len-b))
1161 (bignum-logical-xor-aux b len-b a len-a (%allocate-bignum len-a)))))
1163 ;;; This takes the shorter of two bignums in a and len-a. Res is len-b
1164 ;;; long. Do the XOR.
1165 (defun bignum-logical-xor-aux (a len-a b len-b res)
1166 (declare (type bignum-type a b res)
1167 (type bignum-index len-a len-b))
1169 (declare (type bignum-index i))
1170 (setf (%bignum-ref res i)
1171 (%logxor (%bignum-ref a i) (%bignum-ref b i))))
1172 (do ((i len-a (1+ i))
1173 (sign (%sign-digit a len-a)))
1175 (declare (type bignum-index i))
1176 (setf (%bignum-ref res i) (%logxor sign (%bignum-ref b i))))
1177 (%normalize-bignum res len-b))
1179 ;;;; LDB (load byte)
1182 FOR NOW WE DON'T USE LDB OR DPB. WE USE SHIFTS AND MASKS IN NUMBERS.LISP WHICH
1183 IS LESS EFFICIENT BUT EASIER TO MAINTAIN. BILL SAYS THIS CODE CERTAINLY WORKS!
1185 (defconstant maximum-fixnum-bits #!+ibm-rt-pc 27 #!-ibm-rt-pc 30)
1187 (defun bignum-load-byte (byte bignum)
1188 (declare (type bignum-type bignum))
1189 (let ((byte-len (byte-size byte))
1190 (byte-pos (byte-position byte)))
1191 (if (< byte-len maximum-fixnum-bits)
1192 (bignum-ldb-fixnum-res bignum byte-len byte-pos)
1193 (bignum-ldb-bignum-res bignum byte-len byte-pos))))
1195 ;;; This returns a fixnum result of loading a byte from a bignum. In order, we
1196 ;;; check for the following conditions:
1197 ;;; Insufficient bignum digits to start loading a byte --
1198 ;;; Return 0 or byte-len 1's depending on sign of bignum.
1199 ;;; One bignum digit containing the whole byte spec --
1200 ;;; Grab 'em, shift 'em, and mask out what we don't want.
1201 ;;; Insufficient bignum digits to cover crossing a digit boundary --
1202 ;;; Grab the available bits in the last digit, and or in whatever
1203 ;;; virtual sign bits we need to return a full byte spec.
1204 ;;; Else (we cross a digit boundary with all bits available) --
1205 ;;; Make a couple masks, grab what we want, shift it around, and
1206 ;;; LOGIOR it all together.
1207 ;;; Because (< maximum-fixnum-bits digit-size) and
1208 ;;; (< byte-len maximum-fixnum-bits),
1209 ;;; we only cross one digit boundary if any.
1210 (defun bignum-ldb-fixnum-res (bignum byte-len byte-pos)
1211 (multiple-value-bind (skipped-digits pos) (truncate byte-pos digit-size)
1212 (let ((bignum-len (%bignum-length bignum))
1213 (s-digits+1 (1+ skipped-digits)))
1214 (declare (type bignum-index bignum-len s-digits+1))
1215 (if (>= skipped-digits bignum-len)
1216 (if (%bignum-0-or-plusp bignum bignum-len)
1218 (%make-ones byte-len))
1219 (let ((end (+ pos byte-len)))
1220 (cond ((<= end digit-size)
1221 (logand (ash (%bignum-ref bignum skipped-digits) (- pos))
1222 ;; Must LOGAND after shift here.
1223 (%make-ones byte-len)))
1224 ((>= s-digits+1 bignum-len)
1225 (let* ((available-bits (- digit-size pos))
1226 (res (logand (ash (%bignum-ref bignum skipped-digits)
1228 ;; LOGAND should be unnecessary here
1229 ;; with a logical right shift or a
1230 ;; correct unsigned-byte-32 one.
1231 (%make-ones available-bits))))
1232 (if (%bignum-0-or-plusp bignum bignum-len)
1234 (logior (%ashl (%make-ones (- end digit-size))
1238 (let* ((high-bits-in-first-digit (- digit-size pos))
1239 (high-mask (%make-ones high-bits-in-first-digit))
1240 (low-bits-in-next-digit (- end digit-size))
1241 (low-mask (%make-ones low-bits-in-next-digit)))
1242 (declare (type bignum-element-type high-mask low-mask))
1243 (logior (%ashl (logand (%bignum-ref bignum s-digits+1)
1245 high-bits-in-first-digit)
1246 (logand (ash (%bignum-ref bignum skipped-digits)
1248 ;; LOGAND should be unnecessary here with
1249 ;; a logical right shift or a correct
1250 ;; unsigned-byte-32 one.
1253 ;;; This returns a bignum result of loading a byte from a bignum. In order, we
1254 ;;; check for the following conditions:
1255 ;;; Insufficient bignum digits to start loading a byte --
1256 ;;; Byte-pos starting on a digit boundary --
1257 ;;; Byte spec contained in one bignum digit --
1258 ;;; Grab the bits we want and stick them in a single digit result.
1259 ;;; Since we know byte-pos is non-zero here, we know our single digit
1260 ;;; will have a zero high sign bit.
1261 ;;; Else (unaligned multiple digits) --
1262 ;;; This is like doing a shift right combined with either masking
1263 ;;; out unwanted high bits from bignum or filling in virtual sign
1264 ;;; bits if bignum had insufficient bits. We use SHIFT-RIGHT-ALIGNED
1265 ;;; and reference lots of local variables this macro establishes.
1266 (defun bignum-ldb-bignum-res (bignum byte-len byte-pos)
1267 (multiple-value-bind (skipped-digits pos) (truncate byte-pos digit-size)
1268 (let ((bignum-len (%bignum-length bignum)))
1269 (declare (type bignum-index bignum-len))
1271 ((>= skipped-digits bignum-len)
1272 (make-bignum-virtual-ldb-bits bignum bignum-len byte-len))
1274 (make-aligned-ldb-bignum bignum bignum-len byte-len skipped-digits))
1275 ((< (+ pos byte-len) digit-size)
1276 (let ((res (%allocate-bignum 1)))
1277 (setf (%bignum-ref res 0)
1278 (logand (%ashr (%bignum-ref bignum skipped-digits) pos)
1279 (%make-ones byte-len)))
1282 (make-unaligned-ldb-bignum bignum bignum-len
1283 byte-len skipped-digits pos))))))
1285 ;;; This returns bits from bignum that don't physically exist. These are
1286 ;;; all zero or one depending on the sign of the bignum.
1287 (defun make-bignum-virtual-ldb-bits (bignum bignum-len byte-len)
1288 (if (%bignum-0-or-plusp bignum bignum-len)
1290 (multiple-value-bind (res-len-1 extra) (truncate byte-len digit-size)
1291 (declare (type bignum-index res-len-1))
1292 (let* ((res-len (1+ res-len-1))
1293 (res (%allocate-bignum res-len)))
1294 (declare (type bignum-index res-len))
1297 (setf (%bignum-ref res j) (%make-ones extra))
1298 (%normalize-bignum res res-len))
1299 (declare (type bignum-index j))
1300 (setf (%bignum-ref res j) all-ones-digit))))))
1302 ;;; Since we are picking up aligned digits, we just copy the whole digits
1303 ;;; we want and fill in extra bits. We might have a byte-len that extends
1304 ;;; off the end of the bignum, so we may have to fill in extra 1's if the
1305 ;;; bignum is negative.
1306 (defun make-aligned-ldb-bignum (bignum bignum-len byte-len skipped-digits)
1307 (multiple-value-bind (res-len-1 extra) (truncate byte-len digit-size)
1308 (declare (type bignum-index res-len-1))
1309 (let* ((res-len (1+ res-len-1))
1310 (res (%allocate-bignum res-len)))
1311 (declare (type bignum-index res-len))
1312 (do ((i skipped-digits (1+ i))
1314 ((or (= j res-len-1) (= i bignum-len))
1315 (cond ((< i bignum-len)
1316 (setf (%bignum-ref res j)
1317 (logand (%bignum-ref bignum i)
1318 (the bignum-element-type (%make-ones extra)))))
1319 ((%bignum-0-or-plusp bignum bignum-len))
1323 (setf (%bignum-ref res j) (%make-ones extra)))
1324 (setf (%bignum-ref res j) all-ones-digit))))
1325 (%normalize-bignum res res-len))
1326 (declare (type bignum-index i j))
1327 (setf (%bignum-ref res j) (%bignum-ref bignum i))))))
1329 ;;; This grabs unaligned bignum bits from bignum assuming byte-len causes at
1330 ;;; least one digit boundary crossing. We use SHIFT-RIGHT-UNALIGNED referencing
1331 ;;; lots of local variables established by it.
1332 (defun make-unaligned-ldb-bignum (bignum
1337 (multiple-value-bind (res-len-1 extra) (truncate byte-len digit-size)
1338 (shift-right-unaligned
1339 bignum skipped-digits pos (1+ res-len-1)
1340 ((or (= j res-len-1) (= i+1 bignum-len))
1341 (cond ((= j res-len-1)
1343 ((< extra high-bits-in-first-digit)
1344 (setf (%bignum-ref res j)
1345 (logand (ash (%bignum-ref bignum i) minus-start-pos)
1346 ;; Must LOGAND after shift here.
1347 (%make-ones extra))))
1349 (setf (%bignum-ref res j)
1350 (logand (ash (%bignum-ref bignum i) minus-start-pos)
1351 ;; LOGAND should be unnecessary here with a logical
1352 ;; right shift or a correct unsigned-byte-32 one.
1354 (when (%bignum-0-or-plusp bignum bignum-len)
1355 (setf (%bignum-ref res j)
1356 (logior (%bignum-ref res j)
1358 (- extra high-bits-in-first-digit))
1359 high-bits-in-first-digit)))))))
1361 (setf (%bignum-ref res j)
1362 (logand (ash (%bignum-ref bignum i) minus-start-pos)
1363 ;; LOGAND should be unnecessary here with a logical
1364 ;; right shift or a correct unsigned-byte-32 one.
1366 (unless (%bignum-0-or-plusp bignum bignum-len)
1367 ;; Fill in upper half of this result digit with 1's.
1368 (setf (%bignum-ref res j)
1369 (logior (%bignum-ref res j)
1370 (%ashl low-mask high-bits-in-first-digit)))
1371 ;; Fill in any extra 1's we need to be byte-len long.
1372 (do ((j (1+ j) (1+ j)))
1374 (setf (%bignum-ref res j) (%make-ones extra)))
1375 (setf (%bignum-ref res j) all-ones-digit)))))
1376 (%normalize-bignum res res-len))
1379 ;;;; DPB (deposit byte)
1381 (defun bignum-deposit-byte (new-byte byte-spec bignum)
1382 (declare (type bignum-type bignum))
1383 (let* ((byte-len (byte-size byte-spec))
1384 (byte-pos (byte-position byte-spec))
1385 (bignum-len (%bignum-length bignum))
1386 (bignum-plusp (%bignum-0-or-plusp bignum bignum-len))
1387 (byte-end (+ byte-pos byte-len))
1388 (res-len (1+ (max (ceiling byte-end digit-size) bignum-len)))
1389 (res (%allocate-bignum res-len)))
1390 (declare (type bignum-index bignum-len res-len))
1391 ;; Fill in an extra sign digit in case we set what would otherwise be the
1392 ;; last digit's last bit. Normalize at the end in case this was
1394 (unless bignum-plusp
1395 (setf (%bignum-ref res (1- res-len)) all-ones-digit))
1396 (multiple-value-bind (end-digit end-bits) (truncate byte-end digit-size)
1397 (declare (type bignum-index end-digit))
1398 ;; Fill in bits from bignum up to byte-pos.
1399 (multiple-value-bind (pos-digit pos-bits) (truncate byte-pos digit-size)
1400 (declare (type bignum-index pos-digit))
1402 (end (min pos-digit bignum-len)))
1404 (cond ((< i bignum-len)
1405 (unless (zerop pos-bits)
1406 (setf (%bignum-ref res i)
1407 (logand (%bignum-ref bignum i)
1408 (%make-ones pos-bits)))))
1413 (unless (zerop pos-bits)
1414 (setf (%bignum-ref res i) (%make-ones pos-bits))))
1415 (setf (%bignum-ref res i) all-ones-digit)))))
1416 (setf (%bignum-ref res i) (%bignum-ref bignum i)))
1417 ;; Fill in bits from new-byte.
1418 (if (typep new-byte 'fixnum)
1419 (deposit-fixnum-bits new-byte byte-len pos-digit pos-bits
1420 end-digit end-bits res)
1421 (deposit-bignum-bits new-byte byte-len pos-digit pos-bits
1422 end-digit end-bits res)))
1423 ;; Fill in remaining bits from bignum after byte-spec.
1424 (when (< end-digit bignum-len)
1425 (setf (%bignum-ref res end-digit)
1426 (logior (logand (%bignum-ref bignum end-digit)
1427 (%ashl (%make-ones (- digit-size end-bits))
1429 ;; DEPOSIT-FIXNUM-BITS and DEPOSIT-BIGNUM-BITS only store
1430 ;; bits from new-byte into res's end-digit element, so
1431 ;; we don't need to mask out unwanted high bits.
1432 (%bignum-ref res end-digit)))
1433 (do ((i (1+ end-digit) (1+ i)))
1435 (setf (%bignum-ref res i) (%bignum-ref bignum i)))))
1436 (%normalize-bignum res res-len)))
1438 ;;; This starts at result's pos-digit skipping pos-bits, and it stores bits
1439 ;;; from new-byte, a fixnum, into result. It effectively stores byte-len
1440 ;;; number of bits, but never stores past end-digit and end-bits in result.
1441 ;;; The first branch fires when all the bits we want from new-byte are present;
1442 ;;; if byte-len crosses from the current result digit into the next, the last
1443 ;;; argument to DEPOSIT-FIXNUM-DIGIT is a mask for those bits. The second
1444 ;;; branch handles the need to grab more bits than the fixnum new-byte has, but
1445 ;;; new-byte is positive; therefore, any virtual bits are zero. The mask for
1446 ;;; bits that don't fit in the current result digit is simply the remaining
1447 ;;; bits in the bignum digit containing new-byte; we don't care if we store
1448 ;;; some extra in the next result digit since they will be zeros. The last
1449 ;;; branch handles the need to grab more bits than the fixnum new-byte has, but
1450 ;;; new-byte is negative; therefore, any virtual bits must be explicitly filled
1451 ;;; in as ones. We call DEPOSIT-FIXNUM-DIGIT to grab what bits actually exist
1452 ;;; and to fill in the current result digit.
1453 (defun deposit-fixnum-bits (new-byte byte-len pos-digit pos-bits
1454 end-digit end-bits result)
1455 (declare (type bignum-index pos-digit end-digit))
1456 (let ((other-bits (- digit-size pos-bits))
1457 (new-byte-digit (%fixnum-to-digit new-byte)))
1458 (declare (type bignum-element-type new-byte-digit))
1459 (cond ((< byte-len maximum-fixnum-bits)
1460 (deposit-fixnum-digit new-byte-digit byte-len pos-digit pos-bits
1462 (- byte-len other-bits)))
1463 ((or (plusp new-byte) (zerop new-byte))
1464 (deposit-fixnum-digit new-byte-digit byte-len pos-digit pos-bits
1465 other-bits result pos-bits))
1467 (multiple-value-bind (digit bits)
1468 (deposit-fixnum-digit new-byte-digit byte-len pos-digit pos-bits
1470 (if (< (- byte-len other-bits) digit-size)
1471 (- byte-len other-bits)
1473 (declare (type bignum-index digit))
1474 (cond ((< digit end-digit)
1475 (setf (%bignum-ref result digit)
1476 (logior (%bignum-ref result digit)
1477 (%ashl (%make-ones (- digit-size bits)) bits)))
1478 (do ((i (1+ digit) (1+ i)))
1480 (setf (%bignum-ref result i) (%make-ones end-bits)))
1481 (setf (%bignum-ref result i) all-ones-digit)))
1482 ((> digit end-digit))
1484 (setf (%bignum-ref result digit)
1485 (logior (%bignum-ref result digit)
1486 (%ashl (%make-ones (- end-bits bits))
1489 ;;; This fills in the current result digit from new-byte-digit. The first case
1490 ;;; handles everything we want fitting in the current digit, and other-bits is
1491 ;;; the number of bits remaining to be filled in result's current digit. This
1492 ;;; number is digit-size minus pos-bits. The second branch handles filling in
1493 ;;; result's current digit, and it shoves the unused bits of new-byte-digit
1494 ;;; into the next result digit. This is correct regardless of new-byte-digit's
1495 ;;; sign. It returns the new current result digit and how many bits already
1496 ;;; filled in the result digit.
1497 (defun deposit-fixnum-digit (new-byte-digit byte-len pos-digit pos-bits
1498 other-bits result next-digit-bits-needed)
1499 (declare (type bignum-index pos-digit)
1500 (type bignum-element-type new-byte-digit next-digit-mask))
1501 (cond ((<= byte-len other-bits)
1502 ;; Bits from new-byte fit in the current result digit.
1503 (setf (%bignum-ref result pos-digit)
1504 (logior (%bignum-ref result pos-digit)
1505 (%ashl (logand new-byte-digit (%make-ones byte-len))
1507 (if (= byte-len other-bits)
1508 (values (1+ pos-digit) 0)
1509 (values pos-digit (+ byte-len pos-bits))))
1511 ;; Some of new-byte's bits go in current result digit.
1512 (setf (%bignum-ref result pos-digit)
1513 (logior (%bignum-ref result pos-digit)
1514 (%ashl (logand new-byte-digit (%make-ones other-bits))
1516 (let ((pos-digit+1 (1+ pos-digit)))
1517 ;; The rest of new-byte's bits go in the next result digit.
1518 (setf (%bignum-ref result pos-digit+1)
1519 (logand (ash new-byte-digit (- other-bits))
1520 ;; Must LOGAND after shift here.
1521 (%make-ones next-digit-bits-needed)))
1522 (if (= next-digit-bits-needed digit-size)
1523 (values (1+ pos-digit+1) 0)
1524 (values pos-digit+1 next-digit-bits-needed))))))
1526 ;;; This starts at result's pos-digit skipping pos-bits, and it stores bits
1527 ;;; from new-byte, a bignum, into result. It effectively stores byte-len
1528 ;;; number of bits, but never stores past end-digit and end-bits in result.
1529 ;;; When handling a starting bit unaligned with a digit boundary, we check
1530 ;;; in the second branch for the byte spec fitting into the pos-digit element
1531 ;;; after after pos-bits; DEPOSIT-UNALIGNED-BIGNUM-BITS expects at least one
1532 ;;; digit boundary crossing.
1533 (defun deposit-bignum-bits (bignum-byte byte-len pos-digit pos-bits
1534 end-digit end-bits result)
1535 (declare (type bignum-index pos-digit end-digit))
1536 (cond ((zerop pos-bits)
1537 (deposit-aligned-bignum-bits bignum-byte pos-digit end-digit end-bits
1539 ((or (= end-digit pos-digit)
1540 (and (= end-digit (1+ pos-digit))
1542 (setf (%bignum-ref result pos-digit)
1543 (logior (%bignum-ref result pos-digit)
1544 (%ashl (logand (%bignum-ref bignum-byte 0)
1545 (%make-ones byte-len))
1547 (t (deposit-unaligned-bignum-bits bignum-byte pos-digit pos-bits
1548 end-digit end-bits result))))
1550 ;;; This deposits bits from bignum-byte into result starting at pos-digit and
1551 ;;; the zero'th bit. It effectively only stores bits to end-bits in the
1552 ;;; end-digit element of result. The loop termination code takes care of
1553 ;;; picking up the last digit's bits or filling in virtual negative sign bits.
1554 (defun deposit-aligned-bignum-bits (bignum-byte pos-digit end-digit end-bits
1556 (declare (type bignum-index pos-digit end-digit))
1557 (let* ((bignum-len (%bignum-length bignum-byte))
1558 (bignum-plusp (%bignum-0-or-plusp bignum-byte bignum-len)))
1559 (declare (type bignum-index bignum-len))
1561 (j pos-digit (1+ j)))
1562 ((or (= j end-digit) (= i bignum-len))
1563 (cond ((= j end-digit)
1564 (cond ((< i bignum-len)
1565 (setf (%bignum-ref result j)
1566 (logand (%bignum-ref bignum-byte i)
1567 (%make-ones end-bits))))
1570 (setf (%bignum-ref result j) (%make-ones end-bits)))))
1575 (setf (%bignum-ref result j) (%make-ones end-bits)))
1576 (setf (%bignum-ref result j) all-ones-digit)))))
1577 (setf (%bignum-ref result j) (%bignum-ref bignum-byte i)))))
1579 ;;; This assumes at least one digit crossing.
1580 (defun deposit-unaligned-bignum-bits (bignum-byte pos-digit pos-bits
1581 end-digit end-bits result)
1582 (declare (type bignum-index pos-digit end-digit))
1583 (let* ((bignum-len (%bignum-length bignum-byte))
1584 (bignum-plusp (%bignum-0-or-plusp bignum-byte bignum-len))
1585 (low-mask (%make-ones pos-bits))
1586 (bits-past-pos-bits (- digit-size pos-bits))
1587 (high-mask (%make-ones bits-past-pos-bits))
1588 (minus-high-bits (- bits-past-pos-bits)))
1589 (declare (type bignum-element-type low-mask high-mask)
1590 (type bignum-index bignum-len))
1593 (j+1 (1+ pos-digit) (1+ j+1)))
1594 ((or (= j end-digit) (= i bignum-len))
1597 (setf (%bignum-ref result j)
1599 ((>= pos-bits end-bits)
1600 (logand (%bignum-ref result j) (%make-ones end-bits)))
1602 (logior (%bignum-ref result j)
1603 (%ashl (logand (%bignum-ref bignum-byte i)
1604 (%make-ones (- end-bits pos-bits)))
1607 (logand (%bignum-ref result j)
1608 ;; 0's between pos-bits and end-bits positions.
1609 (logior (%ashl (%make-ones (- digit-size end-bits))
1612 (t (logior (%bignum-ref result j)
1613 (%ashl (%make-ones (- end-bits pos-bits))
1617 (setf (%bignum-ref result j)
1618 (%ashl (%make-ones bits-past-pos-bits) pos-bits))
1619 (do ((j j+1 (1+ j)))
1621 (setf (%bignum-ref result j) (%make-ones end-bits)))
1622 (declare (type bignum-index j))
1623 (setf (%bignum-ref result j) all-ones-digit)))))
1624 (declare (type bignum-index i j j+1))
1625 (let ((digit (%bignum-ref bignum-byte i)))
1626 (declare (type bignum-element-type digit))
1627 (setf (%bignum-ref result j)
1628 (logior (%bignum-ref result j)
1629 (%ashl (logand digit high-mask) pos-bits)))
1630 (setf (%bignum-ref result j+1)
1631 (logand (ash digit minus-high-bits)
1632 ;; LOGAND should be unnecessary here with a logical right
1633 ;; shift or a correct unsigned-byte-32 one.
1639 ;;; This is the original sketch of the algorithm from which I implemented this
1640 ;;; TRUNCATE, assuming both operands are bignums. I should modify this to work
1641 ;;; with the documentation on my functions, as a general introduction. I've
1642 ;;; left this here just in case someone needs it in the future. Don't look at
1643 ;;; this unless reading the functions' comments leaves you at a loss. Remember
1644 ;;; this comes from Knuth, so the book might give you the right general
1649 ;;; If X's magnitude is less than Y's, then result is 0 with remainder X.
1651 ;;; Make x and y positive, copying x if it is already positive.
1653 ;;; Shift y left until there's a 1 in the 30'th bit (most significant, non-sign
1655 ;;; Just do most sig digit to determine how much to shift whole number.
1656 ;;; Shift x this much too.
1657 ;;; Remember this initial shift count.
1659 ;;; Allocate q to be len-x minus len-y quantity plus 1.
1661 ;;; i = last digit of x.
1662 ;;; k = last digit of q.
1666 ;;; j = last digit of y.
1669 ;;; if x[i] = y[j] then g = #xFFFFFFFF
1670 ;;; else g = x[i]x[i-1]/y[j].
1673 ;;; %UNSIGNED-MULTIPLY returns b and c defined below.
1674 ;;; a = x[i-1] - (logand (* g y[j]) #xFFFFFFFF).
1675 ;;; Use %UNSIGNED-MULTIPLY taking low-order result.
1676 ;;; b = (logand (ash (* g y[j-1]) -32) #xFFFFFFFF).
1677 ;;; c = (logand (* g y[j-1]) #xFFFFFFFF).
1679 ;;; if a > b, guess is too high
1680 ;;; g = g - 1; go back to "check guess".
1681 ;;; if a = b and c > x[i-2], guess is too high
1682 ;;; g = g - 1; go back to "check guess".
1683 ;;; GUESS IS 32-BIT NUMBER, SO USE THING TO KEEP IN SPECIAL REGISTER
1684 ;;; SAME FOR A, B, AND C.
1686 ;;; Subtract g * y from x[i - len-y+1]..x[i]. See paper for doing this in step.
1687 ;;; If x[i] < 0, guess is screwed up.
1688 ;;; negative g, then add 1
1689 ;;; zero or positive g, then subtract 1
1690 ;;; AND add y back into x[len-y+1..i].
1696 ;;; If k>=0, goto LOOP.
1698 ;;; Now quotient is good, but remainder is not.
1699 ;;; Shift x right by saved initial left shifting count.
1701 ;;; Check quotient and remainder signs.
1702 ;;; x pos y pos --> q pos r pos
1703 ;;; x pos y neg --> q neg r pos
1704 ;;; x neg y pos --> q neg r neg
1705 ;;; x neg y neg --> q pos r neg
1707 ;;; Normalize quotient and remainder. Cons result if necessary.
1709 ;;; These are used by BIGNUM-TRUNCATE and friends in the general case.
1710 (defvar *truncate-x*)
1711 (defvar *truncate-y*)
1713 ;;; Divide X by Y returning the quotient and remainder. In the
1714 ;;; general case, we shift Y to set up for the algorithm, and we use
1715 ;;; two buffers to save consing intermediate values. X gets
1716 ;;; destructively modified to become the remainder, and we have to
1717 ;;; shift it to account for the initial Y shift. After we multiple
1718 ;;; bind q and r, we first fix up the signs and then return the
1719 ;;; normalized results.
1720 (defun bignum-truncate (x y)
1721 (declare (type bignum-type x y))
1722 (let* ((x-plusp (%bignum-0-or-plusp x (%bignum-length x)))
1723 (y-plusp (%bignum-0-or-plusp y (%bignum-length y)))
1724 (x (if x-plusp x (negate-bignum x nil)))
1725 (y (if y-plusp y (negate-bignum y nil)))
1726 (len-x (%bignum-length x))
1727 (len-y (%bignum-length y)))
1728 (multiple-value-bind (q r)
1730 (bignum-truncate-single-digit x len-x y))
1731 ((plusp (bignum-compare y x))
1732 (let ((res (%allocate-bignum len-x)))
1734 (setf (%bignum-ref res i) (%bignum-ref x i)))
1737 (let ((len-x+1 (1+ len-x)))
1738 (with-bignum-buffers ((*truncate-x* len-x+1)
1739 (*truncate-y* (1+ len-y)))
1740 (let ((y-shift (shift-y-for-truncate y)))
1741 (shift-and-store-truncate-buffers x len-x y len-y y-shift)
1742 (values (return-quotient-leaving-remainder len-x+1 len-y)
1743 ;; Now that RETURN-QUOTIENT-LEAVING-REMAINDER
1744 ;; has executed, we just tidy up the remainder
1745 ;; (in *TRUNCATE-X*) and return it.
1748 (let ((res (%allocate-bignum len-y)))
1749 (declare (type bignum-type res))
1750 (bignum-replace res *truncate-x* :end2 len-y)
1751 (%normalize-bignum res len-y)))
1753 (shift-right-unaligned
1754 *truncate-x* 0 y-shift len-y
1756 (setf (%bignum-ref res j)
1757 (%ashr (%bignum-ref *truncate-x* i)
1759 (%normalize-bignum res res-len))
1761 (let ((quotient (cond ((eq x-plusp y-plusp) q)
1762 ((typep q 'fixnum) (the fixnum (- q)))
1763 (t (negate-bignum-in-place q))))
1764 (rem (cond (x-plusp r)
1765 ((typep r 'fixnum) (the fixnum (- r)))
1766 (t (negate-bignum-in-place r)))))
1767 (values (if (typep quotient 'fixnum)
1769 (%normalize-bignum quotient (%bignum-length quotient)))
1770 (if (typep rem 'fixnum)
1772 (%normalize-bignum rem (%bignum-length rem))))))))
1774 ;;; Divide X by Y when Y is a single bignum digit. BIGNUM-TRUNCATE
1775 ;;; fixes up the quotient and remainder with respect to sign and
1778 ;;; We don't have to worry about shifting Y to make its most
1779 ;;; significant digit sufficiently large for %FLOOR to return 32-bit
1780 ;;; quantities for the q-digit and r-digit. If Y is a single digit
1781 ;;; bignum, it is already large enough for %FLOOR. That is, it has
1782 ;;; some bits on pretty high in the digit.
1783 (defun bignum-truncate-single-digit (x len-x y)
1784 (declare (type bignum-index len-x))
1785 (let ((q (%allocate-bignum len-x))
1787 (y (%bignum-ref y 0)))
1788 (declare (type bignum-element-type r y))
1789 (do ((i (1- len-x) (1- i)))
1791 (multiple-value-bind (q-digit r-digit) (%floor r (%bignum-ref x i) y)
1792 (declare (type bignum-element-type q-digit r-digit))
1793 (setf (%bignum-ref q i) q-digit)
1795 (let ((rem (%allocate-bignum 1)))
1796 (setf (%bignum-ref rem 0) r)
1799 ;;; a helper function for BIGNUM-TRUNCATE
1801 ;;; Divide *TRUNCATE-X* by *TRUNCATE-Y*, returning the quotient
1802 ;;; and destructively modifying *TRUNCATE-X* so that it holds
1805 ;;; LEN-X and LEN-Y tell us how much of the buffers we care about.
1807 ;;; *TRUNCATE-X* definitely has at least three digits, and it has one
1808 ;;; more than *TRUNCATE-Y*. This keeps i, i-1, i-2, and low-x-digit
1809 ;;; happy. Thanks to SHIFT-AND-STORE-TRUNCATE-BUFFERS.
1810 (defun return-quotient-leaving-remainder (len-x len-y)
1811 (declare (type bignum-index len-x len-y))
1812 (let* ((len-q (- len-x len-y))
1813 ;; Add one for extra sign digit in case high bit is on.
1814 (q (%allocate-bignum (1+ len-q)))
1816 (y1 (%bignum-ref *truncate-y* (1- len-y)))
1817 (y2 (%bignum-ref *truncate-y* (- len-y 2)))
1821 (low-x-digit (- i len-y)))
1822 (declare (type bignum-index len-q k i i-1 i-2 low-x-digit)
1823 (type bignum-element-type y1 y2))
1825 (setf (%bignum-ref q k)
1826 (try-bignum-truncate-guess
1827 ;; This modifies *TRUNCATE-X*. Must access elements each pass.
1828 (bignum-truncate-guess y1 y2
1829 (%bignum-ref *truncate-x* i)
1830 (%bignum-ref *truncate-x* i-1)
1831 (%bignum-ref *truncate-x* i-2))
1833 (cond ((zerop k) (return))
1836 (shiftf i i-1 i-2 (1- i-2)))))
1839 ;;; This takes a digit guess, multiplies it by *TRUNCATE-Y* for a
1840 ;;; result one greater in length than LEN-Y, and subtracts this result
1841 ;;; from *TRUNCATE-X*. LOW-X-DIGIT is the first digit of X to start
1842 ;;; the subtraction, and we know X is long enough to subtract a LEN-Y
1843 ;;; plus one length bignum from it. Next we check the result of the
1844 ;;; subtraction, and if the high digit in X became negative, then our
1845 ;;; guess was one too big. In this case, return one less than GUESS
1846 ;;; passed in, and add one value of Y back into X to account for
1847 ;;; subtracting one too many. Knuth shows that the guess is wrong on
1848 ;;; the order of 3/b, where b is the base (2 to the digit-size power)
1849 ;;; -- pretty rarely.
1850 (defun try-bignum-truncate-guess (guess len-y low-x-digit)
1851 (declare (type bignum-index low-x-digit len-y)
1852 (type bignum-element-type guess))
1853 (let ((carry-digit 0)
1856 (declare (type bignum-element-type carry-digit)
1857 (type bignum-index i)
1859 ;; Multiply guess and divisor, subtracting from dividend simultaneously.
1861 (multiple-value-bind (high-digit low-digit)
1862 (%multiply-and-add guess
1863 (%bignum-ref *truncate-y* j)
1865 (declare (type bignum-element-type high-digit low-digit))
1866 (setf carry-digit high-digit)
1867 (multiple-value-bind (x temp-borrow)
1868 (%subtract-with-borrow (%bignum-ref *truncate-x* i)
1871 (declare (type bignum-element-type x)
1872 (fixnum temp-borrow))
1873 (setf (%bignum-ref *truncate-x* i) x)
1874 (setf borrow temp-borrow)))
1876 (setf (%bignum-ref *truncate-x* i)
1877 (%subtract-with-borrow (%bignum-ref *truncate-x* i)
1878 carry-digit borrow))
1879 ;; See whether guess is off by one, adding one Y back in if necessary.
1880 (cond ((%digit-0-or-plusp (%bignum-ref *truncate-x* i))
1883 ;; If subtraction has negative result, add one divisor value back
1884 ;; in. The guess was one too large in magnitude.
1885 (let ((i low-x-digit)
1888 (multiple-value-bind (v k)
1889 (%add-with-carry (%bignum-ref *truncate-y* j)
1890 (%bignum-ref *truncate-x* i)
1892 (declare (type bignum-element-type v))
1893 (setf (%bignum-ref *truncate-x* i) v)
1896 (setf (%bignum-ref *truncate-x* i)
1897 (%add-with-carry (%bignum-ref *truncate-x* i) 0 carry)))
1898 (%subtract-with-borrow guess 1 1)))))
1900 ;;; This returns a guess for the next division step. Y1 is the highest y
1901 ;;; digit, and y2 is the second to highest y digit. The x... variables are
1902 ;;; the three highest x digits for the next division step.
1904 ;;; From Knuth, our guess is either all ones or x-i and x-i-1 divided by y1,
1905 ;;; depending on whether x-i and y1 are the same. We test this guess by
1906 ;;; determining whether guess*y2 is greater than the three high digits of x
1907 ;;; minus guess*y1 shifted left one digit:
1908 ;;; ------------------------------
1909 ;;; | x-i | x-i-1 | x-i-2 |
1910 ;;; ------------------------------
1911 ;;; ------------------------------
1912 ;;; - | g*y1 high | g*y1 low | 0 |
1913 ;;; ------------------------------
1914 ;;; ... < guess*y2 ???
1915 ;;; If guess*y2 is greater, then we decrement our guess by one and try again.
1916 ;;; This returns a guess that is either correct or one too large.
1917 (defun bignum-truncate-guess (y1 y2 x-i x-i-1 x-i-2)
1918 (declare (type bignum-element-type y1 y2 x-i x-i-1 x-i-2))
1919 (let ((guess (if (%digit-compare x-i y1)
1921 (%floor x-i x-i-1 y1))))
1922 (declare (type bignum-element-type guess))
1924 (multiple-value-bind (high-guess*y1 low-guess*y1) (%multiply guess y1)
1925 (declare (type bignum-element-type low-guess*y1 high-guess*y1))
1926 (multiple-value-bind (high-guess*y2 low-guess*y2)
1927 (%multiply guess y2)
1928 (declare (type bignum-element-type high-guess*y2 low-guess*y2))
1929 (multiple-value-bind (middle-digit borrow)
1930 (%subtract-with-borrow x-i-1 low-guess*y1 1)
1931 (declare (type bignum-element-type middle-digit)
1933 ;; Supplying borrow of 1 means there was no borrow, and we know
1934 ;; x-i-2 minus 0 requires no borrow.
1935 (let ((high-digit (%subtract-with-borrow x-i high-guess*y1 borrow)))
1936 (declare (type bignum-element-type high-digit))
1937 (if (and (%digit-compare high-digit 0)
1938 (or (%digit-greater high-guess*y2 middle-digit)
1939 (and (%digit-compare middle-digit high-guess*y2)
1940 (%digit-greater low-guess*y2 x-i-2))))
1941 (setf guess (%subtract-with-borrow guess 1 1))
1942 (return guess)))))))))
1944 ;;; This returns the amount to shift y to place a one in the second highest
1945 ;;; bit. Y must be positive. If the last digit of y is zero, then y has a
1946 ;;; one in the previous digit's sign bit, so we know it will take one less
1947 ;;; than digit-size to get a one where we want. Otherwise, we count how many
1948 ;;; right shifts it takes to get zero; subtracting this value from digit-size
1949 ;;; tells us how many high zeros there are which is one more than the shift
1952 ;;; Note: This is exactly the same as one less than the integer-length of the
1953 ;;; last digit subtracted from the digit-size.
1955 ;;; We shift y to make it sufficiently large that doing the 64-bit by 32-bit
1956 ;;; %FLOOR calls ensures the quotient and remainder fit in 32-bits.
1957 (defun shift-y-for-truncate (y)
1958 (let* ((len (%bignum-length y))
1959 (last (%bignum-ref y (1- len))))
1960 (declare (type bignum-index len)
1961 (type bignum-element-type last))
1962 (- digit-size (integer-length last) 1)))
1964 ;;; Stores two bignums into the truncation bignum buffers, shifting them on the
1965 ;;; way in. This assumes x and y are positive and at least two in length, and
1966 ;;; it assumes *truncate-x* and *truncate-y* are one digit longer than x and y.
1967 (defun shift-and-store-truncate-buffers (x len-x y len-y shift)
1968 (declare (type bignum-index len-x len-y)
1969 (type (integer 0 (#.digit-size)) shift))
1970 (cond ((zerop shift)
1971 (bignum-replace *truncate-x* x :end1 len-x)
1972 (bignum-replace *truncate-y* y :end1 len-y))
1974 (bignum-ashift-left-unaligned x 0 shift (1+ len-x) *truncate-x*)
1975 (bignum-ashift-left-unaligned y 0 shift (1+ len-y) *truncate-y*))))
1977 ;;;; %FLOOR primitive for BIGNUM-TRUNCATE
1979 ;;; When a machine leaves out a 64-bit by 32-bit divide instruction (that is,
1980 ;;; two bignum-digits divided by one), we have to roll our own (the hard way).
1981 ;;; Basically, we treat the operation as four 16-bit digits divided by two
1982 ;;; 16-bit digits. This means we have duplicated most of the code above to do
1983 ;;; this nearly general 16-bit digit bignum divide, but we've unrolled loops
1984 ;;; and made use of other properties of this specific divide situation.
1986 ;;;; %FLOOR for machines with a 32x32 divider.
1989 (declaim (inline 32x16-subtract-with-borrow 32x16-add-with-carry
1990 32x16-divide 32x16-multiply 32x16-multiply-split))
1993 (defconstant 32x16-base-1 #xFFFF)
1995 ;;; This is similar to %SUBTRACT-WITH-BORROW. It returns a 16-bit difference
1996 ;;; and a borrow. Returning a 1 for the borrow means there was no borrow, and
1997 ;;; 0 means there was one.
1999 (defun 32x16-subtract-with-borrow (a b borrow)
2000 (declare (type (unsigned-byte 16) a b)
2001 (type (integer 0 1) borrow))
2002 (let ((diff (+ (- a b) borrow 32x16-base-1)))
2003 (declare (type (unsigned-byte 17) diff))
2004 (values (logand diff #xFFFF)
2007 ;;; This adds a and b, 16-bit quantities, with the carry k. It returns a
2008 ;;; 16-bit sum and a second value, 0 or 1, indicating whether there was a
2011 (defun 32x16-add-with-carry (a b k)
2012 (declare (type (unsigned-byte 16) a b)
2013 (type (integer 0 1) k))
2014 (let ((res (the fixnum (+ a b k))))
2015 (declare (type (unsigned-byte 17) res))
2016 (if (zerop (the fixnum (logand #x10000 res)))
2018 (values (the (unsigned-byte 16) (logand #xFFFF res))
2021 ;;; This is probably a 32-bit by 32-bit divide instruction.
2023 (defun 32x16-divide (a b c)
2024 (declare (type (unsigned-byte 16) a b c))
2025 (floor (the bignum-element-type
2026 (logior (the bignum-element-type (ash a 16))
2030 ;;; This basically exists since we know the answer won't overflow
2031 ;;; bignum-element-type. It's probably just a basic multiply instruction, but
2032 ;;; it can't cons an intermediate bignum. The result goes in a non-descriptor
2035 (defun 32x16-multiply (a b)
2036 (declare (type (unsigned-byte 16) a b))
2037 (the bignum-element-type (* a b)))
2039 ;;; This multiplies a and b, 16-bit quantities, and returns the result as two
2040 ;;; 16-bit quantities, high and low.
2042 (defun 32x16-multiply-split (a b)
2043 (let ((res (32x16-multiply a b)))
2044 (declare (the bignum-element-type res))
2045 (values (the (unsigned-byte 16) (logand #xFFFF (ash res -16)))
2046 (the (unsigned-byte 16) (logand #xFFFF res)))))
2048 ;;; The %FLOOR below uses this buffer the same way BIGNUM-TRUNCATE uses
2049 ;;; *truncate-x*. There's no y buffer since we pass around the two 16-bit
2050 ;;; digits and use them slightly differently than the general truncation
2051 ;;; algorithm above.
2053 (defvar *32x16-truncate-x* (make-array 4 :element-type '(unsigned-byte 16)
2054 :initial-element 0))
2056 ;;; This does the same thing as the %FLOOR above, but it does it at Lisp level
2057 ;;; when there is no 64x32-bit divide instruction on the machine.
2059 ;;; It implements the higher level tactics of BIGNUM-TRUNCATE, but it makes use
2060 ;;; of special situation provided, four 16-bit digits divided by two 16-bit
2063 (defun %floor (a b c)
2064 (declare (type bignum-element-type a b c))
2065 ;; Setup *32x16-truncate-x* buffer from a and b.
2066 (setf (aref *32x16-truncate-x* 0)
2067 (the (unsigned-byte 16) (logand #xFFFF b)))
2068 (setf (aref *32x16-truncate-x* 1)
2069 (the (unsigned-byte 16)
2071 (the (unsigned-byte 16) (ash b -16)))))
2072 (setf (aref *32x16-truncate-x* 2)
2073 (the (unsigned-byte 16) (logand #xFFFF a)))
2074 (setf (aref *32x16-truncate-x* 3)
2075 (the (unsigned-byte 16)
2077 (the (unsigned-byte 16) (ash a -16)))))
2078 ;; From DO-TRUNCATE, but unroll the loop.
2079 (let* ((y1 (logand #xFFFF (ash c -16)))
2080 (y2 (logand #xFFFF c))
2081 (q (the bignum-element-type
2082 (ash (32x16-try-bignum-truncate-guess
2083 (32x16-truncate-guess y1 y2
2084 (aref *32x16-truncate-x* 3)
2085 (aref *32x16-truncate-x* 2)
2086 (aref *32x16-truncate-x* 1))
2089 (declare (type bignum-element-type q)
2090 (type (unsigned-byte 16) y1 y2))
2091 (values (the bignum-element-type
2093 (the (unsigned-byte 16)
2094 (32x16-try-bignum-truncate-guess
2095 (32x16-truncate-guess
2097 (aref *32x16-truncate-x* 2)
2098 (aref *32x16-truncate-x* 1)
2099 (aref *32x16-truncate-x* 0))
2101 (the bignum-element-type
2102 (logior (the bignum-element-type
2103 (ash (aref *32x16-truncate-x* 1) 16))
2104 (the (unsigned-byte 16)
2105 (aref *32x16-truncate-x* 0)))))))
2107 ;;; This is similar to TRY-BIGNUM-TRUNCATE-GUESS, but this unrolls the two
2108 ;;; loops. This also substitutes for %DIGIT-0-OR-PLUSP the equivalent
2109 ;;; expression without any embellishment or pretense of abstraction. The first
2110 ;;; loop is unrolled, but we've put the body of the loop into the function
2111 ;;; 32X16-TRY-GUESS-ONE-RESULT-DIGIT.
2113 (defun 32x16-try-bignum-truncate-guess (guess y-high y-low low-x-digit)
2114 (declare (type bignum-index low-x-digit)
2115 (type (unsigned-byte 16) guess y-high y-low))
2116 (let ((high-x-digit (+ 2 low-x-digit)))
2117 ;; Multiply guess and divisor, subtracting from dividend simultaneously.
2118 (multiple-value-bind (guess*y-hold carry borrow)
2119 (32x16-try-guess-one-result-digit guess y-low 0 0 1 low-x-digit)
2120 (declare (type (unsigned-byte 16) guess*y-hold)
2121 (fixnum carry borrow))
2122 (multiple-value-bind (guess*y-hold carry borrow)
2123 (32x16-try-guess-one-result-digit guess y-high guess*y-hold
2124 carry borrow (1+ low-x-digit))
2125 (declare (type (unsigned-byte 16) guess*y-hold)
2128 (setf (aref *32x16-truncate-x* high-x-digit)
2129 (32x16-subtract-with-borrow (aref *32x16-truncate-x* high-x-digit)
2130 guess*y-hold borrow))))
2131 ;; See whether guess is off by one, adding one Y back in if necessary.
2132 (cond ((zerop (logand #x8000 (aref *32x16-truncate-x* high-x-digit)))
2133 ;; The subtraction result is zero or positive.
2136 ;; If subtraction has negative result, add one divisor value back
2137 ;; in. The guess was one too large in magnitude.
2138 (multiple-value-bind (v carry)
2139 (32x16-add-with-carry y-low
2140 (aref *32x16-truncate-x* low-x-digit)
2142 (declare (type (unsigned-byte 16) v))
2143 (setf (aref *32x16-truncate-x* low-x-digit) v)
2144 (multiple-value-bind (v carry)
2145 (32x16-add-with-carry y-high
2146 (aref *32x16-truncate-x*
2149 (setf (aref *32x16-truncate-x* (1+ low-x-digit)) v)
2150 (setf (aref *32x16-truncate-x* high-x-digit)
2151 (32x16-add-with-carry (aref *32x16-truncate-x* high-x-digit)
2153 (if (zerop (logand #x8000 guess))
2157 ;;; This is similar to the body of the loop in TRY-BIGNUM-TRUNCATE-GUESS that
2158 ;;; multiplies the guess by y and subtracts the result from x simultaneously.
2159 ;;; This returns the digit remembered as part of the multiplication, the carry
2160 ;;; from additions done on behalf of the multiplication, and the borrow from
2161 ;;; doing the subtraction.
2163 (defun 32x16-try-guess-one-result-digit (guess y-digit guess*y-hold
2164 carry borrow x-index)
2165 (multiple-value-bind (high-digit low-digit)
2166 (32x16-multiply-split guess y-digit)
2167 (declare (type (unsigned-byte 16) high-digit low-digit))
2168 (multiple-value-bind (low-digit temp-carry)
2169 (32x16-add-with-carry low-digit guess*y-hold carry)
2170 (declare (type (unsigned-byte 16) low-digit))
2171 (multiple-value-bind (high-digit temp-carry)
2172 (32x16-add-with-carry high-digit temp-carry 0)
2173 (declare (type (unsigned-byte 16) high-digit))
2174 (multiple-value-bind (x temp-borrow)
2175 (32x16-subtract-with-borrow (aref *32x16-truncate-x* x-index)
2177 (declare (type (unsigned-byte 16) x))
2178 (setf (aref *32x16-truncate-x* x-index) x)
2179 (values high-digit temp-carry temp-borrow))))))
2181 ;;; This is similar to BIGNUM-TRUNCATE-GUESS, but instead of computing the
2182 ;;; guess exactly as described in the its comments (digit by digit), this
2183 ;;; massages the 16-bit quantities into 32-bit quantities and performs the
2185 (defun 32x16-truncate-guess (y1 y2 x-i x-i-1 x-i-2)
2186 (declare (type (unsigned-byte 16) y1 y2 x-i x-i-1 x-i-2))
2187 (let ((guess (if (= x-i y1)
2189 (32x16-divide x-i x-i-1 y1))))
2190 (declare (type (unsigned-byte 16) guess))
2192 (let* ((guess*y1 (the bignum-element-type
2194 (the bignum-element-type
2195 (32x16-multiply guess y1)))
2197 (x-y (%subtract-with-borrow
2198 (the bignum-element-type
2199 (logior (the bignum-element-type
2204 (guess*y2 (the bignum-element-type (%multiply guess y2))))
2205 (declare (type bignum-element-type guess*y1 x-y guess*y2))
2206 (if (%digit-greater guess*y2 x-y)
2210 ;;;; general utilities
2212 ;;; Allocate a single word bignum that holds fixnum. This is useful when
2213 ;;; we are trying to mix fixnum and bignum operands.
2214 #!-sb-fluid (declaim (inline make-small-bignum))
2215 (defun make-small-bignum (fixnum)
2216 (let ((res (%allocate-bignum 1)))
2217 (setf (%bignum-ref res 0) (%fixnum-to-digit fixnum))
2220 ;;; Internal in-place operations use this to fixup remaining digits in the
2221 ;;; incoming data, such as in-place shifting. This is basically the same as
2222 ;;; the first form in %NORMALIZE-BIGNUM, but we return the length of the buffer
2223 ;;; instead of shrinking the bignum.
2224 #!-sb-fluid (declaim (sb!ext:maybe-inline %normalize-bignum-buffer))
2225 (defun %normalize-bignum-buffer (result len)
2226 (declare (type bignum-type result)
2227 (type bignum-index len))
2229 (do ((next-digit (%bignum-ref result (- len 2))
2230 (%bignum-ref result (- len 2)))
2231 (sign-digit (%bignum-ref result (1- len)) next-digit))
2232 ((not (zerop (logxor sign-digit (%ashr next-digit (1- digit-size))))))
2234 (setf (%bignum-ref result len) 0)
2239 ;;; This drops the last digit if it is unnecessary sign information. It repeats
2240 ;;; this as needed, possibly ending with a fixnum. If the resulting length from
2241 ;;; shrinking is one, see whether our one word is a fixnum. Shift the possible
2242 ;;; fixnum bits completely out of the word, and compare this with shifting the
2243 ;;; sign bit all the way through. If the bits are all 1's or 0's in both words,
2244 ;;; then there are just sign bits between the fixnum bits and the sign bit. If
2245 ;;; we do have a fixnum, shift it over for the two low-tag bits.
2246 (defun %normalize-bignum (result len)
2247 (declare (type bignum-type result)
2248 (type bignum-index len)
2249 (inline %normalize-bignum-buffer))
2250 (let ((newlen (%normalize-bignum-buffer result len)))
2251 (declare (type bignum-index newlen))
2252 (unless (= newlen len)
2253 (%bignum-set-length result newlen))
2255 (let ((digit (%bignum-ref result 0)))
2256 (if (= (%ashr digit 29) (%ashr digit (1- digit-size)))
2257 (%fixnum-digit-with-correct-sign digit)
2261 ;;; This drops the last digit if it is unnecessary sign information. It
2262 ;;; repeats this as needed, possibly ending with a fixnum magnitude but never
2263 ;;; returning a fixnum.
2264 (defun %mostly-normalize-bignum (result len)
2265 (declare (type bignum-type result)
2266 (type bignum-index len)
2267 (inline %normalize-bignum-buffer))
2268 (let ((newlen (%normalize-bignum-buffer result len)))
2269 (declare (type bignum-index newlen))
2270 (unless (= newlen len)
2271 (%bignum-set-length result newlen))
2276 ;;; the bignum case of the SXHASH function
2277 (defun sxhash-bignum (x)
2278 (let ((result 316495330))
2279 (declare (type fixnum result))
2280 (dotimes (i (%bignum-length x))
2281 (declare (type index i))
2282 (let ((xi (%bignum-ref x i)))
2284 (logand most-positive-fixnum