df1d328abc067851e437d80991f057dbaf84c5f8
[sbcl.git] / src / code / bignum.lisp
1 ;;;; code to implement bignum support
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!BIGNUM")
13 \f
14 ;;;; notes
15
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
25 ;;;       bignum-logbitp bignum-logcount
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))
33
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 ;;;    GCD/Relational operators:
61 ;;;       %DIGIT-COMPARE
62 ;;;       %DIGIT-GREATER
63 ;;;    Relational operators:
64 ;;;       %LOGAND
65 ;;;       %LOGIOR
66 ;;;       %LOGXOR
67 ;;;    LDB
68 ;;;       %FIXNUM-TO-DIGIT
69 ;;;    TRUNCATE
70 ;;;       %FLOOR
71 ;;;
72 ;;; Note: The floating routines know about the float representation.
73 ;;;
74 ;;; PROBLEM 1:
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.
79 ;;;
80 ;;; PROBLEM 2:
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.
85 ;;;
86 ;;; To do:
87 ;;;    fixnums
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.
96 ;;;       addition
97 ;;;       subtraction (twice)
98 ;;;       multiply
99 ;;;       GCD
100 ;;;    Write MASK-FIELD and DEPOSIT-FIELD in terms of logical operations.
101 ;;;    DIVIDE
102 ;;;       IF (/ x y) with bignums:
103 ;;;       do the truncate, and if rem is 0, return quotient.
104 ;;;       if rem is non-0
105 ;;;          gcd of x and y.
106 ;;;          "truncate" each by gcd, ignoring remainder 0.
107 ;;;          form ratio of each result, bottom is positive.
108 \f
109 ;;;; What's a bignum?
110
111 (defconstant digit-size 32)
112
113 (defconstant maximum-bignum-length (1- (ash 1 (- 32 sb!vm:n-widetag-bits))))
114 \f
115 ;;;; internal inline routines
116
117 ;;; %ALLOCATE-BIGNUM must zero all elements.
118 (defun %allocate-bignum (length)
119   (declare (type bignum-index length))
120   (%allocate-bignum length))
121
122 ;;; Extract the length of the bignum.
123 (defun %bignum-length (bignum)
124   (declare (type bignum-type bignum))
125   (%bignum-length bignum))
126
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))
138
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)))
143
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))))
149
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))
157
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.
161 ;;;
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))
167
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))
172   (%multiply x y))
173
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))
187
188 (defun %lognot (digit)
189   (declare (type bignum-element-type digit))
190   (%lognot digit))
191
192 ;;; Each of these does the 32-bit unsigned op.
193 #!-sb-fluid (declaim (inline %logand %logior %logxor))
194 (defun %logand (a b)
195   (declare (type bignum-element-type a b))
196   (logand a b))
197 (defun %logior (a b)
198   (declare (type bignum-element-type a b))
199   (logior a b))
200 (defun %logxor (a b)
201   (declare (type bignum-element-type a b))
202   (logxor a b))
203
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)
207   (declare (fixnum x))
208   (logand x (1- (ash 1 digit-size))))
209
210 #!-32x16-divide
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.
213 ;;;
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))
220     (setq a a b b c c)
221     (%floor a b c)))
222
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))
228       digit))
229
230 ;;; Do an arithmetic shift right of data even though bignum-element-type is
231 ;;; unsigned.
232 (defun %ashr (data count)
233   (declare (type bignum-element-type data)
234            (type (mod 32) count))
235   (%ashr data count))
236
237 ;;; This takes a 32-bit quantity and shifts it to the left, returning a 32-bit
238 ;;; quantity.
239 (defun %ashl (data count)
240   (declare (type bignum-element-type data)
241            (type (mod 32) count))
242   (%ashl data count))
243
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))
249
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))
256
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)))
266
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)
271   (= x y))
272 (defun %digit-greater (x y)
273   (> x y))
274 \f
275 (declaim (optimize (speed 3) (safety 0)))
276 \f
277 ;;;; addition
278
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)
285         (if (> len-a 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))
292              (carry 0))
293         (declare (type bignum-index len-res)
294                  (type bignum-type res)
295                  (type (mod 2) carry))
296         (dotimes (i len-b)
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)
301                      (type (mod 2) k))
302             (setf (%bignum-ref res i) v)
303             (setf carry k)))
304         (if (/= len-a len-b)
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)
309                                    carry)))
310         (%normalize-bignum res len-res)))))
311
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)
316            (type (mod 2) carry)
317            (type bignum-element-type sign-digit-b)
318            (type bignum-index start end))
319   (do ((i start (1+ i)))
320       ((= i end)
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)
327       (setf carry k)))
328   (values))
329 \f
330 ;;;; subtraction
331
332 (eval-when (:compile-toplevel :execute)
333
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))
339         (a-digit (gensym))
340         (a-sign (gensym))
341         (b-digit (gensym))
342         (b-sign (gensym))
343         (i (gensym))
344         (v (gensym))
345         (k (gensym)))
346     `(let* ((,borrow 1)
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)
358              (setf ,borrow ,k))))
359        (,return-fun ,res ,len-res))))
360
361 ) ;EVAL-WHEN
362
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)))
371
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
374 ;;; result.
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)))
381 \f
382 ;;;; multiplication
383
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))
396     (dotimes (i len-a)
397       (declare (type bignum-index i))
398       (let ((carry-digit 0)
399             (x (%bignum-ref a i))
400             (k i))
401         (declare (type bignum-index k)
402                  (type bignum-element-type carry-digit x))
403         (dotimes (j len-b)
404           (multiple-value-bind (big-carry res-digit)
405               (%multiply-and-add x
406                                  (%bignum-ref b j)
407                                  (%bignum-ref res k)
408                                  carry-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)
412             (incf k)))
413         (setf (%bignum-ref res k) carry-digit)))
414     (when negate-res (negate-bignum-in-place res))
415     (%normalize-bignum res len-res)))
416
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)))
425          (carry-digit 0))
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))))
440
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)
454                 low
455                 (- low)))
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))))))
461 \f
462 ;;;; BIGNUM-REPLACE and WITH-BIGNUM-BUFFERS
463
464 (eval-when (:compile-toplevel :execute)
465
466 (sb!xc:defmacro bignum-replace (dest
467                                 src
468                                 &key
469                                 (start1 '0)
470                                 end1
471                                 (start2 '0)
472                                 end2
473                                 from-end)
474   (sb!int:once-only ((n-dest dest)
475                      (n-src src))
476     (let ((n-start1 (gensym))
477           (n-end1 (gensym))
478           (n-start2 (gensym))
479           (n-end2 (gensym))
480           (i1 (gensym))
481           (i2 (gensym))
482           (end1 (or end1 `(%bignum-length ,n-dest)))
483           (end2 (or end2 `(%bignum-length ,n-src))))
484       (if from-end
485           `(let ((,n-start1 ,start1)
486                  (,n-start2 ,start2))
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)
494                  (,n-end2 ,end2))
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))))))))
501
502 (sb!xc:defmacro with-bignum-buffers (specs &body body)
503   #!+sb-doc
504   "WITH-BIGNUM-BUFFERS ({(var size [init])}*) Form*"
505   (sb!int:collect ((binds)
506                    (inits))
507     (dolist (spec specs)
508       (let ((name (first spec))
509             (size (second spec)))
510         (binds `(,name (%allocate-bignum ,size)))
511         (let ((init (third spec)))
512           (when init
513             (inits `(bignum-replace ,name ,init))))))
514     `(let* ,(binds)
515        ,@(inits)
516        ,@body)))
517
518 ) ;EVAL-WHEN
519 \f
520 ;;;; GCD
521
522 ;;; I'm not sure why I need this FTYPE declaration.  Compiled by the
523 ;;; target compiler, it can deduce the return type fine, but without
524 ;;; it, we pay a heavy price in BIGNUM-GCD when compiled by the
525 ;;; cross-compiler. -- CSR, 2004-07-19
526 (declaim (ftype (sfunction (bignum-type bignum-index bignum-type bignum-index)
527                            (unsigned-byte 29))
528                 bignum-factors-of-two))
529 (defun bignum-factors-of-two (a len-a b len-b)
530   (declare (type bignum-index len-a len-b) (type bignum-type a b))
531   (do ((i 0 (1+ i))
532        (end (min len-a len-b)))
533       ((= i end) (error "Unexpected zero bignums?"))
534     (declare (type bignum-index i end))
535     (let ((or-digits (%logior (%bignum-ref a i) (%bignum-ref b i))))
536       (unless (zerop or-digits)
537         (return (do ((j 0 (1+ j))
538                      (or-digits or-digits (%ashr or-digits 1)))
539                     ((oddp or-digits) (+ (* i digit-size) j))
540                   (declare (type (mod 32) j))))))))
541
542 (defun bignum-gcd (a b)
543   (let* ((a (if (%bignum-0-or-plusp a (%bignum-length a))
544                 a
545                 (negate-bignum a nil)))
546          (b (if (%bignum-0-or-plusp b (%bignum-length b))
547                 b
548                 (negate-bignum b nil))))
549     (declare (type bignum-type a b))
550     (when (< a b)
551       (rotatef a b))
552     ;; While the length difference of A and B is sufficiently large,
553     ;; reduce using MOD (slowish, but it should equalize the sizes of
554     ;; A and B pretty quickly). After that, use the binary GCD
555     ;; algorithm to handle the rest. The initial reduction using MOD
556     ;; is sufficient to get rid of the embarrasing order of magnitude
557     ;; difference in GCD/LCM performance between SBCL and most other
558     ;; lisps.
559     ;;
560     ;; FIXME: Using a better algorithm (for example Weber's accelerated
561     ;; integer GCD) would be nice.
562     ;;   -- JES, 2004-07-31
563     (loop until (and (= (%bignum-length b) 1) (zerop (%bignum-ref b 0))) do
564           (when (<= (%bignum-length a) (1+ (%bignum-length b)))
565             (return-from bignum-gcd (bignum-binary-gcd a b)))
566           (let ((rem (mod a b)))
567             (if (fixnump rem)
568                 (setf a (make-small-bignum rem))
569                 (setf a rem))
570             (rotatef a b)))
571     a))
572   
573 (defun bignum-binary-gcd (a b)
574   (declare (type bignum-type a b))
575   (let* ((len-a (%bignum-length a))
576          (len-b (%bignum-length b)))
577     (declare (type bignum-index len-a len-b))
578     (with-bignum-buffers ((a-buffer len-a a)
579                           (b-buffer len-b b)
580                           (res-buffer (max len-a len-b)))
581       (let* ((factors-of-two
582               (bignum-factors-of-two a-buffer len-a
583                                      b-buffer len-b))
584              (len-a (make-gcd-bignum-odd
585                      a-buffer
586                      (bignum-buffer-ashift-right a-buffer len-a
587                                                  factors-of-two)))
588              (len-b (make-gcd-bignum-odd
589                      b-buffer
590                      (bignum-buffer-ashift-right b-buffer len-b
591                                                  factors-of-two))))
592         (declare (type bignum-index len-a len-b))
593         (let ((x a-buffer)
594               (len-x len-a)
595               (y b-buffer)
596               (len-y len-b)
597               (z res-buffer))
598           (loop
599             (multiple-value-bind (u v len-v r len-r)
600                 (bignum-gcd-order-and-subtract x len-x y len-y z)
601               (declare (type bignum-index len-v len-r))
602               (when (and (= len-r 1) (zerop (%bignum-ref r 0)))
603                 (if (zerop factors-of-two)
604                     (let ((ret (%allocate-bignum len-v)))
605                       (dotimes (i len-v)
606                         (setf (%bignum-ref ret i) (%bignum-ref v i)))
607                       (return (%normalize-bignum ret len-v)))
608                     (return (bignum-ashift-left v factors-of-two len-v))))
609               (setf x v  len-x len-v)
610               (setf y r  len-y (make-gcd-bignum-odd r len-r))
611               (setf z u))))))))
612
613 (defun bignum-gcd-order-and-subtract (a len-a b len-b res)
614   (declare (type bignum-index len-a len-b) (type bignum-type a b))
615   (cond ((= len-a len-b)
616          (do ((i (1- len-a) (1- i)))
617              ((= i -1)
618               (setf (%bignum-ref res 0) 0)
619               (values a b len-b res 1))
620            (let ((a-digit (%bignum-ref a i))
621                  (b-digit (%bignum-ref b i)))
622              (cond ((%digit-compare a-digit b-digit))
623                    ((%digit-greater a-digit b-digit)
624                     (return
625                      (values a b len-b res
626                              (subtract-bignum-buffers a len-a b len-b res))))
627                    (t
628                     (return
629                      (values b a len-a res
630                              (subtract-bignum-buffers b len-b
631                                                       a len-a
632                                                       res))))))))
633         ((> len-a len-b)
634          (values a b len-b res
635                  (subtract-bignum-buffers a len-a b len-b res)))
636         (t
637          (values b a len-a res
638                  (subtract-bignum-buffers b len-b a len-a res)))))
639
640 (defun make-gcd-bignum-odd (a len-a)
641   (declare (type bignum-type a) (type bignum-index len-a))
642   (dotimes (index len-a)
643     (declare (type bignum-index index))
644     (do ((digit (%bignum-ref a index) (%ashr digit 1))
645          (increment 0 (1+ increment)))
646         ((zerop digit))
647       (declare (type (mod 32) increment))
648       (when (oddp digit)
649         (return-from make-gcd-bignum-odd
650                      (bignum-buffer-ashift-right a len-a
651                                                  (+ (* index digit-size)
652                                                     increment)))))))
653 \f
654 ;;;; negation
655
656 (eval-when (:compile-toplevel :execute)
657
658 ;;; This negates bignum-len digits of bignum, storing the resulting digits into
659 ;;; result (possibly EQ to bignum) and returning whatever end-carry there is.
660 (sb!xc:defmacro bignum-negate-loop (bignum
661                                     bignum-len
662                                     &optional (result nil resultp))
663   (let ((carry (gensym))
664         (end (gensym))
665         (value (gensym))
666         (last (gensym)))
667     `(let* (,@(if (not resultp) `(,last))
668             (,carry
669              (multiple-value-bind (,value ,carry)
670                  (%add-with-carry (%lognot (%bignum-ref ,bignum 0)) 1 0)
671                ,(if resultp
672                     `(setf (%bignum-ref ,result 0) ,value)
673                     `(setf ,last ,value))
674                ,carry))
675             (i 1)
676             (,end ,bignum-len))
677        (declare (type bit ,carry)
678                 (type bignum-index i ,end))
679        (loop
680          (when (= i ,end) (return))
681          (multiple-value-bind (,value temp)
682              (%add-with-carry (%lognot (%bignum-ref ,bignum i)) 0 ,carry)
683            ,(if resultp
684                 `(setf (%bignum-ref ,result i) ,value)
685                 `(setf ,last ,value))
686            (setf ,carry temp))
687          (incf i))
688        ,(if resultp carry `(values ,carry ,last)))))
689
690 ) ; EVAL-WHEN
691
692 ;;; Fully-normalize is an internal optional. It cause this to always return
693 ;;; a bignum, without any extraneous digits, and it never returns a fixnum.
694 (defun negate-bignum (x &optional (fully-normalize t))
695   (declare (type bignum-type x))
696   (let* ((len-x (%bignum-length x))
697          (len-res (1+ len-x))
698          (res (%allocate-bignum len-res)))
699     (declare (type bignum-index len-x len-res)) ;Test len-res for range?
700     (let ((carry (bignum-negate-loop x len-x res)))
701       (setf (%bignum-ref res len-x)
702             (%add-with-carry (%lognot (%sign-digit x len-x)) 0 carry)))
703     (if fully-normalize
704         (%normalize-bignum res len-res)
705         (%mostly-normalize-bignum res len-res))))
706
707 ;;; This assumes bignum is positive; that is, the result of negating it will
708 ;;; stay in the provided allocated bignum.
709 (defun negate-bignum-in-place (bignum)
710   (bignum-negate-loop bignum (%bignum-length bignum) bignum)
711   bignum)
712 \f
713 ;;;; shifting
714
715 (defconstant all-ones-digit #xFFFFFFFF)
716
717 (eval-when (:compile-toplevel :execute)
718
719 ;;; This macro is used by BIGNUM-ASHIFT-RIGHT, BIGNUM-BUFFER-ASHIFT-RIGHT, and
720 ;;; BIGNUM-LDB-BIGNUM-RES. They supply a termination form that references
721 ;;; locals established by this form. Source is the source bignum. Start-digit
722 ;;; is the first digit in source from which we pull bits. Start-pos is the
723 ;;; first bit we want. Res-len-form is the form that computes the length of
724 ;;; the resulting bignum. Termination is a DO termination form with a test and
725 ;;; body. When result is supplied, it is the variable to which this binds a
726 ;;; newly allocated bignum.
727 ;;;
728 ;;; Given start-pos, 1-31 inclusively, of shift, we form the j'th resulting
729 ;;; digit from high bits of the i'th source digit and the start-pos number of
730 ;;; bits from the i+1'th source digit.
731 (sb!xc:defmacro shift-right-unaligned (source
732                                        start-digit
733                                        start-pos
734                                        res-len-form
735                                        termination
736                                        &optional result)
737   `(let* ((high-bits-in-first-digit (- digit-size ,start-pos))
738           (res-len ,res-len-form)
739           (res-len-1 (1- res-len))
740           ,@(if result `((,result (%allocate-bignum res-len)))))
741      (declare (type bignum-index res-len res-len-1))
742      (do ((i ,start-digit i+1)
743           (i+1 (1+ ,start-digit) (1+ i+1))
744           (j 0 (1+ j)))
745          ,termination
746        (declare (type bignum-index i i+1 j))
747        (setf (%bignum-ref ,(if result result source) j)
748              (%logior (%digit-logical-shift-right (%bignum-ref ,source i)
749                                                   ,start-pos)
750                       (%ashl (%bignum-ref ,source i+1)
751                              high-bits-in-first-digit))))))
752
753 ) ; EVAL-WHEN
754
755 ;;; First compute the number of whole digits to shift, shifting them by
756 ;;; skipping them when we start to pick up bits, and the number of bits to
757 ;;; shift the remaining digits into place. If the number of digits is greater
758 ;;; than the length of the bignum, then the result is either 0 or -1. If we
759 ;;; shift on a digit boundary (that is, n-bits is zero), then we just copy
760 ;;; digits. The last branch handles the general case which uses a macro that a
761 ;;; couple other routines use. The fifth argument to the macro references
762 ;;; locals established by the macro.
763 (defun bignum-ashift-right (bignum count)
764   (declare (type bignum-type bignum)
765            (type unsigned-byte count))
766   (let ((bignum-len (%bignum-length bignum)))
767     (declare (type bignum-index bignum-len))
768     (cond ((fixnump count)
769            (multiple-value-bind (digits n-bits) (truncate count digit-size)
770              (declare (type bignum-index digits))
771              (cond
772               ((>= digits bignum-len)
773                (if (%bignum-0-or-plusp bignum bignum-len) 0 -1))
774               ((zerop n-bits)
775                (bignum-ashift-right-digits bignum digits))
776               (t
777                (shift-right-unaligned bignum digits n-bits (- bignum-len digits)
778                                       ((= j res-len-1)
779                                        (setf (%bignum-ref res j)
780                                              (%ashr (%bignum-ref bignum i) n-bits))
781                                        (%normalize-bignum res res-len))
782                                       res)))))
783           ((> count bignum-len)
784            (if (%bignum-0-or-plusp bignum bignum-len) 0 -1))
785            ;; Since a FIXNUM should be big enough to address anything in
786            ;; memory, including arrays of bits, and since arrays of bits
787            ;; take up about the same space as corresponding fixnums, there
788            ;; should be no way that we fall through to this case: any shift
789            ;; right by a bignum should give zero. But let's check anyway:
790           (t (error "bignum overflow: can't shift right by ~S" count)))))
791
792 (defun bignum-ashift-right-digits (bignum digits)
793   (declare (type bignum-type bignum)
794            (type bignum-index digits))
795   (let* ((res-len (- (%bignum-length bignum) digits))
796          (res (%allocate-bignum res-len)))
797     (declare (type bignum-index res-len)
798              (type bignum-type res))
799     (bignum-replace res bignum :start2 digits)
800     (%normalize-bignum res res-len)))
801
802 ;;; GCD uses this for an in-place shifting operation. This is different enough
803 ;;; from BIGNUM-ASHIFT-RIGHT that it isn't worth folding the bodies into a
804 ;;; macro, but they share the basic algorithm. This routine foregoes a first
805 ;;; test for digits being greater than or equal to bignum-len since that will
806 ;;; never happen for its uses in GCD. We did fold the last branch into a macro
807 ;;; since it was duplicated a few times, and the fifth argument to it
808 ;;; references locals established by the macro.
809 (defun bignum-buffer-ashift-right (bignum bignum-len x)
810   (declare (type bignum-index bignum-len) (fixnum x))
811   (multiple-value-bind (digits n-bits) (truncate x digit-size)
812     (declare (type bignum-index digits))
813     (cond
814      ((zerop n-bits)
815       (let ((new-end (- bignum-len digits)))
816         (bignum-replace bignum bignum :end1 new-end :start2 digits
817                         :end2 bignum-len)
818         (%normalize-bignum-buffer bignum new-end)))
819      (t
820       (shift-right-unaligned bignum digits n-bits (- bignum-len digits)
821                              ((= j res-len-1)
822                               (setf (%bignum-ref bignum j)
823                                     (%ashr (%bignum-ref bignum i) n-bits))
824                               (%normalize-bignum-buffer bignum res-len)))))))
825
826 ;;; This handles shifting a bignum buffer to provide fresh bignum data for some
827 ;;; internal routines. We know bignum is safe when called with bignum-len.
828 ;;; First we compute the number of whole digits to shift, shifting them
829 ;;; starting to store farther along the result bignum. If we shift on a digit
830 ;;; boundary (that is, n-bits is zero), then we just copy digits. The last
831 ;;; branch handles the general case.
832 (defun bignum-ashift-left (bignum x &optional bignum-len)
833   (declare (type bignum-type bignum)
834            (type unsigned-byte x)
835            (type (or null bignum-index) bignum-len))
836   (if (fixnump x)
837     (multiple-value-bind (digits n-bits) (truncate x digit-size)
838       (let* ((bignum-len (or bignum-len (%bignum-length bignum)))
839              (res-len (+ digits bignum-len 1)))
840         (when (> res-len maximum-bignum-length)
841           (error "can't represent result of left shift"))
842         (if (zerop n-bits)
843           (bignum-ashift-left-digits bignum bignum-len digits)
844           (bignum-ashift-left-unaligned bignum digits n-bits res-len))))
845     ;; Left shift by a number too big to be represented as a fixnum
846     ;; would exceed our memory capacity, since a fixnum is big enough
847     ;; to index any array, including a bit array.
848     (error "can't represent result of left shift")))
849
850 (defun bignum-ashift-left-digits (bignum bignum-len digits)
851   (declare (type bignum-index bignum-len digits))
852   (let* ((res-len (+ bignum-len digits))
853          (res (%allocate-bignum res-len)))
854     (declare (type bignum-index res-len))
855     (bignum-replace res bignum :start1 digits :end1 res-len :end2 bignum-len
856                     :from-end t)
857     res))
858
859 ;;; BIGNUM-TRUNCATE uses this to store into a bignum buffer by supplying res.
860 ;;; When res comes in non-nil, then this foregoes allocating a result, and it
861 ;;; normalizes the buffer instead of the would-be allocated result.
862 ;;;
863 ;;; We start storing into one digit higher than digits, storing a whole result
864 ;;; digit from parts of two contiguous digits from bignum. When the loop
865 ;;; finishes, we store the remaining bits from bignum's first digit in the
866 ;;; first non-zero result digit, digits. We also grab some left over high
867 ;;; bits from the last digit of bignum.
868 (defun bignum-ashift-left-unaligned (bignum digits n-bits res-len
869                                      &optional (res nil resp))
870   (declare (type bignum-index digits res-len)
871            (type (mod #.digit-size) n-bits))
872   (let* ((remaining-bits (- digit-size n-bits))
873          (res-len-1 (1- res-len))
874          (res (or res (%allocate-bignum res-len))))
875     (declare (type bignum-index res-len res-len-1))
876     (do ((i 0 i+1)
877          (i+1 1 (1+ i+1))
878          (j (1+ digits) (1+ j)))
879         ((= j res-len-1)
880          (setf (%bignum-ref res digits)
881                (%ashl (%bignum-ref bignum 0) n-bits))
882          (setf (%bignum-ref res j)
883                (%ashr (%bignum-ref bignum i) remaining-bits))
884          (if resp
885              (%normalize-bignum-buffer res res-len)
886              (%normalize-bignum res res-len)))
887       (declare (type bignum-index i i+1 j))
888       (setf (%bignum-ref res j)
889             (%logior (%digit-logical-shift-right (%bignum-ref bignum i)
890                                                  remaining-bits)
891                      (%ashl (%bignum-ref bignum i+1) n-bits))))))
892 \f
893 ;;;; relational operators
894
895 ;;; Return T iff bignum is positive.
896 (defun bignum-plus-p (bignum)
897   (declare (type bignum-type bignum))
898   (%bignum-0-or-plusp bignum (%bignum-length bignum)))
899
900 ;;; This compares two bignums returning -1, 0, or 1, depending on
901 ;;; whether a is less than, equal to, or greater than b.
902 (declaim (ftype (function (bignum bignum) (integer -1 1)) bignum-compare))
903 (defun bignum-compare (a b)
904   (declare (type bignum-type a b))
905   (let* ((len-a (%bignum-length a))
906          (len-b (%bignum-length b))
907          (a-plusp (%bignum-0-or-plusp a len-a))
908          (b-plusp (%bignum-0-or-plusp b len-b)))
909     (declare (type bignum-index len-a len-b))
910     (cond ((not (eq a-plusp b-plusp))
911            (if a-plusp 1 -1))
912           ((= len-a len-b)
913            (do ((i (1- len-a) (1- i)))
914                (())
915              (declare (type bignum-index i))
916              (let ((a-digit (%bignum-ref a i))
917                    (b-digit (%bignum-ref b i)))
918                (declare (type bignum-element-type a-digit b-digit))
919                (when (%digit-greater a-digit b-digit)
920                  (return 1))
921                (when (%digit-greater b-digit a-digit)
922                  (return -1)))
923              (when (zerop i) (return 0))))
924           ((> len-a len-b)
925            (if a-plusp 1 -1))
926           (t (if a-plusp -1 1)))))
927 \f
928 ;;;; float conversion
929
930 ;;; Make a single or double float with the specified significand,
931 ;;; exponent and sign.
932 (defun single-float-from-bits (bits exp plusp)
933   (declare (fixnum exp))
934   (declare (optimize #-sb-xc-host (sb!ext:inhibit-warnings 3)))
935   (let ((res (dpb exp
936                   sb!vm:single-float-exponent-byte
937                   (logandc2 (sb!ext:truly-the (unsigned-byte 31)
938                                               (%bignum-ref bits 1))
939                             sb!vm:single-float-hidden-bit))))
940     (make-single-float
941      (if plusp
942          res
943          (logior res (ash -1 sb!vm:float-sign-shift))))))
944 (defun double-float-from-bits (bits exp plusp)
945   (declare (fixnum exp))
946   (declare (optimize #-sb-xc-host (sb!ext:inhibit-warnings 3)))
947   (let ((hi (dpb exp
948                  sb!vm:double-float-exponent-byte
949                  (logandc2 (sb!ext:truly-the (unsigned-byte 31)
950                                              (%bignum-ref bits 2))
951                            sb!vm:double-float-hidden-bit))))
952     (make-double-float
953      (if plusp
954          hi
955          (logior hi (ash -1 sb!vm:float-sign-shift)))
956      (%bignum-ref bits 1))))
957 #!+(and long-float x86)
958 (defun long-float-from-bits (bits exp plusp)
959   (declare (fixnum exp))
960   (declare (optimize #-sb-xc-host (sb!ext:inhibit-warnings 3)))
961   (make-long-float
962    (if plusp
963        exp
964        (logior exp (ash 1 15)))
965    (%bignum-ref bits 2)
966    (%bignum-ref bits 1)))
967
968 ;;; Convert Bignum to a float in the specified Format, rounding to the best
969 ;;; approximation.
970 (defun bignum-to-float (bignum format)
971   (let* ((plusp (bignum-plus-p bignum))
972          (x (if plusp bignum (negate-bignum bignum)))
973          (len (bignum-integer-length x))
974          (digits (float-format-digits format))
975          (keep (+ digits digit-size))
976          (shift (- keep len))
977          (shifted (if (minusp shift)
978                       (bignum-ashift-right x (- shift))
979                       (bignum-ashift-left x shift)))
980          (low (%bignum-ref shifted 0))
981          (round-bit (ash 1 (1- digit-size))))
982     (declare (type bignum-index len digits keep) (fixnum shift))
983     (labels ((round-up ()
984                (let ((rounded (add-bignums shifted round-bit)))
985                  (if (> (integer-length rounded) keep)
986                      (float-from-bits (bignum-ashift-right rounded 1)
987                                       (1+ len))
988                      (float-from-bits rounded len))))
989              (float-from-bits (bits len)
990                (declare (type bignum-index len))
991                (ecase format
992                  (single-float
993                   (single-float-from-bits
994                    bits
995                    (check-exponent len sb!vm:single-float-bias
996                                    sb!vm:single-float-normal-exponent-max)
997                    plusp))
998                  (double-float
999                   (double-float-from-bits
1000                    bits
1001                    (check-exponent len sb!vm:double-float-bias
1002                                    sb!vm:double-float-normal-exponent-max)
1003                    plusp))
1004                  #!+long-float
1005                  (long-float
1006                   (long-float-from-bits
1007                    bits
1008                    (check-exponent len sb!vm:long-float-bias
1009                                    sb!vm:long-float-normal-exponent-max)
1010                    plusp))))
1011              (check-exponent (exp bias max)
1012                (declare (type bignum-index len))
1013                (let ((exp (+ exp bias)))
1014                  (when (> exp max)
1015                    ;; Why a SIMPLE-TYPE-ERROR? Well, this is mainly
1016                    ;; called by COERCE, which requires an error of
1017                    ;; TYPE-ERROR if the conversion can't happen
1018                    ;; (except in certain circumstances when we are
1019                    ;; coercing to a FUNCTION) -- CSR, 2002-09-18
1020                    (error 'simple-type-error
1021                           :format-control "Too large to be represented as a ~S:~%  ~S"
1022                           :format-arguments (list format x)
1023                           :expected-type format
1024                           :datum x))
1025                  exp)))
1026
1027     (cond
1028      ;; Round down if round bit is 0.
1029      ((zerop (logand round-bit low))
1030       (float-from-bits shifted len))
1031      ;; If only round bit is set, then round to even.
1032      ((and (= low round-bit)
1033            (dotimes (i (- (%bignum-length x) (ceiling keep digit-size))
1034                        t)
1035              (unless (zerop (%bignum-ref x i)) (return nil))))
1036       (let ((next (%bignum-ref shifted 1)))
1037         (if (oddp next)
1038             (round-up)
1039             (float-from-bits shifted len))))
1040      ;; Otherwise, round up.
1041      (t
1042       (round-up))))))
1043 \f
1044 ;;;; integer length and logbitp/logcount
1045
1046 (defun bignum-integer-length (bignum)
1047   (declare (type bignum-type bignum))
1048   (let* ((len (%bignum-length bignum))
1049          (len-1 (1- len))
1050          (digit (%bignum-ref bignum len-1)))
1051     (declare (type bignum-index len len-1)
1052              (type bignum-element-type digit))
1053     (+ (integer-length (%fixnum-digit-with-correct-sign digit))
1054        (* len-1 digit-size))))
1055
1056 (defun bignum-logbitp (index bignum)
1057   (declare (type bignum-type bignum))
1058   (let ((len (%bignum-length bignum)))
1059     (declare (type bignum-index len))
1060     (multiple-value-bind (word-index bit-index)
1061         (floor index digit-size)
1062       (if (>= word-index len)
1063           (not (bignum-plus-p bignum))
1064           (not (zerop (logand (%bignum-ref bignum word-index)
1065                               (ash 1 bit-index))))))))
1066
1067 (defun bignum-logcount (bignum)
1068   (declare (type bignum-type bignum))
1069   (let* ((length (%bignum-length bignum))
1070          (plusp (%bignum-0-or-plusp bignum length))
1071          (result 0))
1072     (declare (type bignum-index length)
1073              (fixnum result))
1074     (do ((index 0 (1+ index)))
1075         ((= index length) result)
1076       (let ((digit (%bignum-ref bignum index)))
1077         (declare (type bignum-element-type digit))
1078         (incf result (logcount (if plusp digit (%lognot digit))))))))
1079 \f
1080 ;;;; logical operations
1081
1082 ;;;; NOT
1083
1084 (defun bignum-logical-not (a)
1085   (declare (type bignum-type a))
1086   (let* ((len (%bignum-length a))
1087          (res (%allocate-bignum len)))
1088     (declare (type bignum-index len))
1089     (dotimes (i len res)
1090       (declare (type bignum-index i))
1091       (setf (%bignum-ref res i) (%lognot (%bignum-ref a i))))))
1092
1093 ;;;; AND
1094
1095 (defun bignum-logical-and (a b)
1096   (declare (type bignum-type a b))
1097   (let* ((len-a (%bignum-length a))
1098          (len-b (%bignum-length b))
1099          (a-plusp (%bignum-0-or-plusp a len-a))
1100          (b-plusp (%bignum-0-or-plusp b len-b)))
1101     (declare (type bignum-index len-a len-b))
1102     (cond
1103      ((< len-a len-b)
1104       (if a-plusp
1105           (logand-shorter-positive a len-a b (%allocate-bignum len-a))
1106           (logand-shorter-negative a len-a b len-b (%allocate-bignum len-b))))
1107      ((< len-b len-a)
1108       (if b-plusp
1109           (logand-shorter-positive b len-b a (%allocate-bignum len-b))
1110           (logand-shorter-negative b len-b a len-a (%allocate-bignum len-a))))
1111      (t (logand-shorter-positive a len-a b (%allocate-bignum len-a))))))
1112
1113 ;;; This takes a shorter bignum, a and len-a, that is positive. Because this
1114 ;;; is AND, we don't care about any bits longer than a's since its infinite 0
1115 ;;; sign bits will mask the other bits out of b. The result is len-a big.
1116 (defun logand-shorter-positive (a len-a b res)
1117   (declare (type bignum-type a b res)
1118            (type bignum-index len-a))
1119   (dotimes (i len-a)
1120     (declare (type bignum-index i))
1121     (setf (%bignum-ref res i)
1122           (%logand (%bignum-ref a i) (%bignum-ref b i))))
1123   (%normalize-bignum res len-a))
1124
1125 ;;; This takes a shorter bignum, a and len-a, that is negative. Because this
1126 ;;; is AND, we just copy any bits longer than a's since its infinite 1 sign
1127 ;;; bits will include any bits from b. The result is len-b big.
1128 (defun logand-shorter-negative (a len-a b len-b res)
1129   (declare (type bignum-type a b res)
1130            (type bignum-index len-a len-b))
1131   (dotimes (i len-a)
1132     (declare (type bignum-index i))
1133     (setf (%bignum-ref res i)
1134           (%logand (%bignum-ref a i) (%bignum-ref b i))))
1135   (do ((i len-a (1+ i)))
1136       ((= i len-b))
1137     (declare (type bignum-index i))
1138     (setf (%bignum-ref res i) (%bignum-ref b i)))
1139   (%normalize-bignum res len-b))
1140
1141 ;;;; IOR
1142
1143 (defun bignum-logical-ior (a b)
1144   (declare (type bignum-type a b))
1145   (let* ((len-a (%bignum-length a))
1146          (len-b (%bignum-length b))
1147          (a-plusp (%bignum-0-or-plusp a len-a))
1148          (b-plusp (%bignum-0-or-plusp b len-b)))
1149     (declare (type bignum-index len-a len-b))
1150     (cond
1151      ((< len-a len-b)
1152       (if a-plusp
1153           (logior-shorter-positive a len-a b len-b (%allocate-bignum len-b))
1154           (logior-shorter-negative a len-a b len-b (%allocate-bignum len-b))))
1155      ((< len-b len-a)
1156       (if b-plusp
1157           (logior-shorter-positive b len-b a len-a (%allocate-bignum len-a))
1158           (logior-shorter-negative b len-b a len-a (%allocate-bignum len-a))))
1159      (t (logior-shorter-positive a len-a b len-b (%allocate-bignum len-a))))))
1160
1161 ;;; This takes a shorter bignum, a and len-a, that is positive. Because this
1162 ;;; is IOR, we don't care about any bits longer than a's since its infinite
1163 ;;; 0 sign bits will mask the other bits out of b out to len-b. The result
1164 ;;; is len-b long.
1165 (defun logior-shorter-positive (a len-a b len-b res)
1166   (declare (type bignum-type a b res)
1167            (type bignum-index len-a len-b))
1168   (dotimes (i len-a)
1169     (declare (type bignum-index i))
1170     (setf (%bignum-ref res i)
1171           (%logior (%bignum-ref a i) (%bignum-ref b i))))
1172   (do ((i len-a (1+ i)))
1173       ((= i len-b))
1174     (declare (type bignum-index i))
1175     (setf (%bignum-ref res i) (%bignum-ref b i)))
1176   (%normalize-bignum res len-b))
1177
1178 ;;; This takes a shorter bignum, a and len-a, that is negative. Because this
1179 ;;; is IOR, we just copy any bits longer than a's since its infinite 1 sign
1180 ;;; bits will include any bits from b. The result is len-b long.
1181 (defun logior-shorter-negative (a len-a b len-b res)
1182   (declare (type bignum-type a b res)
1183            (type bignum-index len-a len-b))
1184   (dotimes (i len-a)
1185     (declare (type bignum-index i))
1186     (setf (%bignum-ref res i)
1187           (%logior (%bignum-ref a i) (%bignum-ref b i))))
1188   (do ((i len-a (1+ i))
1189        (sign (%sign-digit a len-a)))
1190       ((= i len-b))
1191     (declare (type bignum-index i))
1192     (setf (%bignum-ref res i) sign))
1193   (%normalize-bignum res len-b))
1194
1195 ;;;; XOR
1196
1197 (defun bignum-logical-xor (a b)
1198   (declare (type bignum-type a b))
1199   (let ((len-a (%bignum-length a))
1200         (len-b (%bignum-length b)))
1201     (declare (type bignum-index len-a len-b))
1202     (if (< len-a len-b)
1203         (bignum-logical-xor-aux a len-a b len-b (%allocate-bignum len-b))
1204         (bignum-logical-xor-aux b len-b a len-a (%allocate-bignum len-a)))))
1205
1206 ;;; This takes the shorter of two bignums in a and len-a. Res is len-b
1207 ;;; long. Do the XOR.
1208 (defun bignum-logical-xor-aux (a len-a b len-b res)
1209   (declare (type bignum-type a b res)
1210            (type bignum-index len-a len-b))
1211   (dotimes (i len-a)
1212     (declare (type bignum-index i))
1213     (setf (%bignum-ref res i)
1214           (%logxor (%bignum-ref a i) (%bignum-ref b i))))
1215   (do ((i len-a (1+ i))
1216        (sign (%sign-digit a len-a)))
1217       ((= i len-b))
1218     (declare (type bignum-index i))
1219     (setf (%bignum-ref res i) (%logxor sign (%bignum-ref b i))))
1220   (%normalize-bignum res len-b))
1221 \f
1222 ;;;; LDB (load byte)
1223
1224 #|
1225 FOR NOW WE DON'T USE LDB OR DPB. WE USE SHIFTS AND MASKS IN NUMBERS.LISP WHICH
1226 IS LESS EFFICIENT BUT EASIER TO MAINTAIN. BILL SAYS THIS CODE CERTAINLY WORKS!
1227
1228 (defconstant maximum-fixnum-bits #!+ibm-rt-pc 27 #!-ibm-rt-pc 30)
1229
1230 (defun bignum-load-byte (byte bignum)
1231   (declare (type bignum-type bignum))
1232   (let ((byte-len (byte-size byte))
1233         (byte-pos (byte-position byte)))
1234     (if (< byte-len maximum-fixnum-bits)
1235         (bignum-ldb-fixnum-res bignum byte-len byte-pos)
1236         (bignum-ldb-bignum-res bignum byte-len byte-pos))))
1237
1238 ;;; This returns a fixnum result of loading a byte from a bignum. In order, we
1239 ;;; check for the following conditions:
1240 ;;;    Insufficient bignum digits to start loading a byte --
1241 ;;;       Return 0 or byte-len 1's depending on sign of bignum.
1242 ;;;    One bignum digit containing the whole byte spec --
1243 ;;;       Grab 'em, shift 'em, and mask out what we don't want.
1244 ;;;    Insufficient bignum digits to cover crossing a digit boundary --
1245 ;;;       Grab the available bits in the last digit, and or in whatever
1246 ;;;       virtual sign bits we need to return a full byte spec.
1247 ;;;    Else (we cross a digit boundary with all bits available) --
1248 ;;;       Make a couple masks, grab what we want, shift it around, and
1249 ;;;       LOGIOR it all together.
1250 ;;; Because (< maximum-fixnum-bits digit-size) and
1251 ;;;      (< byte-len maximum-fixnum-bits),
1252 ;;; we only cross one digit boundary if any.
1253 (defun bignum-ldb-fixnum-res (bignum byte-len byte-pos)
1254   (multiple-value-bind (skipped-digits pos) (truncate byte-pos digit-size)
1255     (let ((bignum-len (%bignum-length bignum))
1256           (s-digits+1 (1+ skipped-digits)))
1257       (declare (type bignum-index bignum-len s-digits+1))
1258       (if (>= skipped-digits bignum-len)
1259           (if (%bignum-0-or-plusp bignum bignum-len)
1260               0
1261               (%make-ones byte-len))
1262           (let ((end (+ pos byte-len)))
1263             (cond ((<= end digit-size)
1264                    (logand (ash (%bignum-ref bignum skipped-digits) (- pos))
1265                            ;; Must LOGAND after shift here.
1266                            (%make-ones byte-len)))
1267                   ((>= s-digits+1 bignum-len)
1268                    (let* ((available-bits (- digit-size pos))
1269                           (res (logand (ash (%bignum-ref bignum skipped-digits)
1270                                             (- pos))
1271                                        ;; LOGAND should be unnecessary here
1272                                        ;; with a logical right shift or a
1273                                        ;; correct unsigned-byte-32 one.
1274                                        (%make-ones available-bits))))
1275                      (if (%bignum-0-or-plusp bignum bignum-len)
1276                          res
1277                          (logior (%ashl (%make-ones (- end digit-size))
1278                                         available-bits)
1279                                  res))))
1280                   (t
1281                    (let* ((high-bits-in-first-digit (- digit-size pos))
1282                           (high-mask (%make-ones high-bits-in-first-digit))
1283                           (low-bits-in-next-digit (- end digit-size))
1284                           (low-mask (%make-ones low-bits-in-next-digit)))
1285                      (declare (type bignum-element-type high-mask low-mask))
1286                      (logior (%ashl (logand (%bignum-ref bignum s-digits+1)
1287                                             low-mask)
1288                                     high-bits-in-first-digit)
1289                              (logand (ash (%bignum-ref bignum skipped-digits)
1290                                           (- pos))
1291                                      ;; LOGAND should be unnecessary here with
1292                                      ;; a logical right shift or a correct
1293                                      ;; unsigned-byte-32 one.
1294                                      high-mask))))))))))
1295
1296 ;;; This returns a bignum result of loading a byte from a bignum. In order, we
1297 ;;; check for the following conditions:
1298 ;;;    Insufficient bignum digits to start loading a byte --
1299 ;;;    Byte-pos starting on a digit boundary --
1300 ;;;    Byte spec contained in one bignum digit --
1301 ;;;       Grab the bits we want and stick them in a single digit result.
1302 ;;;       Since we know byte-pos is non-zero here, we know our single digit
1303 ;;;       will have a zero high sign bit.
1304 ;;;    Else (unaligned multiple digits) --
1305 ;;;       This is like doing a shift right combined with either masking
1306 ;;;       out unwanted high bits from bignum or filling in virtual sign
1307 ;;;       bits if bignum had insufficient bits. We use SHIFT-RIGHT-ALIGNED
1308 ;;;       and reference lots of local variables this macro establishes.
1309 (defun bignum-ldb-bignum-res (bignum byte-len byte-pos)
1310   (multiple-value-bind (skipped-digits pos) (truncate byte-pos digit-size)
1311     (let ((bignum-len (%bignum-length bignum)))
1312       (declare (type bignum-index bignum-len))
1313       (cond
1314        ((>= skipped-digits bignum-len)
1315         (make-bignum-virtual-ldb-bits bignum bignum-len byte-len))
1316        ((zerop pos)
1317         (make-aligned-ldb-bignum bignum bignum-len byte-len skipped-digits))
1318        ((< (+ pos byte-len) digit-size)
1319         (let ((res (%allocate-bignum 1)))
1320           (setf (%bignum-ref res 0)
1321                 (logand (%ashr (%bignum-ref bignum skipped-digits) pos)
1322                         (%make-ones byte-len)))
1323           res))
1324        (t
1325         (make-unaligned-ldb-bignum bignum bignum-len
1326                                    byte-len skipped-digits pos))))))
1327
1328 ;;; This returns bits from bignum that don't physically exist. These are
1329 ;;; all zero or one depending on the sign of the bignum.
1330 (defun make-bignum-virtual-ldb-bits (bignum bignum-len byte-len)
1331   (if (%bignum-0-or-plusp bignum bignum-len)
1332       0
1333       (multiple-value-bind (res-len-1 extra) (truncate byte-len digit-size)
1334         (declare (type bignum-index res-len-1))
1335         (let* ((res-len (1+ res-len-1))
1336                (res (%allocate-bignum res-len)))
1337           (declare (type bignum-index res-len))
1338           (do ((j 0 (1+ j)))
1339               ((= j res-len-1)
1340                (setf (%bignum-ref res j) (%make-ones extra))
1341                (%normalize-bignum res res-len))
1342             (declare (type bignum-index j))
1343             (setf (%bignum-ref res j) all-ones-digit))))))
1344
1345 ;;; Since we are picking up aligned digits, we just copy the whole digits
1346 ;;; we want and fill in extra bits. We might have a byte-len that extends
1347 ;;; off the end of the bignum, so we may have to fill in extra 1's if the
1348 ;;; bignum is negative.
1349 (defun make-aligned-ldb-bignum (bignum bignum-len byte-len skipped-digits)
1350   (multiple-value-bind (res-len-1 extra) (truncate byte-len digit-size)
1351     (declare (type bignum-index res-len-1))
1352     (let* ((res-len (1+ res-len-1))
1353            (res (%allocate-bignum res-len)))
1354       (declare (type bignum-index res-len))
1355       (do ((i skipped-digits (1+ i))
1356            (j 0 (1+ j)))
1357           ((or (= j res-len-1) (= i bignum-len))
1358            (cond ((< i bignum-len)
1359                   (setf (%bignum-ref res j)
1360                         (logand (%bignum-ref bignum i)
1361                                 (the bignum-element-type (%make-ones extra)))))
1362                  ((%bignum-0-or-plusp bignum bignum-len))
1363                  (t
1364                   (do ((j j (1+ j)))
1365                       ((= j res-len-1)
1366                        (setf (%bignum-ref res j) (%make-ones extra)))
1367                     (setf (%bignum-ref res j) all-ones-digit))))
1368            (%normalize-bignum res res-len))
1369       (declare (type bignum-index i j))
1370       (setf (%bignum-ref res j) (%bignum-ref bignum i))))))
1371
1372 ;;; This grabs unaligned bignum bits from bignum assuming byte-len causes at
1373 ;;; least one digit boundary crossing. We use SHIFT-RIGHT-UNALIGNED referencing
1374 ;;; lots of local variables established by it.
1375 (defun make-unaligned-ldb-bignum (bignum
1376                                   bignum-len
1377                                   byte-len
1378                                   skipped-digits
1379                                   pos)
1380   (multiple-value-bind (res-len-1 extra) (truncate byte-len digit-size)
1381     (shift-right-unaligned
1382      bignum skipped-digits pos (1+ res-len-1)
1383      ((or (= j res-len-1) (= i+1 bignum-len))
1384       (cond ((= j res-len-1)
1385              (cond
1386               ((< extra high-bits-in-first-digit)
1387                (setf (%bignum-ref res j)
1388                      (logand (ash (%bignum-ref bignum i) minus-start-pos)
1389                              ;; Must LOGAND after shift here.
1390                              (%make-ones extra))))
1391               (t
1392                (setf (%bignum-ref res j)
1393                      (logand (ash (%bignum-ref bignum i) minus-start-pos)
1394                              ;; LOGAND should be unnecessary here with a logical
1395                              ;; right shift or a correct unsigned-byte-32 one.
1396                              high-mask))
1397                (when (%bignum-0-or-plusp bignum bignum-len)
1398                  (setf (%bignum-ref res j)
1399                        (logior (%bignum-ref res j)
1400                                (%ashl (%make-ones
1401                                        (- extra high-bits-in-first-digit))
1402                                       high-bits-in-first-digit)))))))
1403             (t
1404              (setf (%bignum-ref res j)
1405                    (logand (ash (%bignum-ref bignum i) minus-start-pos)
1406                            ;; LOGAND should be unnecessary here with a logical
1407                            ;; right shift or a correct unsigned-byte-32 one.
1408                            high-mask))
1409              (unless (%bignum-0-or-plusp bignum bignum-len)
1410                ;; Fill in upper half of this result digit with 1's.
1411                (setf (%bignum-ref res j)
1412                      (logior (%bignum-ref res j)
1413                              (%ashl low-mask high-bits-in-first-digit)))
1414                ;; Fill in any extra 1's we need to be byte-len long.
1415                (do ((j (1+ j) (1+ j)))
1416                    ((>= j res-len-1)
1417                     (setf (%bignum-ref res j) (%make-ones extra)))
1418                  (setf (%bignum-ref res j) all-ones-digit)))))
1419       (%normalize-bignum res res-len))
1420      res)))
1421 \f
1422 ;;;; DPB (deposit byte)
1423
1424 (defun bignum-deposit-byte (new-byte byte-spec bignum)
1425   (declare (type bignum-type bignum))
1426   (let* ((byte-len (byte-size byte-spec))
1427          (byte-pos (byte-position byte-spec))
1428          (bignum-len (%bignum-length bignum))
1429          (bignum-plusp (%bignum-0-or-plusp bignum bignum-len))
1430          (byte-end (+ byte-pos byte-len))
1431          (res-len (1+ (max (ceiling byte-end digit-size) bignum-len)))
1432          (res (%allocate-bignum res-len)))
1433     (declare (type bignum-index bignum-len res-len))
1434     ;; Fill in an extra sign digit in case we set what would otherwise be the
1435     ;; last digit's last bit. Normalize at the end in case this was
1436     ;; unnecessary.
1437     (unless bignum-plusp
1438       (setf (%bignum-ref res (1- res-len)) all-ones-digit))
1439     (multiple-value-bind (end-digit end-bits) (truncate byte-end digit-size)
1440       (declare (type bignum-index end-digit))
1441       ;; Fill in bits from bignum up to byte-pos.
1442       (multiple-value-bind (pos-digit pos-bits) (truncate byte-pos digit-size)
1443         (declare (type bignum-index pos-digit))
1444         (do ((i 0 (1+ i))
1445              (end (min pos-digit bignum-len)))
1446             ((= i end)
1447              (cond ((< i bignum-len)
1448                     (unless (zerop pos-bits)
1449                       (setf (%bignum-ref res i)
1450                             (logand (%bignum-ref bignum i)
1451                                     (%make-ones pos-bits)))))
1452                    (bignum-plusp)
1453                    (t
1454                     (do ((i i (1+ i)))
1455                         ((= i pos-digit)
1456                          (unless (zerop pos-bits)
1457                            (setf (%bignum-ref res i) (%make-ones pos-bits))))
1458                       (setf (%bignum-ref res i) all-ones-digit)))))
1459           (setf (%bignum-ref res i) (%bignum-ref bignum i)))
1460         ;; Fill in bits from new-byte.
1461         (if (typep new-byte 'fixnum)
1462             (deposit-fixnum-bits new-byte byte-len pos-digit pos-bits
1463                                  end-digit end-bits res)
1464             (deposit-bignum-bits new-byte byte-len pos-digit pos-bits
1465                                  end-digit end-bits res)))
1466       ;; Fill in remaining bits from bignum after byte-spec.
1467       (when (< end-digit bignum-len)
1468         (setf (%bignum-ref res end-digit)
1469               (logior (logand (%bignum-ref bignum end-digit)
1470                               (%ashl (%make-ones (- digit-size end-bits))
1471                                      end-bits))
1472                       ;; DEPOSIT-FIXNUM-BITS and DEPOSIT-BIGNUM-BITS only store
1473                       ;; bits from new-byte into res's end-digit element, so
1474                       ;; we don't need to mask out unwanted high bits.
1475                       (%bignum-ref res end-digit)))
1476         (do ((i (1+ end-digit) (1+ i)))
1477             ((= i bignum-len))
1478           (setf (%bignum-ref res i) (%bignum-ref bignum i)))))
1479     (%normalize-bignum res res-len)))
1480
1481 ;;; This starts at result's pos-digit skipping pos-bits, and it stores bits
1482 ;;; from new-byte, a fixnum, into result. It effectively stores byte-len
1483 ;;; number of bits, but never stores past end-digit and end-bits in result.
1484 ;;; The first branch fires when all the bits we want from new-byte are present;
1485 ;;; if byte-len crosses from the current result digit into the next, the last
1486 ;;; argument to DEPOSIT-FIXNUM-DIGIT is a mask for those bits. The second
1487 ;;; branch handles the need to grab more bits than the fixnum new-byte has, but
1488 ;;; new-byte is positive; therefore, any virtual bits are zero. The mask for
1489 ;;; bits that don't fit in the current result digit is simply the remaining
1490 ;;; bits in the bignum digit containing new-byte; we don't care if we store
1491 ;;; some extra in the next result digit since they will be zeros. The last
1492 ;;; branch handles the need to grab more bits than the fixnum new-byte has, but
1493 ;;; new-byte is negative; therefore, any virtual bits must be explicitly filled
1494 ;;; in as ones. We call DEPOSIT-FIXNUM-DIGIT to grab what bits actually exist
1495 ;;; and to fill in the current result digit.
1496 (defun deposit-fixnum-bits (new-byte byte-len pos-digit pos-bits
1497                             end-digit end-bits result)
1498   (declare (type bignum-index pos-digit end-digit))
1499   (let ((other-bits (- digit-size pos-bits))
1500         (new-byte-digit (%fixnum-to-digit new-byte)))
1501     (declare (type bignum-element-type new-byte-digit))
1502     (cond ((< byte-len maximum-fixnum-bits)
1503            (deposit-fixnum-digit new-byte-digit byte-len pos-digit pos-bits
1504                                  other-bits result
1505                                  (- byte-len other-bits)))
1506           ((or (plusp new-byte) (zerop new-byte))
1507            (deposit-fixnum-digit new-byte-digit byte-len pos-digit pos-bits
1508                                  other-bits result pos-bits))
1509           (t
1510            (multiple-value-bind (digit bits)
1511                (deposit-fixnum-digit new-byte-digit byte-len pos-digit pos-bits
1512                                      other-bits result
1513                                      (if (< (- byte-len other-bits) digit-size)
1514                                          (- byte-len other-bits)
1515                                          digit-size))
1516              (declare (type bignum-index digit))
1517              (cond ((< digit end-digit)
1518                     (setf (%bignum-ref result digit)
1519                           (logior (%bignum-ref result digit)
1520                                   (%ashl (%make-ones (- digit-size bits)) bits)))
1521                     (do ((i (1+ digit) (1+ i)))
1522                         ((= i end-digit)
1523                          (setf (%bignum-ref result i) (%make-ones end-bits)))
1524                       (setf (%bignum-ref result i) all-ones-digit)))
1525                    ((> digit end-digit))
1526                    ((< bits end-bits)
1527                     (setf (%bignum-ref result digit)
1528                           (logior (%bignum-ref result digit)
1529                                   (%ashl (%make-ones (- end-bits bits))
1530                                          bits))))))))))
1531
1532 ;;; This fills in the current result digit from new-byte-digit. The first case
1533 ;;; handles everything we want fitting in the current digit, and other-bits is
1534 ;;; the number of bits remaining to be filled in result's current digit. This
1535 ;;; number is digit-size minus pos-bits. The second branch handles filling in
1536 ;;; result's current digit, and it shoves the unused bits of new-byte-digit
1537 ;;; into the next result digit. This is correct regardless of new-byte-digit's
1538 ;;; sign. It returns the new current result digit and how many bits already
1539 ;;; filled in the result digit.
1540 (defun deposit-fixnum-digit (new-byte-digit byte-len pos-digit pos-bits
1541                              other-bits result next-digit-bits-needed)
1542   (declare (type bignum-index pos-digit)
1543            (type bignum-element-type new-byte-digit next-digit-mask))
1544   (cond ((<= byte-len other-bits)
1545          ;; Bits from new-byte fit in the current result digit.
1546          (setf (%bignum-ref result pos-digit)
1547                (logior (%bignum-ref result pos-digit)
1548                        (%ashl (logand new-byte-digit (%make-ones byte-len))
1549                               pos-bits)))
1550          (if (= byte-len other-bits)
1551              (values (1+ pos-digit) 0)
1552              (values pos-digit (+ byte-len pos-bits))))
1553         (t
1554          ;; Some of new-byte's bits go in current result digit.
1555          (setf (%bignum-ref result pos-digit)
1556                (logior (%bignum-ref result pos-digit)
1557                        (%ashl (logand new-byte-digit (%make-ones other-bits))
1558                               pos-bits)))
1559          (let ((pos-digit+1 (1+ pos-digit)))
1560            ;; The rest of new-byte's bits go in the next result digit.
1561            (setf (%bignum-ref result pos-digit+1)
1562                  (logand (ash new-byte-digit (- other-bits))
1563                          ;; Must LOGAND after shift here.
1564                          (%make-ones next-digit-bits-needed)))
1565            (if (= next-digit-bits-needed digit-size)
1566                (values (1+ pos-digit+1) 0)
1567                (values pos-digit+1 next-digit-bits-needed))))))
1568
1569 ;;; This starts at result's pos-digit skipping pos-bits, and it stores bits
1570 ;;; from new-byte, a bignum, into result. It effectively stores byte-len
1571 ;;; number of bits, but never stores past end-digit and end-bits in result.
1572 ;;; When handling a starting bit unaligned with a digit boundary, we check
1573 ;;; in the second branch for the byte spec fitting into the pos-digit element
1574 ;;; after after pos-bits; DEPOSIT-UNALIGNED-BIGNUM-BITS expects at least one
1575 ;;; digit boundary crossing.
1576 (defun deposit-bignum-bits (bignum-byte byte-len pos-digit pos-bits
1577                             end-digit end-bits result)
1578   (declare (type bignum-index pos-digit end-digit))
1579   (cond ((zerop pos-bits)
1580          (deposit-aligned-bignum-bits bignum-byte pos-digit end-digit end-bits
1581                                       result))
1582         ((or (= end-digit pos-digit)
1583              (and (= end-digit (1+ pos-digit))
1584                   (zerop end-bits)))
1585          (setf (%bignum-ref result pos-digit)
1586                (logior (%bignum-ref result pos-digit)
1587                        (%ashl (logand (%bignum-ref bignum-byte 0)
1588                                       (%make-ones byte-len))
1589                               pos-bits))))
1590         (t (deposit-unaligned-bignum-bits bignum-byte pos-digit pos-bits
1591                                           end-digit end-bits result))))
1592
1593 ;;; This deposits bits from bignum-byte into result starting at pos-digit and
1594 ;;; the zero'th bit. It effectively only stores bits to end-bits in the
1595 ;;; end-digit element of result. The loop termination code takes care of
1596 ;;; picking up the last digit's bits or filling in virtual negative sign bits.
1597 (defun deposit-aligned-bignum-bits (bignum-byte pos-digit end-digit end-bits
1598                                     result)
1599   (declare (type bignum-index pos-digit end-digit))
1600   (let* ((bignum-len (%bignum-length bignum-byte))
1601          (bignum-plusp (%bignum-0-or-plusp bignum-byte bignum-len)))
1602     (declare (type bignum-index bignum-len))
1603     (do ((i 0 (1+ i ))
1604          (j pos-digit (1+ j)))
1605         ((or (= j end-digit) (= i bignum-len))
1606          (cond ((= j end-digit)
1607                 (cond ((< i bignum-len)
1608                        (setf (%bignum-ref result j)
1609                              (logand (%bignum-ref bignum-byte i)
1610                                      (%make-ones end-bits))))
1611                       (bignum-plusp)
1612                       (t
1613                        (setf (%bignum-ref result j) (%make-ones end-bits)))))
1614                (bignum-plusp)
1615                (t
1616                 (do ((j j (1+ j)))
1617                     ((= j end-digit)
1618                      (setf (%bignum-ref result j) (%make-ones end-bits)))
1619                   (setf (%bignum-ref result j) all-ones-digit)))))
1620       (setf (%bignum-ref result j) (%bignum-ref bignum-byte i)))))
1621
1622 ;;; This assumes at least one digit crossing.
1623 (defun deposit-unaligned-bignum-bits (bignum-byte pos-digit pos-bits
1624                                       end-digit end-bits result)
1625   (declare (type bignum-index pos-digit end-digit))
1626   (let* ((bignum-len (%bignum-length bignum-byte))
1627          (bignum-plusp (%bignum-0-or-plusp bignum-byte bignum-len))
1628          (low-mask (%make-ones pos-bits))
1629          (bits-past-pos-bits (- digit-size pos-bits))
1630          (high-mask (%make-ones bits-past-pos-bits))
1631          (minus-high-bits (- bits-past-pos-bits)))
1632     (declare (type bignum-element-type low-mask high-mask)
1633              (type bignum-index bignum-len))
1634     (do ((i 0 (1+ i))
1635          (j pos-digit j+1)
1636          (j+1 (1+ pos-digit) (1+ j+1)))
1637         ((or (= j end-digit) (= i bignum-len))
1638          (cond
1639           ((= j end-digit)
1640            (setf (%bignum-ref result j)
1641                  (cond
1642                   ((>= pos-bits end-bits)
1643                    (logand (%bignum-ref result j) (%make-ones end-bits)))
1644                   ((< i bignum-len)
1645                    (logior (%bignum-ref result j)
1646                            (%ashl (logand (%bignum-ref bignum-byte i)
1647                                           (%make-ones (- end-bits pos-bits)))
1648                                   pos-bits)))
1649                   (bignum-plusp
1650                    (logand (%bignum-ref result j)
1651                            ;; 0's between pos-bits and end-bits positions.
1652                            (logior (%ashl (%make-ones (- digit-size end-bits))
1653                                           end-bits)
1654                                    low-mask)))
1655                   (t (logior (%bignum-ref result j)
1656                              (%ashl (%make-ones (- end-bits pos-bits))
1657                                     pos-bits))))))
1658           (bignum-plusp)
1659           (t
1660            (setf (%bignum-ref result j)
1661                  (%ashl (%make-ones bits-past-pos-bits) pos-bits))
1662            (do ((j j+1 (1+ j)))
1663                ((= j end-digit)
1664                 (setf (%bignum-ref result j) (%make-ones end-bits)))
1665              (declare (type bignum-index j))
1666              (setf (%bignum-ref result j) all-ones-digit)))))
1667       (declare (type bignum-index i j j+1))
1668       (let ((digit (%bignum-ref bignum-byte i)))
1669         (declare (type bignum-element-type digit))
1670         (setf (%bignum-ref result j)
1671               (logior (%bignum-ref result j)
1672                       (%ashl (logand digit high-mask) pos-bits)))
1673         (setf (%bignum-ref result j+1)
1674               (logand (ash digit minus-high-bits)
1675                       ;; LOGAND should be unnecessary here with a logical right
1676                       ;; shift or a correct unsigned-byte-32 one.
1677                       low-mask))))))
1678 |#
1679 \f
1680 ;;;; TRUNCATE
1681
1682 ;;; This is the original sketch of the algorithm from which I implemented this
1683 ;;; TRUNCATE, assuming both operands are bignums. I should modify this to work
1684 ;;; with the documentation on my functions, as a general introduction. I've
1685 ;;; left this here just in case someone needs it in the future. Don't look at
1686 ;;; this unless reading the functions' comments leaves you at a loss. Remember
1687 ;;; this comes from Knuth, so the book might give you the right general
1688 ;;; overview.
1689 ;;;
1690 ;;; (truncate x y):
1691 ;;;
1692 ;;; If X's magnitude is less than Y's, then result is 0 with remainder X.
1693 ;;;
1694 ;;; Make x and y positive, copying x if it is already positive.
1695 ;;;
1696 ;;; Shift y left until there's a 1 in the 30'th bit (most significant, non-sign
1697 ;;;       digit)
1698 ;;;    Just do most sig digit to determine how much to shift whole number.
1699 ;;; Shift x this much too.
1700 ;;; Remember this initial shift count.
1701 ;;;
1702 ;;; Allocate q to be len-x minus len-y quantity plus 1.
1703 ;;;
1704 ;;; i = last digit of x.
1705 ;;; k = last digit of q.
1706 ;;;
1707 ;;; LOOP
1708 ;;;
1709 ;;; j = last digit of y.
1710 ;;;
1711 ;;; compute guess.
1712 ;;; if x[i] = y[j] then g = #xFFFFFFFF
1713 ;;; else g = x[i]x[i-1]/y[j].
1714 ;;;
1715 ;;; check guess.
1716 ;;; %UNSIGNED-MULTIPLY returns b and c defined below.
1717 ;;;    a = x[i-1] - (logand (* g y[j]) #xFFFFFFFF).
1718 ;;;       Use %UNSIGNED-MULTIPLY taking low-order result.
1719 ;;;    b = (logand (ash (* g y[j-1]) -32) #xFFFFFFFF).
1720 ;;;    c = (logand (* g y[j-1]) #xFFFFFFFF).
1721 ;;; if a < b, okay.
1722 ;;; if a > b, guess is too high
1723 ;;;    g = g - 1; go back to "check guess".
1724 ;;; if a = b and c > x[i-2], guess is too high
1725 ;;;    g = g - 1; go back to "check guess".
1726 ;;; GUESS IS 32-BIT NUMBER, SO USE THING TO KEEP IN SPECIAL REGISTER
1727 ;;; SAME FOR A, B, AND C.
1728 ;;;
1729 ;;; Subtract g * y from x[i - len-y+1]..x[i]. See paper for doing this in step.
1730 ;;; If x[i] < 0, guess is screwed up.
1731 ;;;    negative g, then add 1
1732 ;;;    zero or positive g, then subtract 1
1733 ;;; AND add y back into x[len-y+1..i].
1734 ;;;
1735 ;;; q[k] = g.
1736 ;;; i = i - 1.
1737 ;;; k = k - 1.
1738 ;;;
1739 ;;; If k>=0, goto LOOP.
1740 ;;;
1741 ;;; Now quotient is good, but remainder is not.
1742 ;;; Shift x right by saved initial left shifting count.
1743 ;;;
1744 ;;; Check quotient and remainder signs.
1745 ;;; x pos y pos --> q pos r pos
1746 ;;; x pos y neg --> q neg r pos
1747 ;;; x neg y pos --> q neg r neg
1748 ;;; x neg y neg --> q pos r neg
1749 ;;;
1750 ;;; Normalize quotient and remainder. Cons result if necessary.
1751
1752 ;;; These are used by BIGNUM-TRUNCATE and friends in the general case.
1753 (defvar *truncate-x*)
1754 (defvar *truncate-y*)
1755
1756 ;;; Divide X by Y returning the quotient and remainder. In the
1757 ;;; general case, we shift Y to set up for the algorithm, and we use
1758 ;;; two buffers to save consing intermediate values. X gets
1759 ;;; destructively modified to become the remainder, and we have to
1760 ;;; shift it to account for the initial Y shift. After we multiple
1761 ;;; bind q and r, we first fix up the signs and then return the
1762 ;;; normalized results.
1763 (defun bignum-truncate (x y)
1764   (declare (type bignum-type x y))
1765   (let* ((x-plusp (%bignum-0-or-plusp x (%bignum-length x)))
1766          (y-plusp (%bignum-0-or-plusp y (%bignum-length y)))
1767          (x (if x-plusp x (negate-bignum x nil)))
1768          (y (if y-plusp y (negate-bignum y nil)))
1769          (len-x (%bignum-length x))
1770          (len-y (%bignum-length y)))
1771     (multiple-value-bind (q r)
1772         (cond ((< len-y 2)
1773                (bignum-truncate-single-digit x len-x y))
1774               ((plusp (bignum-compare y x))
1775                (let ((res (%allocate-bignum len-x)))
1776                  (dotimes (i len-x)
1777                    (setf (%bignum-ref res i) (%bignum-ref x i)))
1778                  (values 0 res)))
1779               (t
1780                (let ((len-x+1 (1+ len-x)))
1781                  (with-bignum-buffers ((*truncate-x* len-x+1)
1782                                        (*truncate-y* (1+ len-y)))
1783                    (let ((y-shift (shift-y-for-truncate y)))
1784                      (shift-and-store-truncate-buffers x len-x y len-y y-shift)
1785                      (values (return-quotient-leaving-remainder len-x+1 len-y)
1786                              ;; Now that RETURN-QUOTIENT-LEAVING-REMAINDER
1787                              ;; has executed, we just tidy up the remainder
1788                              ;; (in *TRUNCATE-X*) and return it.
1789                              (cond
1790                               ((zerop y-shift)
1791                                (let ((res (%allocate-bignum len-y)))
1792                                  (declare (type bignum-type res))
1793                                  (bignum-replace res *truncate-x* :end2 len-y)
1794                                  (%normalize-bignum res len-y)))
1795                               (t
1796                                (shift-right-unaligned
1797                                 *truncate-x* 0 y-shift len-y
1798                                 ((= j res-len-1)
1799                                  (setf (%bignum-ref res j)
1800                                        (%ashr (%bignum-ref *truncate-x* i)
1801                                               y-shift))
1802                                  (%normalize-bignum res res-len))
1803                                 res)))))))))
1804       (let ((quotient (cond ((eq x-plusp y-plusp) q)
1805                             ((typep q 'fixnum) (the fixnum (- q)))
1806                             (t (negate-bignum-in-place q))))
1807             (rem (cond (x-plusp r)
1808                        ((typep r 'fixnum) (the fixnum (- r)))
1809                        (t (negate-bignum-in-place r)))))
1810         (values (if (typep quotient 'fixnum)
1811                     quotient
1812                     (%normalize-bignum quotient (%bignum-length quotient)))
1813                 (if (typep rem 'fixnum)
1814                     rem
1815                     (%normalize-bignum rem (%bignum-length rem))))))))
1816
1817 ;;; Divide X by Y when Y is a single bignum digit. BIGNUM-TRUNCATE
1818 ;;; fixes up the quotient and remainder with respect to sign and
1819 ;;; normalization.
1820 ;;;
1821 ;;; We don't have to worry about shifting Y to make its most
1822 ;;; significant digit sufficiently large for %FLOOR to return 32-bit
1823 ;;; quantities for the q-digit and r-digit. If Y is a single digit
1824 ;;; bignum, it is already large enough for %FLOOR. That is, it has
1825 ;;; some bits on pretty high in the digit.
1826 (defun bignum-truncate-single-digit (x len-x y)
1827   (declare (type bignum-index len-x))
1828   (let ((q (%allocate-bignum len-x))
1829         (r 0)
1830         (y (%bignum-ref y 0)))
1831     (declare (type bignum-element-type r y))
1832     (do ((i (1- len-x) (1- i)))
1833         ((minusp i))
1834       (multiple-value-bind (q-digit r-digit) (%floor r (%bignum-ref x i) y)
1835         (declare (type bignum-element-type q-digit r-digit))
1836         (setf (%bignum-ref q i) q-digit)
1837         (setf r r-digit)))
1838     (let ((rem (%allocate-bignum 1)))
1839       (setf (%bignum-ref rem 0) r)
1840       (values q rem))))
1841
1842 ;;; a helper function for BIGNUM-TRUNCATE
1843 ;;;
1844 ;;; Divide *TRUNCATE-X* by *TRUNCATE-Y*, returning the quotient
1845 ;;; and destructively modifying *TRUNCATE-X* so that it holds
1846 ;;; the remainder.
1847 ;;;
1848 ;;; LEN-X and LEN-Y tell us how much of the buffers we care about.
1849 ;;;
1850 ;;; *TRUNCATE-X* definitely has at least three digits, and it has one
1851 ;;; more than *TRUNCATE-Y*. This keeps i, i-1, i-2, and low-x-digit
1852 ;;; happy. Thanks to SHIFT-AND-STORE-TRUNCATE-BUFFERS.
1853 (defun return-quotient-leaving-remainder (len-x len-y)
1854   (declare (type bignum-index len-x len-y))
1855   (let* ((len-q (- len-x len-y))
1856          ;; Add one for extra sign digit in case high bit is on.
1857          (q (%allocate-bignum (1+ len-q)))
1858          (k (1- len-q))
1859          (y1 (%bignum-ref *truncate-y* (1- len-y)))
1860          (y2 (%bignum-ref *truncate-y* (- len-y 2)))
1861          (i (1- len-x))
1862          (i-1 (1- i))
1863          (i-2 (1- i-1))
1864          (low-x-digit (- i len-y)))
1865     (declare (type bignum-index len-q k i i-1 i-2 low-x-digit)
1866              (type bignum-element-type y1 y2))
1867     (loop
1868       (setf (%bignum-ref q k)
1869             (try-bignum-truncate-guess
1870              ;; This modifies *TRUNCATE-X*. Must access elements each pass.
1871              (bignum-truncate-guess y1 y2
1872                                     (%bignum-ref *truncate-x* i)
1873                                     (%bignum-ref *truncate-x* i-1)
1874                                     (%bignum-ref *truncate-x* i-2))
1875              len-y low-x-digit))
1876       (cond ((zerop k) (return))
1877             (t (decf k)
1878                (decf low-x-digit)
1879                (shiftf i i-1 i-2 (1- i-2)))))
1880     q))
1881
1882 ;;; This takes a digit guess, multiplies it by *TRUNCATE-Y* for a
1883 ;;; result one greater in length than LEN-Y, and subtracts this result
1884 ;;; from *TRUNCATE-X*. LOW-X-DIGIT is the first digit of X to start
1885 ;;; the subtraction, and we know X is long enough to subtract a LEN-Y
1886 ;;; plus one length bignum from it. Next we check the result of the
1887 ;;; subtraction, and if the high digit in X became negative, then our
1888 ;;; guess was one too big. In this case, return one less than GUESS
1889 ;;; passed in, and add one value of Y back into X to account for
1890 ;;; subtracting one too many. Knuth shows that the guess is wrong on
1891 ;;; the order of 3/b, where b is the base (2 to the digit-size power)
1892 ;;; -- pretty rarely.
1893 (defun try-bignum-truncate-guess (guess len-y low-x-digit)
1894   (declare (type bignum-index low-x-digit len-y)
1895            (type bignum-element-type guess))
1896   (let ((carry-digit 0)
1897         (borrow 1)
1898         (i low-x-digit))
1899     (declare (type bignum-element-type carry-digit)
1900              (type bignum-index i)
1901              (fixnum borrow))
1902     ;; Multiply guess and divisor, subtracting from dividend simultaneously.
1903     (dotimes (j len-y)
1904       (multiple-value-bind (high-digit low-digit)
1905           (%multiply-and-add guess
1906                              (%bignum-ref *truncate-y* j)
1907                              carry-digit)
1908         (declare (type bignum-element-type high-digit low-digit))
1909         (setf carry-digit high-digit)
1910         (multiple-value-bind (x temp-borrow)
1911             (%subtract-with-borrow (%bignum-ref *truncate-x* i)
1912                                    low-digit
1913                                    borrow)
1914           (declare (type bignum-element-type x)
1915                    (fixnum temp-borrow))
1916           (setf (%bignum-ref *truncate-x* i) x)
1917           (setf borrow temp-borrow)))
1918       (incf i))
1919     (setf (%bignum-ref *truncate-x* i)
1920           (%subtract-with-borrow (%bignum-ref *truncate-x* i)
1921                                  carry-digit borrow))
1922     ;; See whether guess is off by one, adding one Y back in if necessary.
1923     (cond ((%digit-0-or-plusp (%bignum-ref *truncate-x* i))
1924            guess)
1925           (t
1926            ;; If subtraction has negative result, add one divisor value back
1927            ;; in. The guess was one too large in magnitude.
1928            (let ((i low-x-digit)
1929                  (carry 0))
1930              (dotimes (j len-y)
1931                (multiple-value-bind (v k)
1932                    (%add-with-carry (%bignum-ref *truncate-y* j)
1933                                     (%bignum-ref *truncate-x* i)
1934                                     carry)
1935                  (declare (type bignum-element-type v))
1936                  (setf (%bignum-ref *truncate-x* i) v)
1937                  (setf carry k))
1938                (incf i))
1939              (setf (%bignum-ref *truncate-x* i)
1940                    (%add-with-carry (%bignum-ref *truncate-x* i) 0 carry)))
1941            (%subtract-with-borrow guess 1 1)))))
1942
1943 ;;; This returns a guess for the next division step. Y1 is the highest y
1944 ;;; digit, and y2 is the second to highest y digit. The x... variables are
1945 ;;; the three highest x digits for the next division step.
1946 ;;;
1947 ;;; From Knuth, our guess is either all ones or x-i and x-i-1 divided by y1,
1948 ;;; depending on whether x-i and y1 are the same. We test this guess by
1949 ;;; determining whether guess*y2 is greater than the three high digits of x
1950 ;;; minus guess*y1 shifted left one digit:
1951 ;;;    ------------------------------
1952 ;;;   |    x-i    |   x-i-1  | x-i-2 |
1953 ;;;    ------------------------------
1954 ;;;    ------------------------------
1955 ;;; - | g*y1 high | g*y1 low |   0   |
1956 ;;;    ------------------------------
1957 ;;;             ...               <   guess*y2     ???
1958 ;;; If guess*y2 is greater, then we decrement our guess by one and try again.
1959 ;;; This returns a guess that is either correct or one too large.
1960 (defun bignum-truncate-guess (y1 y2 x-i x-i-1 x-i-2)
1961   (declare (type bignum-element-type y1 y2 x-i x-i-1 x-i-2))
1962   (let ((guess (if (%digit-compare x-i y1)
1963                    all-ones-digit
1964                    (%floor x-i x-i-1 y1))))
1965     (declare (type bignum-element-type guess))
1966     (loop
1967       (multiple-value-bind (high-guess*y1 low-guess*y1) (%multiply guess y1)
1968         (declare (type bignum-element-type low-guess*y1 high-guess*y1))
1969         (multiple-value-bind (high-guess*y2 low-guess*y2)
1970             (%multiply guess y2)
1971           (declare (type bignum-element-type high-guess*y2 low-guess*y2))
1972           (multiple-value-bind (middle-digit borrow)
1973               (%subtract-with-borrow x-i-1 low-guess*y1 1)
1974             (declare (type bignum-element-type middle-digit)
1975                      (fixnum borrow))
1976             ;; Supplying borrow of 1 means there was no borrow, and we know
1977             ;; x-i-2 minus 0 requires no borrow.
1978             (let ((high-digit (%subtract-with-borrow x-i high-guess*y1 borrow)))
1979               (declare (type bignum-element-type high-digit))
1980               (if (and (%digit-compare high-digit 0)
1981                        (or (%digit-greater high-guess*y2 middle-digit)
1982                            (and (%digit-compare middle-digit high-guess*y2)
1983                                 (%digit-greater low-guess*y2 x-i-2))))
1984                   (setf guess (%subtract-with-borrow guess 1 1))
1985                   (return guess)))))))))
1986
1987 ;;; This returns the amount to shift y to place a one in the second highest
1988 ;;; bit. Y must be positive. If the last digit of y is zero, then y has a
1989 ;;; one in the previous digit's sign bit, so we know it will take one less
1990 ;;; than digit-size to get a one where we want. Otherwise, we count how many
1991 ;;; right shifts it takes to get zero; subtracting this value from digit-size
1992 ;;; tells us how many high zeros there are which is one more than the shift
1993 ;;; amount sought.
1994 ;;;
1995 ;;; Note: This is exactly the same as one less than the integer-length of the
1996 ;;; last digit subtracted from the digit-size.
1997 ;;;
1998 ;;; We shift y to make it sufficiently large that doing the 64-bit by 32-bit
1999 ;;; %FLOOR calls ensures the quotient and remainder fit in 32-bits.
2000 (defun shift-y-for-truncate (y)
2001   (let* ((len (%bignum-length y))
2002          (last (%bignum-ref y (1- len))))
2003     (declare (type bignum-index len)
2004              (type bignum-element-type last))
2005     (- digit-size (integer-length last) 1)))
2006
2007 ;;; Stores two bignums into the truncation bignum buffers, shifting them on the
2008 ;;; way in. This assumes x and y are positive and at least two in length, and
2009 ;;; it assumes *truncate-x* and *truncate-y* are one digit longer than x and y.
2010 (defun shift-and-store-truncate-buffers (x len-x y len-y shift)
2011   (declare (type bignum-index len-x len-y)
2012            (type (integer 0 (#.digit-size)) shift))
2013   (cond ((zerop shift)
2014          (bignum-replace *truncate-x* x :end1 len-x)
2015          (bignum-replace *truncate-y* y :end1 len-y))
2016         (t
2017          (bignum-ashift-left-unaligned x 0 shift (1+ len-x) *truncate-x*)
2018          (bignum-ashift-left-unaligned y 0 shift (1+ len-y) *truncate-y*))))
2019 \f
2020 ;;;; %FLOOR primitive for BIGNUM-TRUNCATE
2021
2022 ;;; When a machine leaves out a 64-bit by 32-bit divide instruction (that is,
2023 ;;; two bignum-digits divided by one), we have to roll our own (the hard way).
2024 ;;; Basically, we treat the operation as four 16-bit digits divided by two
2025 ;;; 16-bit digits. This means we have duplicated most of the code above to do
2026 ;;; this nearly general 16-bit digit bignum divide, but we've unrolled loops
2027 ;;; and made use of other properties of this specific divide situation.
2028
2029 ;;;; %FLOOR for machines with a 32x32 divider.
2030
2031 #!-sb-fluid
2032 (declaim (inline 32x16-subtract-with-borrow 32x16-add-with-carry
2033                  32x16-divide 32x16-multiply 32x16-multiply-split))
2034
2035 #!+32x16-divide
2036 (defconstant 32x16-base-1 #xFFFF)
2037
2038 ;;; This is similar to %SUBTRACT-WITH-BORROW. It returns a 16-bit difference
2039 ;;; and a borrow. Returning a 1 for the borrow means there was no borrow, and
2040 ;;; 0 means there was one.
2041 #!+32x16-divide
2042 (defun 32x16-subtract-with-borrow (a b borrow)
2043   (declare (type (unsigned-byte 16) a b)
2044            (type (integer 0 1) borrow))
2045   (let ((diff (+ (- a b) borrow 32x16-base-1)))
2046     (declare (type (unsigned-byte 17) diff))
2047     (values (logand diff #xFFFF)
2048             (ash diff -16))))
2049
2050 ;;; This adds a and b, 16-bit quantities, with the carry k. It returns a
2051 ;;; 16-bit sum and a second value, 0 or 1, indicating whether there was a
2052 ;;; carry.
2053 #!+32x16-divide
2054 (defun 32x16-add-with-carry (a b k)
2055   (declare (type (unsigned-byte 16) a b)
2056            (type (integer 0 1) k))
2057   (let ((res (the fixnum (+ a b k))))
2058     (declare (type (unsigned-byte 17) res))
2059     (if (zerop (the fixnum (logand #x10000 res)))
2060         (values res 0)
2061         (values (the (unsigned-byte 16) (logand #xFFFF res))
2062                 1))))
2063
2064 ;;; This is probably a 32-bit by 32-bit divide instruction.
2065 #!+32x16-divide
2066 (defun 32x16-divide (a b c)
2067   (declare (type (unsigned-byte 16) a b c))
2068   (floor (the bignum-element-type
2069               (logior (the bignum-element-type (ash a 16))
2070                       b))
2071          c))
2072
2073 ;;; This basically exists since we know the answer won't overflow
2074 ;;; bignum-element-type. It's probably just a basic multiply instruction, but
2075 ;;; it can't cons an intermediate bignum. The result goes in a non-descriptor
2076 ;;; register.
2077 #!+32x16-divide
2078 (defun 32x16-multiply (a b)
2079   (declare (type (unsigned-byte 16) a b))
2080   (the bignum-element-type (* a b)))
2081
2082 ;;; This multiplies a and b, 16-bit quantities, and returns the result as two
2083 ;;; 16-bit quantities, high and low.
2084 #!+32x16-divide
2085 (defun 32x16-multiply-split (a b)
2086   (let ((res (32x16-multiply a b)))
2087     (declare (the bignum-element-type res))
2088     (values (the (unsigned-byte 16) (logand #xFFFF (ash res -16)))
2089             (the (unsigned-byte 16) (logand #xFFFF res)))))
2090
2091 ;;; The %FLOOR below uses this buffer the same way BIGNUM-TRUNCATE uses
2092 ;;; *truncate-x*. There's no y buffer since we pass around the two 16-bit
2093 ;;; digits and use them slightly differently than the general truncation
2094 ;;; algorithm above.
2095 #!+32x16-divide
2096 (defvar *32x16-truncate-x* (make-array 4 :element-type '(unsigned-byte 16)
2097                                        :initial-element 0))
2098
2099 ;;; This does the same thing as the %FLOOR above, but it does it at Lisp level
2100 ;;; when there is no 64x32-bit divide instruction on the machine.
2101 ;;;
2102 ;;; It implements the higher level tactics of BIGNUM-TRUNCATE, but it makes use
2103 ;;; of special situation provided, four 16-bit digits divided by two 16-bit
2104 ;;; digits.
2105 #!+32x16-divide
2106 (defun %floor (a b c)
2107   (declare (type bignum-element-type a b c))
2108   ;; Setup *32x16-truncate-x* buffer from a and b.
2109   (setf (aref *32x16-truncate-x* 0)
2110         (the (unsigned-byte 16) (logand #xFFFF b)))
2111   (setf (aref *32x16-truncate-x* 1)
2112         (the (unsigned-byte 16)
2113              (logand #xFFFF
2114                      (the (unsigned-byte 16) (ash b -16)))))
2115   (setf (aref *32x16-truncate-x* 2)
2116         (the (unsigned-byte 16) (logand #xFFFF a)))
2117   (setf (aref *32x16-truncate-x* 3)
2118         (the (unsigned-byte 16)
2119              (logand #xFFFF
2120                      (the (unsigned-byte 16) (ash a -16)))))
2121   ;; From DO-TRUNCATE, but unroll the loop.
2122   (let* ((y1 (logand #xFFFF (ash c -16)))
2123          (y2 (logand #xFFFF c))
2124          (q (the bignum-element-type
2125                  (ash (32x16-try-bignum-truncate-guess
2126                        (32x16-truncate-guess y1 y2
2127                                              (aref *32x16-truncate-x* 3)
2128                                              (aref *32x16-truncate-x* 2)
2129                                              (aref *32x16-truncate-x* 1))
2130                        y1 y2 1)
2131                       16))))
2132     (declare (type bignum-element-type q)
2133              (type (unsigned-byte 16) y1 y2))
2134     (values (the bignum-element-type
2135                  (logior q
2136                          (the (unsigned-byte 16)
2137                               (32x16-try-bignum-truncate-guess
2138                                (32x16-truncate-guess
2139                                 y1 y2
2140                                 (aref *32x16-truncate-x* 2)
2141                                 (aref *32x16-truncate-x* 1)
2142                                 (aref *32x16-truncate-x* 0))
2143                                y1 y2 0))))
2144             (the bignum-element-type
2145                  (logior (the bignum-element-type
2146                               (ash (aref *32x16-truncate-x* 1) 16))
2147                          (the (unsigned-byte 16)
2148                               (aref *32x16-truncate-x* 0)))))))
2149
2150 ;;; This is similar to TRY-BIGNUM-TRUNCATE-GUESS, but this unrolls the two
2151 ;;; loops. This also substitutes for %DIGIT-0-OR-PLUSP the equivalent
2152 ;;; expression without any embellishment or pretense of abstraction. The first
2153 ;;; loop is unrolled, but we've put the body of the loop into the function
2154 ;;; 32X16-TRY-GUESS-ONE-RESULT-DIGIT.
2155 #!+32x16-divide
2156 (defun 32x16-try-bignum-truncate-guess (guess y-high y-low low-x-digit)
2157   (declare (type bignum-index low-x-digit)
2158            (type (unsigned-byte 16) guess y-high y-low))
2159   (let ((high-x-digit (+ 2 low-x-digit)))
2160     ;; Multiply guess and divisor, subtracting from dividend simultaneously.
2161     (multiple-value-bind (guess*y-hold carry borrow)
2162         (32x16-try-guess-one-result-digit guess y-low 0 0 1 low-x-digit)
2163       (declare (type (unsigned-byte 16) guess*y-hold)
2164                (fixnum carry borrow))
2165       (multiple-value-bind (guess*y-hold carry borrow)
2166           (32x16-try-guess-one-result-digit guess y-high guess*y-hold
2167                                             carry borrow (1+ low-x-digit))
2168         (declare (type (unsigned-byte 16) guess*y-hold)
2169                  (fixnum borrow)
2170                  (ignore carry))
2171         (setf (aref *32x16-truncate-x* high-x-digit)
2172               (32x16-subtract-with-borrow (aref *32x16-truncate-x* high-x-digit)
2173                                           guess*y-hold borrow))))
2174     ;; See whether guess is off by one, adding one Y back in if necessary.
2175     (cond ((zerop (logand #x8000 (aref *32x16-truncate-x* high-x-digit)))
2176            ;; The subtraction result is zero or positive.
2177            guess)
2178           (t
2179            ;; If subtraction has negative result, add one divisor value back
2180            ;; in. The guess was one too large in magnitude.
2181            (multiple-value-bind (v carry)
2182                (32x16-add-with-carry y-low
2183                                      (aref *32x16-truncate-x* low-x-digit)
2184                                      0)
2185              (declare (type (unsigned-byte 16) v))
2186              (setf (aref *32x16-truncate-x* low-x-digit) v)
2187              (multiple-value-bind (v carry)
2188                  (32x16-add-with-carry y-high
2189                                        (aref *32x16-truncate-x*
2190                                              (1+ low-x-digit))
2191                                        carry)
2192                (setf (aref *32x16-truncate-x* (1+ low-x-digit)) v)
2193                (setf (aref *32x16-truncate-x* high-x-digit)
2194                      (32x16-add-with-carry (aref *32x16-truncate-x* high-x-digit)
2195                                            carry 0))))
2196            (if (zerop (logand #x8000 guess))
2197                (1- guess)
2198                (1+ guess))))))
2199
2200 ;;; This is similar to the body of the loop in TRY-BIGNUM-TRUNCATE-GUESS that
2201 ;;; multiplies the guess by y and subtracts the result from x simultaneously.
2202 ;;; This returns the digit remembered as part of the multiplication, the carry
2203 ;;; from additions done on behalf of the multiplication, and the borrow from
2204 ;;; doing the subtraction.
2205 #!+32x16-divide
2206 (defun 32x16-try-guess-one-result-digit (guess y-digit guess*y-hold
2207                                          carry borrow x-index)
2208   (multiple-value-bind (high-digit low-digit)
2209       (32x16-multiply-split guess y-digit)
2210     (declare (type (unsigned-byte 16) high-digit low-digit))
2211     (multiple-value-bind (low-digit temp-carry)
2212         (32x16-add-with-carry low-digit guess*y-hold carry)
2213       (declare (type (unsigned-byte 16) low-digit))
2214       (multiple-value-bind (high-digit temp-carry)
2215           (32x16-add-with-carry high-digit temp-carry 0)
2216         (declare (type (unsigned-byte 16) high-digit))
2217         (multiple-value-bind (x temp-borrow)
2218             (32x16-subtract-with-borrow (aref *32x16-truncate-x* x-index)
2219                                         low-digit borrow)
2220           (declare (type (unsigned-byte 16) x))
2221           (setf (aref *32x16-truncate-x* x-index) x)
2222           (values high-digit temp-carry temp-borrow))))))
2223
2224 ;;; This is similar to BIGNUM-TRUNCATE-GUESS, but instead of computing the
2225 ;;; guess exactly as described in the its comments (digit by digit), this
2226 ;;; massages the 16-bit quantities into 32-bit quantities and performs the
2227 #!+32x16-divide
2228 (defun 32x16-truncate-guess (y1 y2 x-i x-i-1 x-i-2)
2229   (declare (type (unsigned-byte 16) y1 y2 x-i x-i-1 x-i-2))
2230   (let ((guess (if (= x-i y1)
2231                    #xFFFF
2232                    (32x16-divide x-i x-i-1 y1))))
2233     (declare (type (unsigned-byte 16) guess))
2234     (loop
2235       (let* ((guess*y1 (the bignum-element-type
2236                             (ash (logand #xFFFF
2237                                          (the bignum-element-type
2238                                               (32x16-multiply guess y1)))
2239                                  16)))
2240              (x-y (%subtract-with-borrow
2241                    (the bignum-element-type
2242                         (logior (the bignum-element-type
2243                                      (ash x-i-1 16))
2244                                 x-i-2))
2245                    guess*y1
2246                    1))
2247              (guess*y2 (the bignum-element-type (%multiply guess y2))))
2248         (declare (type bignum-element-type guess*y1 x-y guess*y2))
2249         (if (%digit-greater guess*y2 x-y)
2250             (decf guess)
2251             (return guess))))))
2252 \f
2253 ;;;; general utilities
2254
2255 ;;; Allocate a single word bignum that holds fixnum. This is useful when
2256 ;;; we are trying to mix fixnum and bignum operands.
2257 #!-sb-fluid (declaim (inline make-small-bignum))
2258 (defun make-small-bignum (fixnum)
2259   (let ((res (%allocate-bignum 1)))
2260     (setf (%bignum-ref res 0) (%fixnum-to-digit fixnum))
2261     res))
2262
2263 ;;; Internal in-place operations use this to fixup remaining digits in the
2264 ;;; incoming data, such as in-place shifting. This is basically the same as
2265 ;;; the first form in %NORMALIZE-BIGNUM, but we return the length of the buffer
2266 ;;; instead of shrinking the bignum.
2267 #!-sb-fluid (declaim (sb!ext:maybe-inline %normalize-bignum-buffer))
2268 (defun %normalize-bignum-buffer (result len)
2269   (declare (type bignum-type result)
2270            (type bignum-index len))
2271   (unless (= len 1)
2272     (do ((next-digit (%bignum-ref result (- len 2))
2273                      (%bignum-ref result (- len 2)))
2274          (sign-digit (%bignum-ref result (1- len)) next-digit))
2275         ((not (zerop (logxor sign-digit (%ashr next-digit (1- digit-size))))))
2276         (decf len)
2277         (setf (%bignum-ref result len) 0)       
2278         (when (= len 1)
2279               (return))))
2280   len)
2281
2282 ;;; This drops the last digit if it is unnecessary sign information. It repeats
2283 ;;; this as needed, possibly ending with a fixnum. If the resulting length from
2284 ;;; shrinking is one, see whether our one word is a fixnum. Shift the possible
2285 ;;; fixnum bits completely out of the word, and compare this with shifting the
2286 ;;; sign bit all the way through. If the bits are all 1's or 0's in both words,
2287 ;;; then there are just sign bits between the fixnum bits and the sign bit. If
2288 ;;; we do have a fixnum, shift it over for the two low-tag bits.
2289 (defun %normalize-bignum (result len)
2290   (declare (type bignum-type result)
2291            (type bignum-index len)
2292            (inline %normalize-bignum-buffer))
2293   (let ((newlen (%normalize-bignum-buffer result len)))
2294     (declare (type bignum-index newlen))
2295     (unless (= newlen len)
2296       (%bignum-set-length result newlen))
2297     (if (= newlen 1)
2298         (let ((digit (%bignum-ref result 0)))
2299           (if (= (%ashr digit 29) (%ashr digit (1- digit-size)))
2300               (%fixnum-digit-with-correct-sign digit)
2301               result))
2302         result)))
2303
2304 ;;; This drops the last digit if it is unnecessary sign information. It
2305 ;;; repeats this as needed, possibly ending with a fixnum magnitude but never
2306 ;;; returning a fixnum.
2307 (defun %mostly-normalize-bignum (result len)
2308   (declare (type bignum-type result)
2309            (type bignum-index len)
2310            (inline %normalize-bignum-buffer))
2311   (let ((newlen (%normalize-bignum-buffer result len)))
2312     (declare (type bignum-index newlen))
2313     (unless (= newlen len)
2314       (%bignum-set-length result newlen))
2315     result))
2316 \f
2317 ;;;; hashing
2318
2319 ;;; the bignum case of the SXHASH function
2320 (defun sxhash-bignum (x)
2321   (let ((result 316495330))
2322     (declare (type fixnum result))
2323     (dotimes (i (%bignum-length x))
2324       (declare (type index i))
2325       (let ((xi (%bignum-ref x i)))
2326         (mixf result
2327               (logand most-positive-fixnum
2328                       xi
2329                       (ash xi -7)))))
2330     result))