• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Parts of the implementation below:
6 
7 // Copyright (c) 2014 the Dart project authors.  Please see the AUTHORS file [1]
8 // for details. All rights reserved. Use of this source code is governed by a
9 // BSD-style license that can be found in the LICENSE file [2].
10 //
11 // [1] https://github.com/dart-lang/sdk/blob/master/AUTHORS
12 // [2] https://github.com/dart-lang/sdk/blob/master/LICENSE
13 
14 // Copyright 2009 The Go Authors. All rights reserved.
15 // Use of this source code is governed by a BSD-style
16 // license that can be found in the LICENSE file [3].
17 //
18 // [3] https://golang.org/LICENSE
19 
20 #include "src/objects/bigint.h"
21 
22 #include "src/double.h"
23 #include "src/objects-inl.h"
24 
25 namespace v8 {
26 namespace internal {
27 
28 // The MutableBigInt class is an implementation detail designed to prevent
29 // accidental mutation of a BigInt after its construction. Step-by-step
30 // construction of a BigInt must happen in terms of MutableBigInt, the
31 // final result is then passed through MutableBigInt::MakeImmutable and not
32 // modified further afterwards.
33 // Many of the functions in this class use arguments of type {BigIntBase},
34 // indicating that they will be used in a read-only capacity, and both
35 // {BigInt} and {MutableBigInt} objects can be passed in.
36 class MutableBigInt : public FreshlyAllocatedBigInt,
37                       public NeverReadOnlySpaceObject {
38  public:
39   using NeverReadOnlySpaceObject::GetHeap;
40   using NeverReadOnlySpaceObject::GetIsolate;
41 
42   // Bottleneck for converting MutableBigInts to BigInts.
43   static MaybeHandle<BigInt> MakeImmutable(MaybeHandle<MutableBigInt> maybe);
44   static Handle<BigInt> MakeImmutable(Handle<MutableBigInt> result);
45 
46   // Allocation helpers.
47   static MaybeHandle<MutableBigInt> New(Isolate* isolate, int length,
48                                         PretenureFlag pretenure = NOT_TENURED);
49   static Handle<BigInt> NewFromInt(Isolate* isolate, int value);
50   static Handle<BigInt> NewFromDouble(Isolate* isolate, double value);
51   void InitializeDigits(int length, byte value = 0);
52   static Handle<MutableBigInt> Copy(Isolate* isolate,
53                                     Handle<BigIntBase> source);
Zero(Isolate * isolate)54   static Handle<BigInt> Zero(Isolate* isolate) {
55     // TODO(jkummerow): Consider caching a canonical zero-BigInt.
56     return MakeImmutable(New(isolate, 0)).ToHandleChecked();
57   }
58 
Cast(Handle<FreshlyAllocatedBigInt> bigint)59   static Handle<MutableBigInt> Cast(Handle<FreshlyAllocatedBigInt> bigint) {
60     SLOW_DCHECK(bigint->IsBigInt());
61     return Handle<MutableBigInt>::cast(bigint);
62   }
63 
64   // Internal helpers.
65   static MaybeHandle<MutableBigInt> BitwiseAnd(Isolate* isolate,
66                                                Handle<BigInt> x,
67                                                Handle<BigInt> y);
68   static MaybeHandle<MutableBigInt> BitwiseXor(Isolate* isolate,
69                                                Handle<BigInt> x,
70                                                Handle<BigInt> y);
71   static MaybeHandle<MutableBigInt> BitwiseOr(Isolate* isolate,
72                                               Handle<BigInt> x,
73                                               Handle<BigInt> y);
74 
75   static Handle<BigInt> TruncateToNBits(Isolate* isolate, int n,
76                                         Handle<BigInt> x);
77   static Handle<BigInt> TruncateAndSubFromPowerOfTwo(Isolate* isolate, int n,
78                                                      Handle<BigInt> x,
79                                                      bool result_sign);
80 
81   static MaybeHandle<BigInt> AbsoluteAdd(Isolate* isolate, Handle<BigInt> x,
82                                          Handle<BigInt> y, bool result_sign);
83   static Handle<BigInt> AbsoluteSub(Isolate* isolate, Handle<BigInt> x,
84                                     Handle<BigInt> y, bool result_sign);
85   static MaybeHandle<MutableBigInt> AbsoluteAddOne(
86       Isolate* isolate, Handle<BigIntBase> x, bool sign,
87       MutableBigInt* result_storage = nullptr);
88   static Handle<MutableBigInt> AbsoluteSubOne(Isolate* isolate,
89                                               Handle<BigIntBase> x);
90   static MaybeHandle<MutableBigInt> AbsoluteSubOne(Isolate* isolate,
91                                                    Handle<BigIntBase> x,
92                                                    int result_length);
93 
94   enum ExtraDigitsHandling { kCopy, kSkip };
95   enum SymmetricOp { kSymmetric, kNotSymmetric };
96   static inline Handle<MutableBigInt> AbsoluteBitwiseOp(
97       Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
98       MutableBigInt* result_storage, ExtraDigitsHandling extra_digits,
99       SymmetricOp symmetric, std::function<digit_t(digit_t, digit_t)> op);
100   static Handle<MutableBigInt> AbsoluteAnd(
101       Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
102       MutableBigInt* result_storage = nullptr);
103   static Handle<MutableBigInt> AbsoluteAndNot(
104       Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
105       MutableBigInt* result_storage = nullptr);
106   static Handle<MutableBigInt> AbsoluteOr(
107       Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
108       MutableBigInt* result_storage = nullptr);
109   static Handle<MutableBigInt> AbsoluteXor(
110       Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
111       MutableBigInt* result_storage = nullptr);
112 
113   static int AbsoluteCompare(Handle<BigIntBase> x, Handle<BigIntBase> y);
114 
115   static void MultiplyAccumulate(Handle<BigIntBase> multiplicand,
116                                  digit_t multiplier,
117                                  Handle<MutableBigInt> accumulator,
118                                  int accumulator_index);
119   static void InternalMultiplyAdd(BigIntBase* source, digit_t factor,
120                                   digit_t summand, int n,
121                                   MutableBigInt* result);
122   void InplaceMultiplyAdd(uintptr_t factor, uintptr_t summand);
123 
124   // Specialized helpers for Divide/Remainder.
125   static void AbsoluteDivSmall(Isolate* isolate, Handle<BigIntBase> x,
126                                digit_t divisor, Handle<MutableBigInt>* quotient,
127                                digit_t* remainder);
128   static bool AbsoluteDivLarge(Isolate* isolate, Handle<BigIntBase> dividend,
129                                Handle<BigIntBase> divisor,
130                                Handle<MutableBigInt>* quotient,
131                                Handle<MutableBigInt>* remainder);
132   static bool ProductGreaterThan(digit_t factor1, digit_t factor2, digit_t high,
133                                  digit_t low);
134   digit_t InplaceAdd(Handle<BigIntBase> summand, int start_index);
135   digit_t InplaceSub(Handle<BigIntBase> subtrahend, int start_index);
136   void InplaceRightShift(int shift);
137   enum SpecialLeftShiftMode {
138     kSameSizeResult,
139     kAlwaysAddOneDigit,
140   };
141   static MaybeHandle<MutableBigInt> SpecialLeftShift(Isolate* isolate,
142                                                      Handle<BigIntBase> x,
143                                                      int shift,
144                                                      SpecialLeftShiftMode mode);
145 
146   // Specialized helpers for shift operations.
147   static MaybeHandle<BigInt> LeftShiftByAbsolute(Isolate* isolate,
148                                                  Handle<BigIntBase> x,
149                                                  Handle<BigIntBase> y);
150   static Handle<BigInt> RightShiftByAbsolute(Isolate* isolate,
151                                              Handle<BigIntBase> x,
152                                              Handle<BigIntBase> y);
153   static Handle<BigInt> RightShiftByMaximum(Isolate* isolate, bool sign);
154   static Maybe<digit_t> ToShiftAmount(Handle<BigIntBase> x);
155 
156   static MaybeHandle<String> ToStringBasePowerOfTwo(Isolate* isolate,
157                                                     Handle<BigIntBase> x,
158                                                     int radix);
159   static MaybeHandle<String> ToStringGeneric(Isolate* isolate,
160                                              Handle<BigIntBase> x, int radix);
161 
162   static double ToDouble(Handle<BigIntBase> x);
163   enum Rounding { kRoundDown, kTie, kRoundUp };
164   static Rounding DecideRounding(Handle<BigIntBase> x, int mantissa_bits_unset,
165                                  int digit_index, uint64_t current_digit);
166 
167   // Returns the least significant 64 bits, simulating two's complement
168   // representation.
169   static uint64_t GetRawBits(BigIntBase* x, bool* lossless);
170 
171   // Digit arithmetic helpers.
172   static inline digit_t digit_add(digit_t a, digit_t b, digit_t* carry);
173   static inline digit_t digit_sub(digit_t a, digit_t b, digit_t* borrow);
174   static inline digit_t digit_mul(digit_t a, digit_t b, digit_t* high);
175   static inline digit_t digit_div(digit_t high, digit_t low, digit_t divisor,
176                                   digit_t* remainder);
177   static digit_t digit_pow(digit_t base, digit_t exponent);
digit_ismax(digit_t x)178   static inline bool digit_ismax(digit_t x) {
179     return static_cast<digit_t>(~x) == 0;
180   }
181 
182 // Internal field setters. Non-mutable BigInts don't have these.
183 #include "src/objects/object-macros.h"
set_sign(bool new_sign)184   inline void set_sign(bool new_sign) {
185     intptr_t bitfield = READ_INTPTR_FIELD(this, kBitfieldOffset);
186     bitfield = SignBits::update(static_cast<uint32_t>(bitfield), new_sign);
187     WRITE_INTPTR_FIELD(this, kBitfieldOffset, bitfield);
188   }
set_length(int new_length)189   inline void set_length(int new_length) {
190     intptr_t bitfield = READ_INTPTR_FIELD(this, kBitfieldOffset);
191     bitfield = LengthBits::update(static_cast<uint32_t>(bitfield), new_length);
192     WRITE_INTPTR_FIELD(this, kBitfieldOffset, bitfield);
193   }
initialize_bitfield(bool sign,int length)194   inline void initialize_bitfield(bool sign, int length) {
195     intptr_t bitfield = LengthBits::encode(length) | SignBits::encode(sign);
196     WRITE_INTPTR_FIELD(this, kBitfieldOffset, bitfield);
197   }
set_digit(int n,digit_t value)198   inline void set_digit(int n, digit_t value) {
199     SLOW_DCHECK(0 <= n && n < length());
200     Address address = FIELD_ADDR(this, kDigitsOffset + n * kDigitSize);
201     (*reinterpret_cast<digit_t*>(address)) = value;
202   }
203 #include "src/objects/object-macros-undef.h"
204 
205   void set_64_bits(uint64_t bits);
206 };
207 
New(Isolate * isolate,int length,PretenureFlag pretenure)208 MaybeHandle<MutableBigInt> MutableBigInt::New(Isolate* isolate, int length,
209                                               PretenureFlag pretenure) {
210   if (length > BigInt::kMaxLength) {
211     THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
212                     MutableBigInt);
213   }
214   Handle<MutableBigInt> result =
215       Cast(isolate->factory()->NewBigInt(length, pretenure));
216   result->initialize_bitfield(false, length);
217 #if DEBUG
218   result->InitializeDigits(length, 0xBF);
219 #endif
220   return result;
221 }
222 
NewFromInt(Isolate * isolate,int value)223 Handle<BigInt> MutableBigInt::NewFromInt(Isolate* isolate, int value) {
224   if (value == 0) return Zero(isolate);
225   Handle<MutableBigInt> result = Cast(isolate->factory()->NewBigInt(1));
226   bool sign = value < 0;
227   result->initialize_bitfield(sign, 1);
228   if (!sign) {
229     result->set_digit(0, value);
230   } else {
231     if (value == kMinInt) {
232       STATIC_ASSERT(kMinInt == -kMaxInt - 1);
233       result->set_digit(0, static_cast<BigInt::digit_t>(kMaxInt) + 1);
234     } else {
235       result->set_digit(0, -value);
236     }
237   }
238   return MakeImmutable(result);
239 }
240 
NewFromDouble(Isolate * isolate,double value)241 Handle<BigInt> MutableBigInt::NewFromDouble(Isolate* isolate, double value) {
242   DCHECK_EQ(value, std::floor(value));
243   if (value == 0) return Zero(isolate);
244 
245   bool sign = value < 0;  // -0 was already handled above.
246   uint64_t double_bits = bit_cast<uint64_t>(value);
247   int raw_exponent =
248       static_cast<int>(double_bits >> Double::kPhysicalSignificandSize) & 0x7FF;
249   DCHECK_NE(raw_exponent, 0x7FF);
250   DCHECK_GE(raw_exponent, 0x3FF);
251   int exponent = raw_exponent - 0x3FF;
252   int digits = exponent / kDigitBits + 1;
253   Handle<MutableBigInt> result = Cast(isolate->factory()->NewBigInt(digits));
254   result->initialize_bitfield(sign, digits);
255 
256   // We construct a BigInt from the double {value} by shifting its mantissa
257   // according to its exponent and mapping the bit pattern onto digits.
258   //
259   //               <----------- bitlength = exponent + 1 ----------->
260   //                <----- 52 ------> <------ trailing zeroes ------>
261   // mantissa:     1yyyyyyyyyyyyyyyyy 0000000000000000000000000000000
262   // digits:    0001xxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
263   //                <-->          <------>
264   //          msd_topbit         kDigitBits
265   //
266   uint64_t mantissa =
267       (double_bits & Double::kSignificandMask) | Double::kHiddenBit;
268   const int kMantissaTopBit = Double::kSignificandSize - 1;  // 0-indexed.
269   // 0-indexed position of most significant bit in the most significant digit.
270   int msd_topbit = exponent % kDigitBits;
271   // Number of unused bits in {mantissa}. We'll keep them shifted to the
272   // left (i.e. most significant part) of the underlying uint64_t.
273   int remaining_mantissa_bits = 0;
274   // Next digit under construction.
275   digit_t digit;
276 
277   // First, build the MSD by shifting the mantissa appropriately.
278   if (msd_topbit < kMantissaTopBit) {
279     remaining_mantissa_bits = kMantissaTopBit - msd_topbit;
280     digit = mantissa >> remaining_mantissa_bits;
281     mantissa = mantissa << (64 - remaining_mantissa_bits);
282   } else {
283     DCHECK_GE(msd_topbit, kMantissaTopBit);
284     digit = mantissa << (msd_topbit - kMantissaTopBit);
285     mantissa = 0;
286   }
287   result->set_digit(digits - 1, digit);
288   // Then fill in the rest of the digits.
289   for (int digit_index = digits - 2; digit_index >= 0; digit_index--) {
290     if (remaining_mantissa_bits > 0) {
291       remaining_mantissa_bits -= kDigitBits;
292       if (sizeof(digit) == 4) {
293         digit = mantissa >> 32;
294         mantissa = mantissa << 32;
295       } else {
296         DCHECK_EQ(sizeof(digit), 8);
297         digit = mantissa;
298         mantissa = 0;
299       }
300     } else {
301       digit = 0;
302     }
303     result->set_digit(digit_index, digit);
304   }
305   return MakeImmutable(result);
306 }
307 
Copy(Isolate * isolate,Handle<BigIntBase> source)308 Handle<MutableBigInt> MutableBigInt::Copy(Isolate* isolate,
309                                           Handle<BigIntBase> source) {
310   int length = source->length();
311   // Allocating a BigInt of the same length as an existing BigInt cannot throw.
312   Handle<MutableBigInt> result = New(isolate, length).ToHandleChecked();
313   memcpy(reinterpret_cast<void*>(result->address() + BigIntBase::kHeaderSize),
314          reinterpret_cast<void*>(source->address() + BigIntBase::kHeaderSize),
315          BigInt::SizeFor(length) - BigIntBase::kHeaderSize);
316   return result;
317 }
318 
InitializeDigits(int length,byte value)319 void MutableBigInt::InitializeDigits(int length, byte value) {
320   memset(reinterpret_cast<void*>(reinterpret_cast<Address>(this) +
321                                  kDigitsOffset - kHeapObjectTag),
322          value, length * kDigitSize);
323 }
324 
MakeImmutable(MaybeHandle<MutableBigInt> maybe)325 MaybeHandle<BigInt> MutableBigInt::MakeImmutable(
326     MaybeHandle<MutableBigInt> maybe) {
327   Handle<MutableBigInt> result;
328   if (!maybe.ToHandle(&result)) return MaybeHandle<BigInt>();
329   return MakeImmutable(result);
330 }
331 
MakeImmutable(Handle<MutableBigInt> result)332 Handle<BigInt> MutableBigInt::MakeImmutable(Handle<MutableBigInt> result) {
333   // Check if we need to right-trim any leading zero-digits.
334   int old_length = result->length();
335   int new_length = old_length;
336   while (new_length > 0 && result->digit(new_length - 1) == 0) new_length--;
337   int to_trim = old_length - new_length;
338   if (to_trim != 0) {
339     int size_delta = to_trim * kDigitSize;
340     Address new_end = result->address() + BigInt::SizeFor(new_length);
341     Heap* heap = result->GetHeap();
342     heap->CreateFillerObjectAt(new_end, size_delta, ClearRecordedSlots::kNo);
343     result->set_length(new_length);
344 
345     // Canonicalize -0n.
346     if (new_length == 0) {
347       result->set_sign(false);
348       // TODO(jkummerow): If we cache a canonical 0n, return that here.
349     }
350   }
351   DCHECK_IMPLIES(result->length() > 0,
352                  result->digit(result->length() - 1) != 0);  // MSD is non-zero.
353   return Handle<BigInt>(reinterpret_cast<BigInt**>(result.location()));
354 }
355 
Zero(Isolate * isolate)356 Handle<BigInt> BigInt::Zero(Isolate* isolate) {
357   return MutableBigInt::Zero(isolate);
358 }
359 
UnaryMinus(Isolate * isolate,Handle<BigInt> x)360 Handle<BigInt> BigInt::UnaryMinus(Isolate* isolate, Handle<BigInt> x) {
361   // Special case: There is no -0n.
362   if (x->is_zero()) {
363     return x;
364   }
365   Handle<MutableBigInt> result = MutableBigInt::Copy(isolate, x);
366   result->set_sign(!x->sign());
367   return MutableBigInt::MakeImmutable(result);
368 }
369 
BitwiseNot(Isolate * isolate,Handle<BigInt> x)370 MaybeHandle<BigInt> BigInt::BitwiseNot(Isolate* isolate, Handle<BigInt> x) {
371   MaybeHandle<MutableBigInt> result;
372   if (x->sign()) {
373     // ~(-x) == ~(~(x-1)) == x-1
374     result = MutableBigInt::AbsoluteSubOne(isolate, x, x->length());
375   } else {
376     // ~x == -x-1 == -(x+1)
377     result = MutableBigInt::AbsoluteAddOne(isolate, x, true);
378   }
379   return MutableBigInt::MakeImmutable(result);
380 }
381 
Exponentiate(Isolate * isolate,Handle<BigInt> base,Handle<BigInt> exponent)382 MaybeHandle<BigInt> BigInt::Exponentiate(Isolate* isolate, Handle<BigInt> base,
383                                          Handle<BigInt> exponent) {
384   // 1. If exponent is < 0, throw a RangeError exception.
385   if (exponent->sign()) {
386     THROW_NEW_ERROR(isolate,
387                     NewRangeError(MessageTemplate::kBigIntNegativeExponent),
388                     BigInt);
389   }
390   // 2. If base is 0n and exponent is 0n, return 1n.
391   if (exponent->is_zero()) {
392     return MutableBigInt::NewFromInt(isolate, 1);
393   }
394   // 3. Return a BigInt representing the mathematical value of base raised
395   //    to the power exponent.
396   if (base->is_zero()) return base;
397   if (base->length() == 1 && base->digit(0) == 1) {
398     // (-1) ** even_number == 1.
399     if (base->sign() && (exponent->digit(0) & 1) == 0) {
400       return UnaryMinus(isolate, base);
401     }
402     // (-1) ** odd_number == -1; 1 ** anything == 1.
403     return base;
404   }
405   // For all bases >= 2, very large exponents would lead to unrepresentable
406   // results.
407   STATIC_ASSERT(kMaxLengthBits < std::numeric_limits<digit_t>::max());
408   if (exponent->length() > 1) {
409     THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
410                     BigInt);
411   }
412   digit_t exp_value = exponent->digit(0);
413   if (exp_value == 1) return base;
414   if (exp_value >= kMaxLengthBits) {
415     THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
416                     BigInt);
417   }
418   STATIC_ASSERT(kMaxLengthBits <= kMaxInt);
419   int n = static_cast<int>(exp_value);
420   if (base->length() == 1 && base->digit(0) == 2) {
421     // Fast path for 2^n.
422     int needed_digits = 1 + (n / kDigitBits);
423     Handle<MutableBigInt> result;
424     if (!MutableBigInt::New(isolate, needed_digits).ToHandle(&result)) {
425       return MaybeHandle<BigInt>();
426     }
427     result->InitializeDigits(needed_digits);
428     // All bits are zero. Now set the n-th bit.
429     digit_t msd = static_cast<digit_t>(1) << (n % kDigitBits);
430     result->set_digit(needed_digits - 1, msd);
431     // Result is negative for odd powers of -2n.
432     if (base->sign()) result->set_sign((n & 1) != 0);
433     return MutableBigInt::MakeImmutable(result);
434   }
435   Handle<BigInt> result;
436   Handle<BigInt> running_square = base;
437   // This implicitly sets the result's sign correctly.
438   if (n & 1) result = base;
439   n >>= 1;
440   for (; n != 0; n >>= 1) {
441     MaybeHandle<BigInt> maybe_result =
442         Multiply(isolate, running_square, running_square);
443     if (!maybe_result.ToHandle(&running_square)) return maybe_result;
444     if (n & 1) {
445       if (result.is_null()) {
446         result = running_square;
447       } else {
448         maybe_result = Multiply(isolate, result, running_square);
449         if (!maybe_result.ToHandle(&result)) return maybe_result;
450       }
451     }
452   }
453   return result;
454 }
455 
Multiply(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)456 MaybeHandle<BigInt> BigInt::Multiply(Isolate* isolate, Handle<BigInt> x,
457                                      Handle<BigInt> y) {
458   if (x->is_zero()) return x;
459   if (y->is_zero()) return y;
460   int result_length = x->length() + y->length();
461   Handle<MutableBigInt> result;
462   if (!MutableBigInt::New(isolate, result_length).ToHandle(&result)) {
463     return MaybeHandle<BigInt>();
464   }
465   result->InitializeDigits(result_length);
466   for (int i = 0; i < x->length(); i++) {
467     MutableBigInt::MultiplyAccumulate(y, x->digit(i), result, i);
468   }
469   result->set_sign(x->sign() != y->sign());
470   return MutableBigInt::MakeImmutable(result);
471 }
472 
Divide(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)473 MaybeHandle<BigInt> BigInt::Divide(Isolate* isolate, Handle<BigInt> x,
474                                    Handle<BigInt> y) {
475   // 1. If y is 0n, throw a RangeError exception.
476   if (y->is_zero()) {
477     THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntDivZero),
478                     BigInt);
479   }
480   // 2. Let quotient be the mathematical value of x divided by y.
481   // 3. Return a BigInt representing quotient rounded towards 0 to the next
482   //    integral value.
483   if (MutableBigInt::AbsoluteCompare(x, y) < 0) {
484     return Zero(isolate);
485   }
486   Handle<MutableBigInt> quotient;
487   bool result_sign = x->sign() != y->sign();
488   if (y->length() == 1) {
489     digit_t divisor = y->digit(0);
490     if (divisor == 1) {
491       return result_sign == x->sign() ? x : UnaryMinus(isolate, x);
492     }
493     digit_t remainder;
494     MutableBigInt::AbsoluteDivSmall(isolate, x, divisor, &quotient, &remainder);
495   } else {
496     if (!MutableBigInt::AbsoluteDivLarge(isolate, x, y, &quotient, nullptr)) {
497       return MaybeHandle<BigInt>();
498     }
499   }
500   quotient->set_sign(x->sign() != y->sign());
501   return MutableBigInt::MakeImmutable(quotient);
502 }
503 
Remainder(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)504 MaybeHandle<BigInt> BigInt::Remainder(Isolate* isolate, Handle<BigInt> x,
505                                       Handle<BigInt> y) {
506   // 1. If y is 0n, throw a RangeError exception.
507   if (y->is_zero()) {
508     THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntDivZero),
509                     BigInt);
510   }
511   // 2. Return the BigInt representing x modulo y.
512   // See https://github.com/tc39/proposal-bigint/issues/84 though.
513   if (MutableBigInt::AbsoluteCompare(x, y) < 0) return x;
514   Handle<MutableBigInt> remainder;
515   if (y->length() == 1) {
516     digit_t divisor = y->digit(0);
517     if (divisor == 1) return Zero(isolate);
518     digit_t remainder_digit;
519     MutableBigInt::AbsoluteDivSmall(isolate, x, divisor, nullptr,
520                                     &remainder_digit);
521     if (remainder_digit == 0) {
522       return Zero(isolate);
523     }
524     remainder = MutableBigInt::New(isolate, 1).ToHandleChecked();
525     remainder->set_digit(0, remainder_digit);
526   } else {
527     if (!MutableBigInt::AbsoluteDivLarge(isolate, x, y, nullptr, &remainder)) {
528       return MaybeHandle<BigInt>();
529     }
530   }
531   remainder->set_sign(x->sign());
532   return MutableBigInt::MakeImmutable(remainder);
533 }
534 
Add(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)535 MaybeHandle<BigInt> BigInt::Add(Isolate* isolate, Handle<BigInt> x,
536                                 Handle<BigInt> y) {
537   bool xsign = x->sign();
538   if (xsign == y->sign()) {
539     // x + y == x + y
540     // -x + -y == -(x + y)
541     return MutableBigInt::AbsoluteAdd(isolate, x, y, xsign);
542   }
543   // x + -y == x - y == -(y - x)
544   // -x + y == y - x == -(x - y)
545   if (MutableBigInt::AbsoluteCompare(x, y) >= 0) {
546     return MutableBigInt::AbsoluteSub(isolate, x, y, xsign);
547   }
548   return MutableBigInt::AbsoluteSub(isolate, y, x, !xsign);
549 }
550 
Subtract(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)551 MaybeHandle<BigInt> BigInt::Subtract(Isolate* isolate, Handle<BigInt> x,
552                                      Handle<BigInt> y) {
553   bool xsign = x->sign();
554   if (xsign != y->sign()) {
555     // x - (-y) == x + y
556     // (-x) - y == -(x + y)
557     return MutableBigInt::AbsoluteAdd(isolate, x, y, xsign);
558   }
559   // x - y == -(y - x)
560   // (-x) - (-y) == y - x == -(x - y)
561   if (MutableBigInt::AbsoluteCompare(x, y) >= 0) {
562     return MutableBigInt::AbsoluteSub(isolate, x, y, xsign);
563   }
564   return MutableBigInt::AbsoluteSub(isolate, y, x, !xsign);
565 }
566 
LeftShift(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)567 MaybeHandle<BigInt> BigInt::LeftShift(Isolate* isolate, Handle<BigInt> x,
568                                       Handle<BigInt> y) {
569   if (y->is_zero() || x->is_zero()) return x;
570   if (y->sign()) return MutableBigInt::RightShiftByAbsolute(isolate, x, y);
571   return MutableBigInt::LeftShiftByAbsolute(isolate, x, y);
572 }
573 
SignedRightShift(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)574 MaybeHandle<BigInt> BigInt::SignedRightShift(Isolate* isolate, Handle<BigInt> x,
575                                              Handle<BigInt> y) {
576   if (y->is_zero() || x->is_zero()) return x;
577   if (y->sign()) return MutableBigInt::LeftShiftByAbsolute(isolate, x, y);
578   return MutableBigInt::RightShiftByAbsolute(isolate, x, y);
579 }
580 
UnsignedRightShift(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)581 MaybeHandle<BigInt> BigInt::UnsignedRightShift(Isolate* isolate,
582                                                Handle<BigInt> x,
583                                                Handle<BigInt> y) {
584   THROW_NEW_ERROR(isolate, NewTypeError(MessageTemplate::kBigIntShr), BigInt);
585 }
586 
587 namespace {
588 
589 // Produces comparison result for {left_negative} == sign(x) != sign(y).
UnequalSign(bool left_negative)590 ComparisonResult UnequalSign(bool left_negative) {
591   return left_negative ? ComparisonResult::kLessThan
592                        : ComparisonResult::kGreaterThan;
593 }
594 
595 // Produces result for |x| > |y|, with {both_negative} == sign(x) == sign(y);
AbsoluteGreater(bool both_negative)596 ComparisonResult AbsoluteGreater(bool both_negative) {
597   return both_negative ? ComparisonResult::kLessThan
598                        : ComparisonResult::kGreaterThan;
599 }
600 
601 // Produces result for |x| < |y|, with {both_negative} == sign(x) == sign(y).
AbsoluteLess(bool both_negative)602 ComparisonResult AbsoluteLess(bool both_negative) {
603   return both_negative ? ComparisonResult::kGreaterThan
604                        : ComparisonResult::kLessThan;
605 }
606 
607 }  // namespace
608 
609 // (Never returns kUndefined.)
CompareToBigInt(Handle<BigInt> x,Handle<BigInt> y)610 ComparisonResult BigInt::CompareToBigInt(Handle<BigInt> x, Handle<BigInt> y) {
611   bool x_sign = x->sign();
612   if (x_sign != y->sign()) return UnequalSign(x_sign);
613 
614   int result = MutableBigInt::AbsoluteCompare(x, y);
615   if (result > 0) return AbsoluteGreater(x_sign);
616   if (result < 0) return AbsoluteLess(x_sign);
617   return ComparisonResult::kEqual;
618 }
619 
EqualToBigInt(BigInt * x,BigInt * y)620 bool BigInt::EqualToBigInt(BigInt* x, BigInt* y) {
621   if (x->sign() != y->sign()) return false;
622   if (x->length() != y->length()) return false;
623   for (int i = 0; i < x->length(); i++) {
624     if (x->digit(i) != y->digit(i)) return false;
625   }
626   return true;
627 }
628 
BitwiseAnd(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)629 MaybeHandle<BigInt> BigInt::BitwiseAnd(Isolate* isolate, Handle<BigInt> x,
630                                        Handle<BigInt> y) {
631   return MutableBigInt::MakeImmutable(MutableBigInt::BitwiseAnd(isolate, x, y));
632 }
633 
BitwiseAnd(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)634 MaybeHandle<MutableBigInt> MutableBigInt::BitwiseAnd(Isolate* isolate,
635                                                      Handle<BigInt> x,
636                                                      Handle<BigInt> y) {
637   if (!x->sign() && !y->sign()) {
638     return AbsoluteAnd(isolate, x, y);
639   } else if (x->sign() && y->sign()) {
640     int result_length = Max(x->length(), y->length()) + 1;
641     // (-x) & (-y) == ~(x-1) & ~(y-1) == ~((x-1) | (y-1))
642     // == -(((x-1) | (y-1)) + 1)
643     Handle<MutableBigInt> result;
644     if (!AbsoluteSubOne(isolate, x, result_length).ToHandle(&result)) {
645       return MaybeHandle<MutableBigInt>();
646     }
647     Handle<MutableBigInt> y_1 = AbsoluteSubOne(isolate, y);
648     result = AbsoluteOr(isolate, result, y_1, *result);
649     return AbsoluteAddOne(isolate, result, true, *result);
650   } else {
651     DCHECK(x->sign() != y->sign());
652     // Assume that x is the positive BigInt.
653     if (x->sign()) std::swap(x, y);
654     // x & (-y) == x & ~(y-1) == x &~ (y-1)
655     return AbsoluteAndNot(isolate, x, AbsoluteSubOne(isolate, y));
656   }
657 }
658 
BitwiseXor(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)659 MaybeHandle<BigInt> BigInt::BitwiseXor(Isolate* isolate, Handle<BigInt> x,
660                                        Handle<BigInt> y) {
661   return MutableBigInt::MakeImmutable(MutableBigInt::BitwiseXor(isolate, x, y));
662 }
663 
BitwiseXor(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)664 MaybeHandle<MutableBigInt> MutableBigInt::BitwiseXor(Isolate* isolate,
665                                                      Handle<BigInt> x,
666                                                      Handle<BigInt> y) {
667   if (!x->sign() && !y->sign()) {
668     return AbsoluteXor(isolate, x, y);
669   } else if (x->sign() && y->sign()) {
670     int result_length = Max(x->length(), y->length());
671     // (-x) ^ (-y) == ~(x-1) ^ ~(y-1) == (x-1) ^ (y-1)
672     Handle<MutableBigInt> result =
673         AbsoluteSubOne(isolate, x, result_length).ToHandleChecked();
674     Handle<MutableBigInt> y_1 = AbsoluteSubOne(isolate, y);
675     return AbsoluteXor(isolate, result, y_1, *result);
676   } else {
677     DCHECK(x->sign() != y->sign());
678     int result_length = Max(x->length(), y->length()) + 1;
679     // Assume that x is the positive BigInt.
680     if (x->sign()) std::swap(x, y);
681     // x ^ (-y) == x ^ ~(y-1) == ~(x ^ (y-1)) == -((x ^ (y-1)) + 1)
682     Handle<MutableBigInt> result;
683     if (!AbsoluteSubOne(isolate, y, result_length).ToHandle(&result)) {
684       return MaybeHandle<MutableBigInt>();
685     }
686     result = AbsoluteXor(isolate, result, x, *result);
687     return AbsoluteAddOne(isolate, result, true, *result);
688   }
689 }
690 
BitwiseOr(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)691 MaybeHandle<BigInt> BigInt::BitwiseOr(Isolate* isolate, Handle<BigInt> x,
692                                       Handle<BigInt> y) {
693   return MutableBigInt::MakeImmutable(MutableBigInt::BitwiseOr(isolate, x, y));
694 }
695 
BitwiseOr(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y)696 MaybeHandle<MutableBigInt> MutableBigInt::BitwiseOr(Isolate* isolate,
697                                                     Handle<BigInt> x,
698                                                     Handle<BigInt> y) {
699   int result_length = Max(x->length(), y->length());
700   if (!x->sign() && !y->sign()) {
701     return AbsoluteOr(isolate, x, y);
702   } else if (x->sign() && y->sign()) {
703     // (-x) | (-y) == ~(x-1) | ~(y-1) == ~((x-1) & (y-1))
704     // == -(((x-1) & (y-1)) + 1)
705     Handle<MutableBigInt> result =
706         AbsoluteSubOne(isolate, x, result_length).ToHandleChecked();
707     Handle<MutableBigInt> y_1 = AbsoluteSubOne(isolate, y);
708     result = AbsoluteAnd(isolate, result, y_1, *result);
709     return AbsoluteAddOne(isolate, result, true, *result);
710   } else {
711     DCHECK(x->sign() != y->sign());
712     // Assume that x is the positive BigInt.
713     if (x->sign()) std::swap(x, y);
714     // x | (-y) == x | ~(y-1) == ~((y-1) &~ x) == -(((y-1) &~ x) + 1)
715     Handle<MutableBigInt> result =
716         AbsoluteSubOne(isolate, y, result_length).ToHandleChecked();
717     result = AbsoluteAndNot(isolate, result, x, *result);
718     return AbsoluteAddOne(isolate, result, true, *result);
719   }
720 }
721 
Increment(Isolate * isolate,Handle<BigInt> x)722 MaybeHandle<BigInt> BigInt::Increment(Isolate* isolate, Handle<BigInt> x) {
723   if (x->sign()) {
724     Handle<MutableBigInt> result = MutableBigInt::AbsoluteSubOne(isolate, x);
725     result->set_sign(true);
726     return MutableBigInt::MakeImmutable(result);
727   } else {
728     return MutableBigInt::MakeImmutable(
729         MutableBigInt::AbsoluteAddOne(isolate, x, false));
730   }
731 }
732 
Decrement(Isolate * isolate,Handle<BigInt> x)733 MaybeHandle<BigInt> BigInt::Decrement(Isolate* isolate, Handle<BigInt> x) {
734   MaybeHandle<MutableBigInt> result;
735   if (x->sign()) {
736     result = MutableBigInt::AbsoluteAddOne(isolate, x, true);
737   } else if (x->is_zero()) {
738     // TODO(jkummerow): Consider caching a canonical -1n BigInt.
739     return MutableBigInt::NewFromInt(isolate, -1);
740   } else {
741     result = MutableBigInt::AbsoluteSubOne(isolate, x);
742   }
743   return MutableBigInt::MakeImmutable(result);
744 }
745 
CompareToString(Isolate * isolate,Handle<BigInt> x,Handle<String> y)746 ComparisonResult BigInt::CompareToString(Isolate* isolate, Handle<BigInt> x,
747                                          Handle<String> y) {
748   // a. Let ny be StringToBigInt(y);
749   MaybeHandle<BigInt> maybe_ny = StringToBigInt(isolate, y);
750   // b. If ny is NaN, return undefined.
751   Handle<BigInt> ny;
752   if (!maybe_ny.ToHandle(&ny)) {
753     DCHECK(!isolate->has_pending_exception());
754     return ComparisonResult::kUndefined;
755   }
756   // c. Return BigInt::lessThan(x, ny).
757   return CompareToBigInt(x, ny);
758 }
759 
EqualToString(Isolate * isolate,Handle<BigInt> x,Handle<String> y)760 bool BigInt::EqualToString(Isolate* isolate, Handle<BigInt> x,
761                            Handle<String> y) {
762   // a. Let n be StringToBigInt(y).
763   MaybeHandle<BigInt> maybe_n = StringToBigInt(isolate, y);
764   // b. If n is NaN, return false.
765   Handle<BigInt> n;
766   if (!maybe_n.ToHandle(&n)) {
767     DCHECK(!isolate->has_pending_exception());
768     return false;
769   }
770   // c. Return the result of x == n.
771   return EqualToBigInt(*x, *n);
772 }
773 
EqualToNumber(Handle<BigInt> x,Handle<Object> y)774 bool BigInt::EqualToNumber(Handle<BigInt> x, Handle<Object> y) {
775   DCHECK(y->IsNumber());
776   // a. If x or y are any of NaN, +∞, or -∞, return false.
777   // b. If the mathematical value of x is equal to the mathematical value of y,
778   //    return true, otherwise return false.
779   if (y->IsSmi()) {
780     int value = Smi::ToInt(*y);
781     if (value == 0) return x->is_zero();
782     // Any multi-digit BigInt is bigger than a Smi.
783     STATIC_ASSERT(sizeof(digit_t) >= sizeof(value));
784     return (x->length() == 1) && (x->sign() == (value < 0)) &&
785            (x->digit(0) ==
786             static_cast<digit_t>(std::abs(static_cast<int64_t>(value))));
787   }
788   DCHECK(y->IsHeapNumber());
789   double value = Handle<HeapNumber>::cast(y)->value();
790   return CompareToDouble(x, value) == ComparisonResult::kEqual;
791 }
792 
CompareToNumber(Handle<BigInt> x,Handle<Object> y)793 ComparisonResult BigInt::CompareToNumber(Handle<BigInt> x, Handle<Object> y) {
794   DCHECK(y->IsNumber());
795   if (y->IsSmi()) {
796     bool x_sign = x->sign();
797     int y_value = Smi::ToInt(*y);
798     bool y_sign = (y_value < 0);
799     if (x_sign != y_sign) return UnequalSign(x_sign);
800 
801     if (x->is_zero()) {
802       DCHECK(!y_sign);
803       return y_value == 0 ? ComparisonResult::kEqual
804                           : ComparisonResult::kLessThan;
805     }
806     // Any multi-digit BigInt is bigger than a Smi.
807     STATIC_ASSERT(sizeof(digit_t) >= sizeof(y_value));
808     if (x->length() > 1) return AbsoluteGreater(x_sign);
809 
810     digit_t abs_value = std::abs(static_cast<int64_t>(y_value));
811     digit_t x_digit = x->digit(0);
812     if (x_digit > abs_value) return AbsoluteGreater(x_sign);
813     if (x_digit < abs_value) return AbsoluteLess(x_sign);
814     return ComparisonResult::kEqual;
815   }
816   DCHECK(y->IsHeapNumber());
817   double value = Handle<HeapNumber>::cast(y)->value();
818   return CompareToDouble(x, value);
819 }
820 
CompareToDouble(Handle<BigInt> x,double y)821 ComparisonResult BigInt::CompareToDouble(Handle<BigInt> x, double y) {
822   if (std::isnan(y)) return ComparisonResult::kUndefined;
823   if (y == V8_INFINITY) return ComparisonResult::kLessThan;
824   if (y == -V8_INFINITY) return ComparisonResult::kGreaterThan;
825   bool x_sign = x->sign();
826   // Note that this is different from the double's sign bit for -0. That's
827   // intentional because -0 must be treated like 0.
828   bool y_sign = (y < 0);
829   if (x_sign != y_sign) return UnequalSign(x_sign);
830   if (y == 0) {
831     DCHECK(!x_sign);
832     return x->is_zero() ? ComparisonResult::kEqual
833                         : ComparisonResult::kGreaterThan;
834   }
835   if (x->is_zero()) {
836     DCHECK(!y_sign);
837     return ComparisonResult::kLessThan;
838   }
839   uint64_t double_bits = bit_cast<uint64_t>(y);
840   int raw_exponent =
841       static_cast<int>(double_bits >> Double::kPhysicalSignificandSize) & 0x7FF;
842   uint64_t mantissa = double_bits & Double::kSignificandMask;
843   // Non-finite doubles are handled above.
844   DCHECK_NE(raw_exponent, 0x7FF);
845   int exponent = raw_exponent - 0x3FF;
846   if (exponent < 0) {
847     // The absolute value of the double is less than 1. Only 0n has an
848     // absolute value smaller than that, but we've already covered that case.
849     DCHECK(!x->is_zero());
850     return AbsoluteGreater(x_sign);
851   }
852   int x_length = x->length();
853   digit_t x_msd = x->digit(x_length - 1);
854   int msd_leading_zeros = base::bits::CountLeadingZeros(x_msd);
855   int x_bitlength = x_length * kDigitBits - msd_leading_zeros;
856   int y_bitlength = exponent + 1;
857   if (x_bitlength < y_bitlength) return AbsoluteLess(x_sign);
858   if (x_bitlength > y_bitlength) return AbsoluteGreater(x_sign);
859 
860   // At this point, we know that signs and bit lengths (i.e. position of
861   // the most significant bit in exponent-free representation) are identical.
862   // {x} is not zero, {y} is finite and not denormal.
863   // Now we virtually convert the double to an integer by shifting its
864   // mantissa according to its exponent, so it will align with the BigInt {x},
865   // and then we compare them bit for bit until we find a difference or the
866   // least significant bit.
867   //                    <----- 52 ------> <-- virtual trailing zeroes -->
868   // y / mantissa:     1yyyyyyyyyyyyyyyyy 0000000000000000000000000000000
869   // x / digits:    0001xxxx xxxxxxxx xxxxxxxx ...
870   //                    <-->          <------>
871   //              msd_topbit         kDigitBits
872   //
873   mantissa |= Double::kHiddenBit;
874   const int kMantissaTopBit = 52;  // 0-indexed.
875   // 0-indexed position of {x}'s most significant bit within the {msd}.
876   int msd_topbit = kDigitBits - 1 - msd_leading_zeros;
877   DCHECK_EQ(msd_topbit, (x_bitlength - 1) % kDigitBits);
878   // Shifted chunk of {mantissa} for comparing with {digit}.
879   digit_t compare_mantissa;
880   // Number of unprocessed bits in {mantissa}. We'll keep them shifted to
881   // the left (i.e. most significant part) of the underlying uint64_t.
882   int remaining_mantissa_bits = 0;
883 
884   // First, compare the most significant digit against the beginning of
885   // the mantissa.
886   if (msd_topbit < kMantissaTopBit) {
887     remaining_mantissa_bits = (kMantissaTopBit - msd_topbit);
888     compare_mantissa = mantissa >> remaining_mantissa_bits;
889     mantissa = mantissa << (64 - remaining_mantissa_bits);
890   } else {
891     DCHECK_GE(msd_topbit, kMantissaTopBit);
892     compare_mantissa = mantissa << (msd_topbit - kMantissaTopBit);
893     mantissa = 0;
894   }
895   if (x_msd > compare_mantissa) return AbsoluteGreater(x_sign);
896   if (x_msd < compare_mantissa) return AbsoluteLess(x_sign);
897 
898   // Then, compare additional digits against any remaining mantissa bits.
899   for (int digit_index = x_length - 2; digit_index >= 0; digit_index--) {
900     if (remaining_mantissa_bits > 0) {
901       remaining_mantissa_bits -= kDigitBits;
902       if (sizeof(mantissa) != sizeof(x_msd)) {
903         compare_mantissa = mantissa >> (64 - kDigitBits);
904         // "& 63" to appease compilers. kDigitBits is 32 here anyway.
905         mantissa = mantissa << (kDigitBits & 63);
906       } else {
907         compare_mantissa = mantissa;
908         mantissa = 0;
909       }
910     } else {
911       compare_mantissa = 0;
912     }
913     digit_t digit = x->digit(digit_index);
914     if (digit > compare_mantissa) return AbsoluteGreater(x_sign);
915     if (digit < compare_mantissa) return AbsoluteLess(x_sign);
916   }
917 
918   // Integer parts are equal; check whether {y} has a fractional part.
919   if (mantissa != 0) {
920     DCHECK_GT(remaining_mantissa_bits, 0);
921     return AbsoluteLess(x_sign);
922   }
923   return ComparisonResult::kEqual;
924 }
925 
ToString(Isolate * isolate,Handle<BigInt> bigint,int radix)926 MaybeHandle<String> BigInt::ToString(Isolate* isolate, Handle<BigInt> bigint,
927                                      int radix) {
928   if (bigint->is_zero()) {
929     return isolate->factory()->NewStringFromStaticChars("0");
930   }
931   if (base::bits::IsPowerOfTwo(radix)) {
932     return MutableBigInt::ToStringBasePowerOfTwo(isolate, bigint, radix);
933   }
934   return MutableBigInt::ToStringGeneric(isolate, bigint, radix);
935 }
936 
FromNumber(Isolate * isolate,Handle<Object> number)937 MaybeHandle<BigInt> BigInt::FromNumber(Isolate* isolate,
938                                        Handle<Object> number) {
939   DCHECK(number->IsNumber());
940   if (number->IsSmi()) {
941     return MutableBigInt::NewFromInt(isolate, Smi::ToInt(*number));
942   }
943   double value = HeapNumber::cast(*number)->value();
944   if (!std::isfinite(value) || (DoubleToInteger(value) != value)) {
945     THROW_NEW_ERROR(isolate,
946                     NewRangeError(MessageTemplate::kBigIntFromNumber, number),
947                     BigInt);
948   }
949   return MutableBigInt::NewFromDouble(isolate, value);
950 }
951 
FromObject(Isolate * isolate,Handle<Object> obj)952 MaybeHandle<BigInt> BigInt::FromObject(Isolate* isolate, Handle<Object> obj) {
953   if (obj->IsJSReceiver()) {
954     ASSIGN_RETURN_ON_EXCEPTION(
955         isolate, obj,
956         JSReceiver::ToPrimitive(Handle<JSReceiver>::cast(obj),
957                                 ToPrimitiveHint::kNumber),
958         BigInt);
959   }
960 
961   if (obj->IsBoolean()) {
962     return MutableBigInt::NewFromInt(isolate, obj->BooleanValue(isolate));
963   }
964   if (obj->IsBigInt()) {
965     return Handle<BigInt>::cast(obj);
966   }
967   if (obj->IsString()) {
968     Handle<BigInt> n;
969     if (!StringToBigInt(isolate, Handle<String>::cast(obj)).ToHandle(&n)) {
970       THROW_NEW_ERROR(isolate,
971                       NewSyntaxError(MessageTemplate::kBigIntFromObject, obj),
972                       BigInt);
973     }
974     return n;
975   }
976 
977   THROW_NEW_ERROR(
978       isolate, NewTypeError(MessageTemplate::kBigIntFromObject, obj), BigInt);
979 }
980 
ToNumber(Isolate * isolate,Handle<BigInt> x)981 Handle<Object> BigInt::ToNumber(Isolate* isolate, Handle<BigInt> x) {
982   if (x->is_zero()) return Handle<Smi>(Smi::kZero, isolate);
983   if (x->length() == 1 && x->digit(0) < Smi::kMaxValue) {
984     int value = static_cast<int>(x->digit(0));
985     if (x->sign()) value = -value;
986     return Handle<Smi>(Smi::FromInt(value), isolate);
987   }
988   double result = MutableBigInt::ToDouble(x);
989   return isolate->factory()->NewHeapNumber(result);
990 }
991 
ToDouble(Handle<BigIntBase> x)992 double MutableBigInt::ToDouble(Handle<BigIntBase> x) {
993   if (x->is_zero()) return 0.0;
994   int x_length = x->length();
995   digit_t x_msd = x->digit(x_length - 1);
996   int msd_leading_zeros = base::bits::CountLeadingZeros(x_msd);
997   int x_bitlength = x_length * kDigitBits - msd_leading_zeros;
998   if (x_bitlength > 1024) return x->sign() ? -V8_INFINITY : V8_INFINITY;
999   uint64_t exponent = x_bitlength - 1;
1000   // We need the most significant bit shifted to the position of a double's
1001   // "hidden bit". We also need to hide that MSB, so we shift it out.
1002   uint64_t current_digit = x_msd;
1003   int digit_index = x_length - 1;
1004   int shift = msd_leading_zeros + 1 + (64 - kDigitBits);
1005   DCHECK_LE(1, shift);
1006   DCHECK_LE(shift, 64);
1007   uint64_t mantissa = (shift == 64) ? 0 : current_digit << shift;
1008   mantissa >>= 12;
1009   int mantissa_bits_unset = shift - 12;
1010   // If not all mantissa bits are defined yet, get more digits as needed.
1011   if (mantissa_bits_unset >= kDigitBits && digit_index > 0) {
1012     digit_index--;
1013     current_digit = static_cast<uint64_t>(x->digit(digit_index));
1014     mantissa |= (current_digit << (mantissa_bits_unset - kDigitBits));
1015     mantissa_bits_unset -= kDigitBits;
1016   }
1017   if (mantissa_bits_unset > 0 && digit_index > 0) {
1018     DCHECK_LT(mantissa_bits_unset, kDigitBits);
1019     digit_index--;
1020     current_digit = static_cast<uint64_t>(x->digit(digit_index));
1021     mantissa |= (current_digit >> (kDigitBits - mantissa_bits_unset));
1022     mantissa_bits_unset -= kDigitBits;
1023   }
1024   // If there are unconsumed digits left, we may have to round.
1025   Rounding rounding =
1026       DecideRounding(x, mantissa_bits_unset, digit_index, current_digit);
1027   if (rounding == kRoundUp || (rounding == kTie && (mantissa & 1) == 1)) {
1028     mantissa++;
1029     // Incrementing the mantissa can overflow the mantissa bits. In that case
1030     // the new mantissa will be all zero (plus hidden bit).
1031     if ((mantissa >> Double::kPhysicalSignificandSize) != 0) {
1032       mantissa = 0;
1033       exponent++;
1034       // Incrementing the exponent can overflow too.
1035       if (exponent > 1023) {
1036         return x->sign() ? -V8_INFINITY : V8_INFINITY;
1037       }
1038     }
1039   }
1040   // Assemble the result.
1041   uint64_t sign_bit = x->sign() ? (static_cast<uint64_t>(1) << 63) : 0;
1042   exponent = (exponent + 0x3FF) << Double::kPhysicalSignificandSize;
1043   uint64_t double_bits = sign_bit | exponent | mantissa;
1044   return bit_cast<double>(double_bits);
1045 }
1046 
1047 // This is its own function to keep control flow sane. The meaning of the
1048 // parameters is defined by {ToDouble}'s local variable usage.
DecideRounding(Handle<BigIntBase> x,int mantissa_bits_unset,int digit_index,uint64_t current_digit)1049 MutableBigInt::Rounding MutableBigInt::DecideRounding(Handle<BigIntBase> x,
1050                                                       int mantissa_bits_unset,
1051                                                       int digit_index,
1052                                                       uint64_t current_digit) {
1053   if (mantissa_bits_unset > 0) return kRoundDown;
1054   int top_unconsumed_bit;
1055   if (mantissa_bits_unset < 0) {
1056     // There are unconsumed bits in {current_digit}.
1057     top_unconsumed_bit = -mantissa_bits_unset - 1;
1058   } else {
1059     DCHECK_EQ(mantissa_bits_unset, 0);
1060     // {current_digit} fit the mantissa exactly; look at the next digit.
1061     if (digit_index == 0) return kRoundDown;
1062     digit_index--;
1063     current_digit = static_cast<uint64_t>(x->digit(digit_index));
1064     top_unconsumed_bit = kDigitBits - 1;
1065   }
1066   // If the most significant remaining bit is 0, round down.
1067   uint64_t bitmask = static_cast<uint64_t>(1) << top_unconsumed_bit;
1068   if ((current_digit & bitmask) == 0) {
1069     return kRoundDown;
1070   }
1071   // If any other remaining bit is set, round up.
1072   bitmask -= 1;
1073   if ((current_digit & bitmask) != 0) return kRoundUp;
1074   while (digit_index > 0) {
1075     digit_index--;
1076     if (x->digit(digit_index) != 0) return kRoundUp;
1077   }
1078   return kTie;
1079 }
1080 
BigIntShortPrint(std::ostream & os)1081 void BigInt::BigIntShortPrint(std::ostream& os) {
1082   if (sign()) os << "-";
1083   int len = length();
1084   if (len == 0) {
1085     os << "0";
1086     return;
1087   }
1088   if (len > 1) os << "...";
1089   os << digit(0);
1090 }
1091 
1092 // Internal helpers.
1093 
AbsoluteAdd(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y,bool result_sign)1094 MaybeHandle<BigInt> MutableBigInt::AbsoluteAdd(Isolate* isolate,
1095                                                Handle<BigInt> x,
1096                                                Handle<BigInt> y,
1097                                                bool result_sign) {
1098   if (x->length() < y->length()) return AbsoluteAdd(isolate, y, x, result_sign);
1099   if (x->is_zero()) {
1100     DCHECK(y->is_zero());
1101     return x;
1102   }
1103   if (y->is_zero()) {
1104     return result_sign == x->sign() ? x : BigInt::UnaryMinus(isolate, x);
1105   }
1106   Handle<MutableBigInt> result;
1107   if (!New(isolate, x->length() + 1).ToHandle(&result)) {
1108     return MaybeHandle<BigInt>();
1109   }
1110   digit_t carry = 0;
1111   int i = 0;
1112   for (; i < y->length(); i++) {
1113     digit_t new_carry = 0;
1114     digit_t sum = digit_add(x->digit(i), y->digit(i), &new_carry);
1115     sum = digit_add(sum, carry, &new_carry);
1116     result->set_digit(i, sum);
1117     carry = new_carry;
1118   }
1119   for (; i < x->length(); i++) {
1120     digit_t new_carry = 0;
1121     digit_t sum = digit_add(x->digit(i), carry, &new_carry);
1122     result->set_digit(i, sum);
1123     carry = new_carry;
1124   }
1125   result->set_digit(i, carry);
1126   result->set_sign(result_sign);
1127   return MakeImmutable(result);
1128 }
1129 
AbsoluteSub(Isolate * isolate,Handle<BigInt> x,Handle<BigInt> y,bool result_sign)1130 Handle<BigInt> MutableBigInt::AbsoluteSub(Isolate* isolate, Handle<BigInt> x,
1131                                           Handle<BigInt> y, bool result_sign) {
1132   DCHECK(x->length() >= y->length());
1133   SLOW_DCHECK(AbsoluteCompare(x, y) >= 0);
1134   if (x->is_zero()) {
1135     DCHECK(y->is_zero());
1136     return x;
1137   }
1138   if (y->is_zero()) {
1139     return result_sign == x->sign() ? x : BigInt::UnaryMinus(isolate, x);
1140   }
1141   Handle<MutableBigInt> result = New(isolate, x->length()).ToHandleChecked();
1142   digit_t borrow = 0;
1143   int i = 0;
1144   for (; i < y->length(); i++) {
1145     digit_t new_borrow = 0;
1146     digit_t difference = digit_sub(x->digit(i), y->digit(i), &new_borrow);
1147     difference = digit_sub(difference, borrow, &new_borrow);
1148     result->set_digit(i, difference);
1149     borrow = new_borrow;
1150   }
1151   for (; i < x->length(); i++) {
1152     digit_t new_borrow = 0;
1153     digit_t difference = digit_sub(x->digit(i), borrow, &new_borrow);
1154     result->set_digit(i, difference);
1155     borrow = new_borrow;
1156   }
1157   DCHECK_EQ(0, borrow);
1158   result->set_sign(result_sign);
1159   return MakeImmutable(result);
1160 }
1161 
1162 // Adds 1 to the absolute value of {x} and sets the result's sign to {sign}.
1163 // {result_storage} is optional; if present, it will be used to store the
1164 // result, otherwise a new BigInt will be allocated for the result.
1165 // {result_storage} and {x} may refer to the same BigInt for in-place
1166 // modification.
AbsoluteAddOne(Isolate * isolate,Handle<BigIntBase> x,bool sign,MutableBigInt * result_storage)1167 MaybeHandle<MutableBigInt> MutableBigInt::AbsoluteAddOne(
1168     Isolate* isolate, Handle<BigIntBase> x, bool sign,
1169     MutableBigInt* result_storage) {
1170   int input_length = x->length();
1171   // The addition will overflow into a new digit if all existing digits are
1172   // at maximum.
1173   bool will_overflow = true;
1174   for (int i = 0; i < input_length; i++) {
1175     if (!digit_ismax(x->digit(i))) {
1176       will_overflow = false;
1177       break;
1178     }
1179   }
1180   int result_length = input_length + will_overflow;
1181   Handle<MutableBigInt> result(result_storage, isolate);
1182   if (result_storage == nullptr) {
1183     if (!New(isolate, result_length).ToHandle(&result)) {
1184       return MaybeHandle<MutableBigInt>();
1185     }
1186   } else {
1187     DCHECK(result->length() == result_length);
1188   }
1189   digit_t carry = 1;
1190   for (int i = 0; i < input_length; i++) {
1191     digit_t new_carry = 0;
1192     result->set_digit(i, digit_add(x->digit(i), carry, &new_carry));
1193     carry = new_carry;
1194   }
1195   if (result_length > input_length) {
1196     result->set_digit(input_length, carry);
1197   } else {
1198     DCHECK_EQ(carry, 0);
1199   }
1200   result->set_sign(sign);
1201   return result;
1202 }
1203 
1204 // Subtracts 1 from the absolute value of {x}. {x} must not be zero.
AbsoluteSubOne(Isolate * isolate,Handle<BigIntBase> x)1205 Handle<MutableBigInt> MutableBigInt::AbsoluteSubOne(Isolate* isolate,
1206                                                     Handle<BigIntBase> x) {
1207   DCHECK(!x->is_zero());
1208   // Requesting a result length identical to an existing BigInt's length
1209   // cannot overflow the limit.
1210   return AbsoluteSubOne(isolate, x, x->length()).ToHandleChecked();
1211 }
1212 
1213 // Like the above, but you can specify that the allocated result should have
1214 // length {result_length}, which must be at least as large as {x->length()}.
AbsoluteSubOne(Isolate * isolate,Handle<BigIntBase> x,int result_length)1215 MaybeHandle<MutableBigInt> MutableBigInt::AbsoluteSubOne(Isolate* isolate,
1216                                                          Handle<BigIntBase> x,
1217                                                          int result_length) {
1218   DCHECK(!x->is_zero());
1219   DCHECK(result_length >= x->length());
1220   Handle<MutableBigInt> result;
1221   if (!New(isolate, result_length).ToHandle(&result)) {
1222     return MaybeHandle<MutableBigInt>();
1223   }
1224   int length = x->length();
1225   digit_t borrow = 1;
1226   for (int i = 0; i < length; i++) {
1227     digit_t new_borrow = 0;
1228     result->set_digit(i, digit_sub(x->digit(i), borrow, &new_borrow));
1229     borrow = new_borrow;
1230   }
1231   DCHECK_EQ(borrow, 0);
1232   for (int i = length; i < result_length; i++) {
1233     result->set_digit(i, borrow);
1234   }
1235   return result;
1236 }
1237 
1238 // Helper for Absolute{And,AndNot,Or,Xor}.
1239 // Performs the given binary {op} on digit pairs of {x} and {y}; when the
1240 // end of the shorter of the two is reached, {extra_digits} configures how
1241 // remaining digits in the longer input (if {symmetric} == kSymmetric, in
1242 // {x} otherwise) are handled: copied to the result or ignored.
1243 // If {result_storage} is non-nullptr, it will be used for the result and
1244 // any extra digits in it will be zeroed out, otherwise a new BigInt (with
1245 // the same length as the longer input) will be allocated.
1246 // {result_storage} may alias {x} or {y} for in-place modification.
1247 // Example:
1248 //              y:             [ y2 ][ y1 ][ y0 ]
1249 //              x:       [ x3 ][ x2 ][ x1 ][ x0 ]
1250 //                          |     |     |     |
1251 //                      (kCopy)  (op)  (op)  (op)
1252 //                          |     |     |     |
1253 //                          v     v     v     v
1254 // result_storage: [  0 ][ x3 ][ r2 ][ r1 ][ r0 ]
AbsoluteBitwiseOp(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y,MutableBigInt * result_storage,ExtraDigitsHandling extra_digits,SymmetricOp symmetric,std::function<digit_t (digit_t,digit_t)> op)1255 inline Handle<MutableBigInt> MutableBigInt::AbsoluteBitwiseOp(
1256     Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
1257     MutableBigInt* result_storage, ExtraDigitsHandling extra_digits,
1258     SymmetricOp symmetric, std::function<digit_t(digit_t, digit_t)> op) {
1259   int x_length = x->length();
1260   int y_length = y->length();
1261   int num_pairs = y_length;
1262   if (x_length < y_length) {
1263     num_pairs = x_length;
1264     if (symmetric == kSymmetric) {
1265       std::swap(x, y);
1266       std::swap(x_length, y_length);
1267     }
1268   }
1269   DCHECK(num_pairs == Min(x_length, y_length));
1270   Handle<MutableBigInt> result(result_storage, isolate);
1271   int result_length = extra_digits == kCopy ? x_length : num_pairs;
1272   if (result_storage == nullptr) {
1273     result = New(isolate, result_length).ToHandleChecked();
1274   } else {
1275     DCHECK(result_storage->length() >= result_length);
1276     result_length = result_storage->length();
1277   }
1278   int i = 0;
1279   for (; i < num_pairs; i++) {
1280     result->set_digit(i, op(x->digit(i), y->digit(i)));
1281   }
1282   if (extra_digits == kCopy) {
1283     for (; i < x_length; i++) {
1284       result->set_digit(i, x->digit(i));
1285     }
1286   }
1287   for (; i < result_length; i++) {
1288     result->set_digit(i, 0);
1289   }
1290   return result;
1291 }
1292 
1293 // If {result_storage} is non-nullptr, it will be used for the result,
1294 // otherwise a new BigInt of appropriate length will be allocated.
1295 // {result_storage} may alias {x} or {y} for in-place modification.
AbsoluteAnd(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y,MutableBigInt * result_storage)1296 Handle<MutableBigInt> MutableBigInt::AbsoluteAnd(
1297     Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
1298     MutableBigInt* result_storage) {
1299   return AbsoluteBitwiseOp(isolate, x, y, result_storage, kSkip, kSymmetric,
1300                            [](digit_t a, digit_t b) { return a & b; });
1301 }
1302 
1303 // If {result_storage} is non-nullptr, it will be used for the result,
1304 // otherwise a new BigInt of appropriate length will be allocated.
1305 // {result_storage} may alias {x} or {y} for in-place modification.
AbsoluteAndNot(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y,MutableBigInt * result_storage)1306 Handle<MutableBigInt> MutableBigInt::AbsoluteAndNot(
1307     Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
1308     MutableBigInt* result_storage) {
1309   return AbsoluteBitwiseOp(isolate, x, y, result_storage, kCopy, kNotSymmetric,
1310                            [](digit_t a, digit_t b) { return a & ~b; });
1311 }
1312 
1313 // If {result_storage} is non-nullptr, it will be used for the result,
1314 // otherwise a new BigInt of appropriate length will be allocated.
1315 // {result_storage} may alias {x} or {y} for in-place modification.
AbsoluteOr(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y,MutableBigInt * result_storage)1316 Handle<MutableBigInt> MutableBigInt::AbsoluteOr(Isolate* isolate,
1317                                                 Handle<BigIntBase> x,
1318                                                 Handle<BigIntBase> y,
1319                                                 MutableBigInt* result_storage) {
1320   return AbsoluteBitwiseOp(isolate, x, y, result_storage, kCopy, kSymmetric,
1321                            [](digit_t a, digit_t b) { return a | b; });
1322 }
1323 
1324 // If {result_storage} is non-nullptr, it will be used for the result,
1325 // otherwise a new BigInt of appropriate length will be allocated.
1326 // {result_storage} may alias {x} or {y} for in-place modification.
AbsoluteXor(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y,MutableBigInt * result_storage)1327 Handle<MutableBigInt> MutableBigInt::AbsoluteXor(
1328     Isolate* isolate, Handle<BigIntBase> x, Handle<BigIntBase> y,
1329     MutableBigInt* result_storage) {
1330   return AbsoluteBitwiseOp(isolate, x, y, result_storage, kCopy, kSymmetric,
1331                            [](digit_t a, digit_t b) { return a ^ b; });
1332 }
1333 
1334 // Returns a positive value if abs(x) > abs(y), a negative value if
1335 // abs(x) < abs(y), or zero if abs(x) == abs(y).
AbsoluteCompare(Handle<BigIntBase> x,Handle<BigIntBase> y)1336 int MutableBigInt::AbsoluteCompare(Handle<BigIntBase> x, Handle<BigIntBase> y) {
1337   int diff = x->length() - y->length();
1338   if (diff != 0) return diff;
1339   int i = x->length() - 1;
1340   while (i >= 0 && x->digit(i) == y->digit(i)) i--;
1341   if (i < 0) return 0;
1342   return x->digit(i) > y->digit(i) ? 1 : -1;
1343 }
1344 
1345 // Multiplies {multiplicand} with {multiplier} and adds the result to
1346 // {accumulator}, starting at {accumulator_index} for the least-significant
1347 // digit.
1348 // Callers must ensure that {accumulator} is big enough to hold the result.
MultiplyAccumulate(Handle<BigIntBase> multiplicand,digit_t multiplier,Handle<MutableBigInt> accumulator,int accumulator_index)1349 void MutableBigInt::MultiplyAccumulate(Handle<BigIntBase> multiplicand,
1350                                        digit_t multiplier,
1351                                        Handle<MutableBigInt> accumulator,
1352                                        int accumulator_index) {
1353   // This is a minimum requirement; the DCHECK in the second loop below
1354   // will enforce more as needed.
1355   DCHECK(accumulator->length() > multiplicand->length() + accumulator_index);
1356   if (multiplier == 0L) return;
1357   digit_t carry = 0;
1358   digit_t high = 0;
1359   for (int i = 0; i < multiplicand->length(); i++, accumulator_index++) {
1360     digit_t acc = accumulator->digit(accumulator_index);
1361     digit_t new_carry = 0;
1362     // Add last round's carryovers.
1363     acc = digit_add(acc, high, &new_carry);
1364     acc = digit_add(acc, carry, &new_carry);
1365     // Compute this round's multiplication.
1366     digit_t m_digit = multiplicand->digit(i);
1367     digit_t low = digit_mul(multiplier, m_digit, &high);
1368     acc = digit_add(acc, low, &new_carry);
1369     // Store result and prepare for next round.
1370     accumulator->set_digit(accumulator_index, acc);
1371     carry = new_carry;
1372   }
1373   for (; carry != 0 || high != 0; accumulator_index++) {
1374     DCHECK(accumulator_index < accumulator->length());
1375     digit_t acc = accumulator->digit(accumulator_index);
1376     digit_t new_carry = 0;
1377     acc = digit_add(acc, high, &new_carry);
1378     high = 0;
1379     acc = digit_add(acc, carry, &new_carry);
1380     accumulator->set_digit(accumulator_index, acc);
1381     carry = new_carry;
1382   }
1383 }
1384 
1385 // Multiplies {source} with {factor} and adds {summand} to the result.
1386 // {result} and {source} may be the same BigInt for inplace modification.
InternalMultiplyAdd(BigIntBase * source,digit_t factor,digit_t summand,int n,MutableBigInt * result)1387 void MutableBigInt::InternalMultiplyAdd(BigIntBase* source, digit_t factor,
1388                                         digit_t summand, int n,
1389                                         MutableBigInt* result) {
1390   DCHECK(source->length() >= n);
1391   DCHECK(result->length() >= n);
1392   digit_t carry = summand;
1393   digit_t high = 0;
1394   for (int i = 0; i < n; i++) {
1395     digit_t current = source->digit(i);
1396     digit_t new_carry = 0;
1397     // Compute this round's multiplication.
1398     digit_t new_high = 0;
1399     current = digit_mul(current, factor, &new_high);
1400     // Add last round's carryovers.
1401     current = digit_add(current, high, &new_carry);
1402     current = digit_add(current, carry, &new_carry);
1403     // Store result and prepare for next round.
1404     result->set_digit(i, current);
1405     carry = new_carry;
1406     high = new_high;
1407   }
1408   if (result->length() > n) {
1409     result->set_digit(n++, carry + high);
1410     // Current callers don't pass in such large results, but let's be robust.
1411     while (n < result->length()) {
1412       result->set_digit(n++, 0);
1413     }
1414   } else {
1415     CHECK_EQ(carry + high, 0);
1416   }
1417 }
1418 
1419 // Multiplies {x} with {factor} and then adds {summand} to it.
InplaceMultiplyAdd(Handle<FreshlyAllocatedBigInt> x,uintptr_t factor,uintptr_t summand)1420 void BigInt::InplaceMultiplyAdd(Handle<FreshlyAllocatedBigInt> x,
1421                                 uintptr_t factor, uintptr_t summand) {
1422   STATIC_ASSERT(sizeof(factor) == sizeof(digit_t));
1423   STATIC_ASSERT(sizeof(summand) == sizeof(digit_t));
1424   Handle<MutableBigInt> bigint = MutableBigInt::Cast(x);
1425   MutableBigInt::InternalMultiplyAdd(*bigint, factor, summand, bigint->length(),
1426                                      *bigint);
1427 }
1428 
1429 // Divides {x} by {divisor}, returning the result in {quotient} and {remainder}.
1430 // Mathematically, the contract is:
1431 // quotient = (x - remainder) / divisor, with 0 <= remainder < divisor.
1432 // If {quotient} is an empty handle, an appropriately sized BigInt will be
1433 // allocated for it; otherwise the caller must ensure that it is big enough.
1434 // {quotient} can be the same as {x} for an in-place division. {quotient} can
1435 // also be nullptr if the caller is only interested in the remainder.
AbsoluteDivSmall(Isolate * isolate,Handle<BigIntBase> x,digit_t divisor,Handle<MutableBigInt> * quotient,digit_t * remainder)1436 void MutableBigInt::AbsoluteDivSmall(Isolate* isolate, Handle<BigIntBase> x,
1437                                      digit_t divisor,
1438                                      Handle<MutableBigInt>* quotient,
1439                                      digit_t* remainder) {
1440   DCHECK_NE(divisor, 0);
1441   DCHECK(!x->is_zero());  // Callers check anyway, no need to handle this.
1442   *remainder = 0;
1443   int length = x->length();
1444   if (quotient != nullptr) {
1445     if ((*quotient).is_null()) {
1446       *quotient = New(isolate, length).ToHandleChecked();
1447     }
1448     for (int i = length - 1; i >= 0; i--) {
1449       digit_t q = digit_div(*remainder, x->digit(i), divisor, remainder);
1450       (*quotient)->set_digit(i, q);
1451     }
1452   } else {
1453     for (int i = length - 1; i >= 0; i--) {
1454       digit_div(*remainder, x->digit(i), divisor, remainder);
1455     }
1456   }
1457 }
1458 
1459 // Divides {dividend} by {divisor}, returning the result in {quotient} and
1460 // {remainder}. Mathematically, the contract is:
1461 // quotient = (dividend - remainder) / divisor, with 0 <= remainder < divisor.
1462 // Both {quotient} and {remainder} are optional, for callers that are only
1463 // interested in one of them.
1464 // See Knuth, Volume 2, section 4.3.1, Algorithm D.
AbsoluteDivLarge(Isolate * isolate,Handle<BigIntBase> dividend,Handle<BigIntBase> divisor,Handle<MutableBigInt> * quotient,Handle<MutableBigInt> * remainder)1465 bool MutableBigInt::AbsoluteDivLarge(Isolate* isolate,
1466                                      Handle<BigIntBase> dividend,
1467                                      Handle<BigIntBase> divisor,
1468                                      Handle<MutableBigInt>* quotient,
1469                                      Handle<MutableBigInt>* remainder) {
1470   DCHECK_GE(divisor->length(), 2);
1471   DCHECK(dividend->length() >= divisor->length());
1472   // The unusual variable names inside this function are consistent with
1473   // Knuth's book, as well as with Go's implementation of this algorithm.
1474   // Maintaining this consistency is probably more useful than trying to
1475   // come up with more descriptive names for them.
1476   int n = divisor->length();
1477   int m = dividend->length() - n;
1478 
1479   // The quotient to be computed.
1480   Handle<MutableBigInt> q;
1481   if (quotient != nullptr) q = New(isolate, m + 1).ToHandleChecked();
1482   // In each iteration, {qhatv} holds {divisor} * {current quotient digit}.
1483   // "v" is the book's name for {divisor}, "qhat" the current quotient digit.
1484   Handle<MutableBigInt> qhatv;
1485   if (!New(isolate, n + 1).ToHandle(&qhatv)) return false;
1486 
1487   // D1.
1488   // Left-shift inputs so that the divisor's MSB is set. This is necessary
1489   // to prevent the digit-wise divisions (see digit_div call below) from
1490   // overflowing (they take a two digits wide input, and return a one digit
1491   // result).
1492   int shift = base::bits::CountLeadingZeros(divisor->digit(n - 1));
1493   if (shift > 0) {
1494     divisor = SpecialLeftShift(isolate, divisor, shift, kSameSizeResult)
1495                   .ToHandleChecked();
1496   }
1497   // Holds the (continuously updated) remaining part of the dividend, which
1498   // eventually becomes the remainder.
1499   Handle<MutableBigInt> u;
1500   if (!SpecialLeftShift(isolate, dividend, shift, kAlwaysAddOneDigit)
1501            .ToHandle(&u)) {
1502     return false;
1503   }
1504 
1505   // D2.
1506   // Iterate over the dividend's digit (like the "grad school" algorithm).
1507   // {vn1} is the divisor's most significant digit.
1508   digit_t vn1 = divisor->digit(n - 1);
1509   for (int j = m; j >= 0; j--) {
1510     // D3.
1511     // Estimate the current iteration's quotient digit (see Knuth for details).
1512     // {qhat} is the current quotient digit.
1513     digit_t qhat = std::numeric_limits<digit_t>::max();
1514     // {ujn} is the dividend's most significant remaining digit.
1515     digit_t ujn = u->digit(j + n);
1516     if (ujn != vn1) {
1517       // {rhat} is the current iteration's remainder.
1518       digit_t rhat = 0;
1519       // Estimate the current quotient digit by dividing the most significant
1520       // digits of dividend and divisor. The result will not be too small,
1521       // but could be a bit too large.
1522       qhat = digit_div(ujn, u->digit(j + n - 1), vn1, &rhat);
1523 
1524       // Decrement the quotient estimate as needed by looking at the next
1525       // digit, i.e. by testing whether
1526       // qhat * v_{n-2} > (rhat << kDigitBits) + u_{j+n-2}.
1527       digit_t vn2 = divisor->digit(n - 2);
1528       digit_t ujn2 = u->digit(j + n - 2);
1529       while (ProductGreaterThan(qhat, vn2, rhat, ujn2)) {
1530         qhat--;
1531         digit_t prev_rhat = rhat;
1532         rhat += vn1;
1533         // v[n-1] >= 0, so this tests for overflow.
1534         if (rhat < prev_rhat) break;
1535       }
1536     }
1537 
1538     // D4.
1539     // Multiply the divisor with the current quotient digit, and subtract
1540     // it from the dividend. If there was "borrow", then the quotient digit
1541     // was one too high, so we must correct it and undo one subtraction of
1542     // the (shifted) divisor.
1543     InternalMultiplyAdd(*divisor, qhat, 0, n, *qhatv);
1544     digit_t c = u->InplaceSub(qhatv, j);
1545     if (c != 0) {
1546       c = u->InplaceAdd(divisor, j);
1547       u->set_digit(j + n, u->digit(j + n) + c);
1548       qhat--;
1549     }
1550 
1551     if (quotient != nullptr) q->set_digit(j, qhat);
1552   }
1553   if (quotient != nullptr) {
1554     *quotient = q;  // Caller will right-trim.
1555   }
1556   if (remainder != nullptr) {
1557     u->InplaceRightShift(shift);
1558     *remainder = u;
1559   }
1560   return true;
1561 }
1562 
1563 // Returns whether (factor1 * factor2) > (high << kDigitBits) + low.
ProductGreaterThan(digit_t factor1,digit_t factor2,digit_t high,digit_t low)1564 bool MutableBigInt::ProductGreaterThan(digit_t factor1, digit_t factor2,
1565                                        digit_t high, digit_t low) {
1566   digit_t result_high;
1567   digit_t result_low = digit_mul(factor1, factor2, &result_high);
1568   return result_high > high || (result_high == high && result_low > low);
1569 }
1570 
1571 // Adds {summand} onto {this}, starting with {summand}'s 0th digit
1572 // at {this}'s {start_index}'th digit. Returns the "carry" (0 or 1).
InplaceAdd(Handle<BigIntBase> summand,int start_index)1573 BigInt::digit_t MutableBigInt::InplaceAdd(Handle<BigIntBase> summand,
1574                                           int start_index) {
1575   digit_t carry = 0;
1576   int n = summand->length();
1577   DCHECK(length() >= start_index + n);
1578   for (int i = 0; i < n; i++) {
1579     digit_t new_carry = 0;
1580     digit_t sum =
1581         digit_add(digit(start_index + i), summand->digit(i), &new_carry);
1582     sum = digit_add(sum, carry, &new_carry);
1583     set_digit(start_index + i, sum);
1584     carry = new_carry;
1585   }
1586   return carry;
1587 }
1588 
1589 // Subtracts {subtrahend} from {this}, starting with {subtrahend}'s 0th digit
1590 // at {this}'s {start_index}-th digit. Returns the "borrow" (0 or 1).
InplaceSub(Handle<BigIntBase> subtrahend,int start_index)1591 BigInt::digit_t MutableBigInt::InplaceSub(Handle<BigIntBase> subtrahend,
1592                                           int start_index) {
1593   digit_t borrow = 0;
1594   int n = subtrahend->length();
1595   DCHECK(length() >= start_index + n);
1596   for (int i = 0; i < n; i++) {
1597     digit_t new_borrow = 0;
1598     digit_t difference =
1599         digit_sub(digit(start_index + i), subtrahend->digit(i), &new_borrow);
1600     difference = digit_sub(difference, borrow, &new_borrow);
1601     set_digit(start_index + i, difference);
1602     borrow = new_borrow;
1603   }
1604   return borrow;
1605 }
1606 
InplaceRightShift(int shift)1607 void MutableBigInt::InplaceRightShift(int shift) {
1608   DCHECK_GE(shift, 0);
1609   DCHECK_LT(shift, kDigitBits);
1610   DCHECK_GT(length(), 0);
1611   DCHECK_EQ(digit(0) & ((static_cast<digit_t>(1) << shift) - 1), 0);
1612   if (shift == 0) return;
1613   digit_t carry = digit(0) >> shift;
1614   int last = length() - 1;
1615   for (int i = 0; i < last; i++) {
1616     digit_t d = digit(i + 1);
1617     set_digit(i, (d << (kDigitBits - shift)) | carry);
1618     carry = d >> shift;
1619   }
1620   set_digit(last, carry);
1621 }
1622 
1623 // Always copies the input, even when {shift} == 0.
1624 // {shift} must be less than kDigitBits, {x} must be non-zero.
SpecialLeftShift(Isolate * isolate,Handle<BigIntBase> x,int shift,SpecialLeftShiftMode mode)1625 MaybeHandle<MutableBigInt> MutableBigInt::SpecialLeftShift(
1626     Isolate* isolate, Handle<BigIntBase> x, int shift,
1627     SpecialLeftShiftMode mode) {
1628   DCHECK_GE(shift, 0);
1629   DCHECK_LT(shift, kDigitBits);
1630   DCHECK_GT(x->length(), 0);
1631   int n = x->length();
1632   int result_length = mode == kAlwaysAddOneDigit ? n + 1 : n;
1633   Handle<MutableBigInt> result;
1634   if (!New(isolate, result_length).ToHandle(&result)) {
1635     return MaybeHandle<MutableBigInt>();
1636   }
1637   if (shift == 0) {
1638     for (int i = 0; i < n; i++) result->set_digit(i, x->digit(i));
1639     if (mode == kAlwaysAddOneDigit) result->set_digit(n, 0);
1640     return result;
1641   }
1642   DCHECK_GT(shift, 0);
1643   digit_t carry = 0;
1644   for (int i = 0; i < n; i++) {
1645     digit_t d = x->digit(i);
1646     result->set_digit(i, (d << shift) | carry);
1647     carry = d >> (kDigitBits - shift);
1648   }
1649   if (mode == kAlwaysAddOneDigit) {
1650     result->set_digit(n, carry);
1651   } else {
1652     DCHECK_EQ(mode, kSameSizeResult);
1653     DCHECK_EQ(carry, 0);
1654   }
1655   return result;
1656 }
1657 
LeftShiftByAbsolute(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y)1658 MaybeHandle<BigInt> MutableBigInt::LeftShiftByAbsolute(Isolate* isolate,
1659                                                        Handle<BigIntBase> x,
1660                                                        Handle<BigIntBase> y) {
1661   Maybe<digit_t> maybe_shift = ToShiftAmount(y);
1662   if (maybe_shift.IsNothing()) {
1663     THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
1664                     BigInt);
1665   }
1666   digit_t shift = maybe_shift.FromJust();
1667   int digit_shift = static_cast<int>(shift / kDigitBits);
1668   int bits_shift = static_cast<int>(shift % kDigitBits);
1669   int length = x->length();
1670   bool grow = bits_shift != 0 &&
1671               (x->digit(length - 1) >> (kDigitBits - bits_shift)) != 0;
1672   int result_length = length + digit_shift + grow;
1673   if (result_length > kMaxLength) {
1674     THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
1675                     BigInt);
1676   }
1677   Handle<MutableBigInt> result;
1678   if (!New(isolate, result_length).ToHandle(&result)) {
1679     return MaybeHandle<BigInt>();
1680   }
1681   if (bits_shift == 0) {
1682     int i = 0;
1683     for (; i < digit_shift; i++) result->set_digit(i, 0ul);
1684     for (; i < result_length; i++) {
1685       result->set_digit(i, x->digit(i - digit_shift));
1686     }
1687   } else {
1688     digit_t carry = 0;
1689     for (int i = 0; i < digit_shift; i++) result->set_digit(i, 0ul);
1690     for (int i = 0; i < length; i++) {
1691       digit_t d = x->digit(i);
1692       result->set_digit(i + digit_shift, (d << bits_shift) | carry);
1693       carry = d >> (kDigitBits - bits_shift);
1694     }
1695     if (grow) {
1696       result->set_digit(length + digit_shift, carry);
1697     } else {
1698       DCHECK_EQ(carry, 0);
1699     }
1700   }
1701   result->set_sign(x->sign());
1702   return MakeImmutable(result);
1703 }
1704 
RightShiftByAbsolute(Isolate * isolate,Handle<BigIntBase> x,Handle<BigIntBase> y)1705 Handle<BigInt> MutableBigInt::RightShiftByAbsolute(Isolate* isolate,
1706                                                    Handle<BigIntBase> x,
1707                                                    Handle<BigIntBase> y) {
1708   int length = x->length();
1709   bool sign = x->sign();
1710   Maybe<digit_t> maybe_shift = ToShiftAmount(y);
1711   if (maybe_shift.IsNothing()) {
1712     return RightShiftByMaximum(isolate, sign);
1713   }
1714   digit_t shift = maybe_shift.FromJust();
1715   int digit_shift = static_cast<int>(shift / kDigitBits);
1716   int bits_shift = static_cast<int>(shift % kDigitBits);
1717   int result_length = length - digit_shift;
1718   if (result_length <= 0) {
1719     return RightShiftByMaximum(isolate, sign);
1720   }
1721   // For negative numbers, round down if any bit was shifted out (so that e.g.
1722   // -5n >> 1n == -3n and not -2n). Check now whether this will happen and
1723   // whether it can cause overflow into a new digit. If we allocate the result
1724   // large enough up front, it avoids having to do a second allocation later.
1725   bool must_round_down = false;
1726   if (sign) {
1727     const digit_t mask = (static_cast<digit_t>(1) << bits_shift) - 1;
1728     if ((x->digit(digit_shift) & mask) != 0) {
1729       must_round_down = true;
1730     } else {
1731       for (int i = 0; i < digit_shift; i++) {
1732         if (x->digit(i) != 0) {
1733           must_round_down = true;
1734           break;
1735         }
1736       }
1737     }
1738   }
1739   // If bits_shift is non-zero, it frees up bits, preventing overflow.
1740   if (must_round_down && bits_shift == 0) {
1741     // Overflow cannot happen if the most significant digit has unset bits.
1742     digit_t msd = x->digit(length - 1);
1743     bool rounding_can_overflow = digit_ismax(msd);
1744     if (rounding_can_overflow) result_length++;
1745   }
1746 
1747   DCHECK_LE(result_length, length);
1748   Handle<MutableBigInt> result = New(isolate, result_length).ToHandleChecked();
1749   if (bits_shift == 0) {
1750     for (int i = digit_shift; i < length; i++) {
1751       result->set_digit(i - digit_shift, x->digit(i));
1752     }
1753   } else {
1754     digit_t carry = x->digit(digit_shift) >> bits_shift;
1755     int last = length - digit_shift - 1;
1756     for (int i = 0; i < last; i++) {
1757       digit_t d = x->digit(i + digit_shift + 1);
1758       result->set_digit(i, (d << (kDigitBits - bits_shift)) | carry);
1759       carry = d >> bits_shift;
1760     }
1761     result->set_digit(last, carry);
1762   }
1763 
1764   if (sign) {
1765     result->set_sign(true);
1766     if (must_round_down) {
1767       // Since the result is negative, rounding down means adding one to
1768       // its absolute value. This cannot overflow.
1769       result = AbsoluteAddOne(isolate, result, true, *result).ToHandleChecked();
1770     }
1771   }
1772   return MakeImmutable(result);
1773 }
1774 
RightShiftByMaximum(Isolate * isolate,bool sign)1775 Handle<BigInt> MutableBigInt::RightShiftByMaximum(Isolate* isolate, bool sign) {
1776   if (sign) {
1777     // TODO(jkummerow): Consider caching a canonical -1n BigInt.
1778     return NewFromInt(isolate, -1);
1779   } else {
1780     return Zero(isolate);
1781   }
1782 }
1783 
1784 // Returns the value of {x} if it is less than the maximum bit length of
1785 // a BigInt, or Nothing otherwise.
ToShiftAmount(Handle<BigIntBase> x)1786 Maybe<BigInt::digit_t> MutableBigInt::ToShiftAmount(Handle<BigIntBase> x) {
1787   if (x->length() > 1) return Nothing<digit_t>();
1788   digit_t value = x->digit(0);
1789   STATIC_ASSERT(kMaxLengthBits < std::numeric_limits<digit_t>::max());
1790   if (value > kMaxLengthBits) return Nothing<digit_t>();
1791   return Just(value);
1792 }
1793 
1794 // Lookup table for the maximum number of bits required per character of a
1795 // base-N string representation of a number. To increase accuracy, the array
1796 // value is the actual value multiplied by 32. To generate this table:
1797 // for (var i = 0; i <= 36; i++) { print(Math.ceil(Math.log2(i) * 32) + ","); }
1798 constexpr uint8_t kMaxBitsPerChar[] = {
1799     0,   0,   32,  51,  64,  75,  83,  90,  96,  // 0..8
1800     102, 107, 111, 115, 119, 122, 126, 128,      // 9..16
1801     131, 134, 136, 139, 141, 143, 145, 147,      // 17..24
1802     149, 151, 153, 154, 156, 158, 159, 160,      // 25..32
1803     162, 163, 165, 166,                          // 33..36
1804 };
1805 
1806 static const int kBitsPerCharTableShift = 5;
1807 static const size_t kBitsPerCharTableMultiplier = 1u << kBitsPerCharTableShift;
1808 
AllocateFor(Isolate * isolate,int radix,int charcount,ShouldThrow should_throw,PretenureFlag pretenure)1809 MaybeHandle<FreshlyAllocatedBigInt> BigInt::AllocateFor(
1810     Isolate* isolate, int radix, int charcount, ShouldThrow should_throw,
1811     PretenureFlag pretenure) {
1812   DCHECK(2 <= radix && radix <= 36);
1813   DCHECK_GE(charcount, 0);
1814   size_t bits_per_char = kMaxBitsPerChar[radix];
1815   size_t chars = static_cast<size_t>(charcount);
1816   const int roundup = kBitsPerCharTableMultiplier - 1;
1817   if (chars <= (std::numeric_limits<size_t>::max() - roundup) / bits_per_char) {
1818     size_t bits_min = bits_per_char * chars;
1819     // Divide by 32 (see table), rounding up.
1820     bits_min = (bits_min + roundup) >> kBitsPerCharTableShift;
1821     if (bits_min <= static_cast<size_t>(kMaxInt)) {
1822       // Divide by kDigitsBits, rounding up.
1823       int length = (static_cast<int>(bits_min) + kDigitBits - 1) / kDigitBits;
1824       if (length <= kMaxLength) {
1825         Handle<MutableBigInt> result =
1826             MutableBigInt::New(isolate, length, pretenure).ToHandleChecked();
1827         result->InitializeDigits(length);
1828         return result;
1829       }
1830     }
1831   }
1832   // All the overflow/maximum checks above fall through to here.
1833   if (should_throw == kThrowOnError) {
1834     THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
1835                     FreshlyAllocatedBigInt);
1836   } else {
1837     return MaybeHandle<FreshlyAllocatedBigInt>();
1838   }
1839 }
1840 
Finalize(Handle<FreshlyAllocatedBigInt> x,bool sign)1841 Handle<BigInt> BigInt::Finalize(Handle<FreshlyAllocatedBigInt> x, bool sign) {
1842   Handle<MutableBigInt> bigint = MutableBigInt::Cast(x);
1843   bigint->set_sign(sign);
1844   return MutableBigInt::MakeImmutable(bigint);
1845 }
1846 
1847 // The serialization format MUST NOT CHANGE without updating the format
1848 // version in value-serializer.cc!
GetBitfieldForSerialization() const1849 uint32_t BigInt::GetBitfieldForSerialization() const {
1850   // In order to make the serialization format the same on 32/64 bit builds,
1851   // we convert the length-in-digits to length-in-bytes for serialization.
1852   // Being able to do this depends on having enough LengthBits:
1853   STATIC_ASSERT(kMaxLength * kDigitSize <= LengthBits::kMax);
1854   int bytelength = length() * kDigitSize;
1855   return SignBits::encode(sign()) | LengthBits::encode(bytelength);
1856 }
1857 
DigitsByteLengthForBitfield(uint32_t bitfield)1858 int BigInt::DigitsByteLengthForBitfield(uint32_t bitfield) {
1859   return LengthBits::decode(bitfield);
1860 }
1861 
1862 // The serialization format MUST NOT CHANGE without updating the format
1863 // version in value-serializer.cc!
SerializeDigits(uint8_t * storage)1864 void BigInt::SerializeDigits(uint8_t* storage) {
1865   void* digits = reinterpret_cast<void*>(reinterpret_cast<Address>(this) +
1866                                          kDigitsOffset - kHeapObjectTag);
1867 #if defined(V8_TARGET_LITTLE_ENDIAN)
1868   int bytelength = length() * kDigitSize;
1869   memcpy(storage, digits, bytelength);
1870 #elif defined(V8_TARGET_BIG_ENDIAN)
1871   digit_t* digit_storage = reinterpret_cast<digit_t*>(storage);
1872   const digit_t* digit = reinterpret_cast<const digit_t*>(digits);
1873   for (int i = 0; i < length(); i++) {
1874     *digit_storage = ByteReverse(*digit);
1875     digit_storage++;
1876     digit++;
1877   }
1878 #endif  // V8_TARGET_BIG_ENDIAN
1879 }
1880 
1881 // The serialization format MUST NOT CHANGE without updating the format
1882 // version in value-serializer.cc!
FromSerializedDigits(Isolate * isolate,uint32_t bitfield,Vector<const uint8_t> digits_storage,PretenureFlag pretenure)1883 MaybeHandle<BigInt> BigInt::FromSerializedDigits(
1884     Isolate* isolate, uint32_t bitfield, Vector<const uint8_t> digits_storage,
1885     PretenureFlag pretenure) {
1886   int bytelength = LengthBits::decode(bitfield);
1887   DCHECK(digits_storage.length() == bytelength);
1888   bool sign = SignBits::decode(bitfield);
1889   int length = (bytelength + kDigitSize - 1) / kDigitSize;  // Round up.
1890   Handle<MutableBigInt> result =
1891       MutableBigInt::Cast(isolate->factory()->NewBigInt(length, pretenure));
1892   result->initialize_bitfield(sign, length);
1893   void* digits = reinterpret_cast<void*>(reinterpret_cast<Address>(*result) +
1894                                          kDigitsOffset - kHeapObjectTag);
1895 #if defined(V8_TARGET_LITTLE_ENDIAN)
1896   memcpy(digits, digits_storage.start(), bytelength);
1897   void* padding_start =
1898       reinterpret_cast<void*>(reinterpret_cast<Address>(digits) + bytelength);
1899   memset(padding_start, 0, length * kDigitSize - bytelength);
1900 #elif defined(V8_TARGET_BIG_ENDIAN)
1901   digit_t* digit = reinterpret_cast<digit_t*>(digits);
1902   const digit_t* digit_storage =
1903       reinterpret_cast<const digit_t*>(digits_storage.start());
1904   for (int i = 0; i < bytelength / kDigitSize; i++) {
1905     *digit = ByteReverse(*digit_storage);
1906     digit_storage++;
1907     digit++;
1908   }
1909   if (bytelength % kDigitSize) {
1910     *digit = 0;
1911     byte* digit_byte = reinterpret_cast<byte*>(digit);
1912     digit_byte += sizeof(*digit) - 1;
1913     const byte* digit_storage_byte =
1914         reinterpret_cast<const byte*>(digit_storage);
1915     for (int i = 0; i < bytelength % kDigitSize; i++) {
1916       *digit_byte = *digit_storage_byte;
1917       digit_byte--;
1918       digit_storage_byte++;
1919     }
1920   }
1921 #endif  // V8_TARGET_BIG_ENDIAN
1922   return MutableBigInt::MakeImmutable(result);
1923 }
1924 
1925 static const char kConversionChars[] = "0123456789abcdefghijklmnopqrstuvwxyz";
1926 
ToStringBasePowerOfTwo(Isolate * isolate,Handle<BigIntBase> x,int radix)1927 MaybeHandle<String> MutableBigInt::ToStringBasePowerOfTwo(Isolate* isolate,
1928                                                           Handle<BigIntBase> x,
1929                                                           int radix) {
1930   STATIC_ASSERT(base::bits::IsPowerOfTwo(kDigitBits));
1931   DCHECK(base::bits::IsPowerOfTwo(radix));
1932   DCHECK(radix >= 2 && radix <= 32);
1933   DCHECK(!x->is_zero());
1934 
1935   const int length = x->length();
1936   const bool sign = x->sign();
1937   const int bits_per_char = base::bits::CountTrailingZeros(radix);
1938   const int char_mask = radix - 1;
1939   // Compute the length of the resulting string: divide the bit length of the
1940   // BigInt by the number of bits representable per character (rounding up).
1941   const digit_t msd = x->digit(length - 1);
1942   const int msd_leading_zeros = base::bits::CountLeadingZeros(msd);
1943   const size_t bit_length = length * kDigitBits - msd_leading_zeros;
1944   const size_t chars_required =
1945       (bit_length + bits_per_char - 1) / bits_per_char + sign;
1946 
1947   if (chars_required > String::kMaxLength) {
1948     THROW_NEW_ERROR(isolate, NewInvalidStringLengthError(), String);
1949   }
1950 
1951   Handle<SeqOneByteString> result =
1952       isolate->factory()
1953           ->NewRawOneByteString(static_cast<int>(chars_required))
1954           .ToHandleChecked();
1955   DisallowHeapAllocation no_gc;
1956   uint8_t* buffer = result->GetChars();
1957   // Print the number into the string, starting from the last position.
1958   int pos = static_cast<int>(chars_required - 1);
1959   digit_t digit = 0;
1960   // Keeps track of how many unprocessed bits there are in {digit}.
1961   int available_bits = 0;
1962   for (int i = 0; i < length - 1; i++) {
1963     digit_t new_digit = x->digit(i);
1964     // Take any leftover bits from the last iteration into account.
1965     int current = (digit | (new_digit << available_bits)) & char_mask;
1966     buffer[pos--] = kConversionChars[current];
1967     int consumed_bits = bits_per_char - available_bits;
1968     digit = new_digit >> consumed_bits;
1969     available_bits = kDigitBits - consumed_bits;
1970     while (available_bits >= bits_per_char) {
1971       buffer[pos--] = kConversionChars[digit & char_mask];
1972       digit >>= bits_per_char;
1973       available_bits -= bits_per_char;
1974     }
1975   }
1976   // Take any leftover bits from the last iteration into account.
1977   int current = (digit | (msd << available_bits)) & char_mask;
1978   buffer[pos--] = kConversionChars[current];
1979   digit = msd >> (bits_per_char - available_bits);
1980   while (digit != 0) {
1981     buffer[pos--] = kConversionChars[digit & char_mask];
1982     digit >>= bits_per_char;
1983   }
1984   if (sign) buffer[pos--] = '-';
1985   DCHECK_EQ(pos, -1);
1986   return result;
1987 }
1988 
ToStringGeneric(Isolate * isolate,Handle<BigIntBase> x,int radix)1989 MaybeHandle<String> MutableBigInt::ToStringGeneric(Isolate* isolate,
1990                                                    Handle<BigIntBase> x,
1991                                                    int radix) {
1992   DCHECK(radix >= 2 && radix <= 36);
1993   DCHECK(!x->is_zero());
1994   Heap* heap = isolate->heap();
1995 
1996   const int length = x->length();
1997   const bool sign = x->sign();
1998 
1999   // Compute (an overapproximation of) the length of the resulting string:
2000   // Divide bit length of the BigInt by bits representable per character.
2001   const size_t bit_length =
2002       length * kDigitBits - base::bits::CountLeadingZeros(x->digit(length - 1));
2003   // Maximum number of bits we can represent with one character. We'll use this
2004   // to find an appropriate chunk size below.
2005   const uint8_t max_bits_per_char = kMaxBitsPerChar[radix];
2006   // For estimating result length, we have to be pessimistic and work with
2007   // the minimum number of bits one character can represent.
2008   const uint8_t min_bits_per_char = max_bits_per_char - 1;
2009   // Perform the following computation with uint64_t to avoid overflows.
2010   uint64_t chars_required = bit_length;
2011   chars_required *= kBitsPerCharTableMultiplier;
2012   chars_required += min_bits_per_char - 1;  // Round up.
2013   chars_required /= min_bits_per_char;
2014   chars_required += sign;
2015 
2016   if (chars_required > String::kMaxLength) {
2017     THROW_NEW_ERROR(isolate, NewInvalidStringLengthError(), String);
2018   }
2019   Handle<SeqOneByteString> result =
2020       isolate->factory()
2021           ->NewRawOneByteString(static_cast<int>(chars_required))
2022           .ToHandleChecked();
2023 
2024 #if DEBUG
2025   // Zap the string first.
2026   {
2027     DisallowHeapAllocation no_gc;
2028     uint8_t* chars = result->GetChars();
2029     for (int i = 0; i < static_cast<int>(chars_required); i++) chars[i] = '?';
2030   }
2031 #endif
2032 
2033   // We assemble the result string in reverse order, and then reverse it.
2034   // TODO(jkummerow): Consider building the string from the right, and
2035   // left-shifting it if the length estimate was too large.
2036   int pos = 0;
2037 
2038   digit_t last_digit;
2039   if (length == 1) {
2040     last_digit = x->digit(0);
2041   } else {
2042     int chunk_chars =
2043         kDigitBits * kBitsPerCharTableMultiplier / max_bits_per_char;
2044     digit_t chunk_divisor = digit_pow(radix, chunk_chars);
2045     // By construction of chunk_chars, there can't have been overflow.
2046     DCHECK_NE(chunk_divisor, 0);
2047     int nonzero_digit = length - 1;
2048     DCHECK_NE(x->digit(nonzero_digit), 0);
2049     // {rest} holds the part of the BigInt that we haven't looked at yet.
2050     // Not to be confused with "remainder"!
2051     Handle<MutableBigInt> rest;
2052     // In the first round, divide the input, allocating a new BigInt for
2053     // the result == rest; from then on divide the rest in-place.
2054     Handle<BigIntBase>* dividend = &x;
2055     do {
2056       digit_t chunk;
2057       AbsoluteDivSmall(isolate, *dividend, chunk_divisor, &rest, &chunk);
2058       DCHECK(!rest.is_null());
2059       dividend = reinterpret_cast<Handle<BigIntBase>*>(&rest);
2060       DisallowHeapAllocation no_gc;
2061       uint8_t* chars = result->GetChars();
2062       for (int i = 0; i < chunk_chars; i++) {
2063         chars[pos++] = kConversionChars[chunk % radix];
2064         chunk /= radix;
2065       }
2066       DCHECK_EQ(chunk, 0);
2067       if (rest->digit(nonzero_digit) == 0) nonzero_digit--;
2068       // We can never clear more than one digit per iteration, because
2069       // chunk_divisor is smaller than max digit value.
2070       DCHECK_GT(rest->digit(nonzero_digit), 0);
2071     } while (nonzero_digit > 0);
2072     last_digit = rest->digit(0);
2073   }
2074   DisallowHeapAllocation no_gc;
2075   uint8_t* chars = result->GetChars();
2076   do {
2077     chars[pos++] = kConversionChars[last_digit % radix];
2078     last_digit /= radix;
2079   } while (last_digit > 0);
2080   DCHECK_GE(pos, 1);
2081   DCHECK(pos <= static_cast<int>(chars_required));
2082   // Remove leading zeroes.
2083   while (pos > 1 && chars[pos - 1] == '0') pos--;
2084   if (sign) chars[pos++] = '-';
2085   // Trim any over-allocation (which can happen due to conservative estimates).
2086   if (pos < static_cast<int>(chars_required)) {
2087     result->synchronized_set_length(pos);
2088     int string_size =
2089         SeqOneByteString::SizeFor(static_cast<int>(chars_required));
2090     int needed_size = SeqOneByteString::SizeFor(pos);
2091     if (needed_size < string_size) {
2092       Address new_end = result->address() + needed_size;
2093       heap->CreateFillerObjectAt(new_end, (string_size - needed_size),
2094                                  ClearRecordedSlots::kNo);
2095     }
2096   }
2097   // Reverse the string.
2098   for (int i = 0, j = pos - 1; i < j; i++, j--) {
2099     uint8_t tmp = chars[i];
2100     chars[i] = chars[j];
2101     chars[j] = tmp;
2102   }
2103 #if DEBUG
2104   // Verify that all characters have been written.
2105   DCHECK(result->length() == pos);
2106   for (int i = 0; i < pos; i++) DCHECK_NE(chars[i], '?');
2107 #endif
2108   return result;
2109 }
2110 
AsIntN(Isolate * isolate,uint64_t n,Handle<BigInt> x)2111 Handle<BigInt> BigInt::AsIntN(Isolate* isolate, uint64_t n, Handle<BigInt> x) {
2112   if (x->is_zero()) return x;
2113   if (n == 0) return MutableBigInt::Zero(isolate);
2114   uint64_t needed_length = (n + kDigitBits - 1) / kDigitBits;
2115   uint64_t x_length = static_cast<uint64_t>(x->length());
2116   // If {x} has less than {n} bits, return it directly.
2117   if (x_length < needed_length) return x;
2118   DCHECK_LE(needed_length, kMaxInt);
2119   digit_t top_digit = x->digit(static_cast<int>(needed_length) - 1);
2120   digit_t compare_digit = static_cast<digit_t>(1) << ((n - 1) % kDigitBits);
2121   if (x_length == needed_length && top_digit < compare_digit) return x;
2122   // Otherwise we have to truncate (which is a no-op in the special case
2123   // of x == -2^(n-1)), and determine the right sign. We also might have
2124   // to subtract from 2^n to simulate having two's complement representation.
2125   // In most cases, the result's sign is x->sign() xor "(n-1)th bit present".
2126   // The only exception is when x is negative, has the (n-1)th bit, and all
2127   // its bits below (n-1) are zero. In that case, the result is the minimum
2128   // n-bit integer (example: asIntN(3, -12n) => -4n).
2129   bool has_bit = (top_digit & compare_digit) == compare_digit;
2130   DCHECK_LE(n, kMaxInt);
2131   int N = static_cast<int>(n);
2132   if (!has_bit) {
2133     return MutableBigInt::TruncateToNBits(isolate, N, x);
2134   }
2135   if (!x->sign()) {
2136     return MutableBigInt::TruncateAndSubFromPowerOfTwo(isolate, N, x, true);
2137   }
2138   // Negative numbers must subtract from 2^n, except for the special case
2139   // described above.
2140   if ((top_digit & (compare_digit - 1)) == 0) {
2141     for (int i = static_cast<int>(needed_length) - 2; i >= 0; i--) {
2142       if (x->digit(i) != 0) {
2143         return MutableBigInt::TruncateAndSubFromPowerOfTwo(isolate, N, x,
2144                                                            false);
2145       }
2146     }
2147     return MutableBigInt::TruncateToNBits(isolate, N, x);
2148   }
2149   return MutableBigInt::TruncateAndSubFromPowerOfTwo(isolate, N, x, false);
2150 }
2151 
AsUintN(Isolate * isolate,uint64_t n,Handle<BigInt> x)2152 MaybeHandle<BigInt> BigInt::AsUintN(Isolate* isolate, uint64_t n,
2153                                     Handle<BigInt> x) {
2154   if (x->is_zero()) return x;
2155   if (n == 0) return MutableBigInt::Zero(isolate);
2156   // If {x} is negative, simulate two's complement representation.
2157   if (x->sign()) {
2158     if (n > kMaxLengthBits) {
2159       THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
2160                       BigInt);
2161     }
2162     return MutableBigInt::TruncateAndSubFromPowerOfTwo(
2163         isolate, static_cast<int>(n), x, false);
2164   }
2165   // If {x} is positive and has up to {n} bits, return it directly.
2166   if (n >= kMaxLengthBits) return x;
2167   STATIC_ASSERT(kMaxLengthBits < kMaxInt - kDigitBits);
2168   int needed_length = static_cast<int>((n + kDigitBits - 1) / kDigitBits);
2169   if (x->length() < needed_length) return x;
2170   int bits_in_top_digit = n % kDigitBits;
2171   if (bits_in_top_digit == 0) {
2172     if (x->length() == needed_length) return x;
2173   } else {
2174     digit_t top_digit = x->digit(needed_length - 1);
2175     if ((top_digit >> bits_in_top_digit) == 0) return x;
2176   }
2177   // Otherwise, truncate.
2178   DCHECK_LE(n, kMaxInt);
2179   return MutableBigInt::TruncateToNBits(isolate, static_cast<int>(n), x);
2180 }
2181 
TruncateToNBits(Isolate * isolate,int n,Handle<BigInt> x)2182 Handle<BigInt> MutableBigInt::TruncateToNBits(Isolate* isolate, int n,
2183                                               Handle<BigInt> x) {
2184   // Only call this when there's something to do.
2185   DCHECK_NE(n, 0);
2186   DCHECK_GT(x->length(), n / kDigitBits);
2187 
2188   int needed_digits = (n + (kDigitBits - 1)) / kDigitBits;
2189   DCHECK_LE(needed_digits, x->length());
2190   Handle<MutableBigInt> result = New(isolate, needed_digits).ToHandleChecked();
2191 
2192   // Copy all digits except the MSD.
2193   int last = needed_digits - 1;
2194   for (int i = 0; i < last; i++) {
2195     result->set_digit(i, x->digit(i));
2196   }
2197 
2198   // The MSD might contain extra bits that we don't want.
2199   digit_t msd = x->digit(last);
2200   if (n % kDigitBits != 0) {
2201     int drop = kDigitBits - (n % kDigitBits);
2202     msd = (msd << drop) >> drop;
2203   }
2204   result->set_digit(last, msd);
2205   result->set_sign(x->sign());
2206   return MakeImmutable(result);
2207 }
2208 
2209 // Subtracts the least significant n bits of abs(x) from 2^n.
TruncateAndSubFromPowerOfTwo(Isolate * isolate,int n,Handle<BigInt> x,bool result_sign)2210 Handle<BigInt> MutableBigInt::TruncateAndSubFromPowerOfTwo(Isolate* isolate,
2211                                                            int n,
2212                                                            Handle<BigInt> x,
2213                                                            bool result_sign) {
2214   DCHECK_NE(n, 0);
2215   DCHECK_LE(n, kMaxLengthBits);
2216 
2217   int needed_digits = (n + (kDigitBits - 1)) / kDigitBits;
2218   DCHECK_LE(needed_digits, kMaxLength);  // Follows from n <= kMaxLengthBits.
2219   Handle<MutableBigInt> result = New(isolate, needed_digits).ToHandleChecked();
2220 
2221   // Process all digits except the MSD.
2222   int i = 0;
2223   int last = needed_digits - 1;
2224   int x_length = x->length();
2225   digit_t borrow = 0;
2226   // Take digits from {x} unless its length is exhausted.
2227   int limit = Min(last, x_length);
2228   for (; i < limit; i++) {
2229     digit_t new_borrow = 0;
2230     digit_t difference = digit_sub(0, x->digit(i), &new_borrow);
2231     difference = digit_sub(difference, borrow, &new_borrow);
2232     result->set_digit(i, difference);
2233     borrow = new_borrow;
2234   }
2235   // Then simulate leading zeroes in {x} as needed.
2236   for (; i < last; i++) {
2237     digit_t new_borrow = 0;
2238     digit_t difference = digit_sub(0, borrow, &new_borrow);
2239     result->set_digit(i, difference);
2240     borrow = new_borrow;
2241   }
2242 
2243   // The MSD might contain extra bits that we don't want.
2244   digit_t msd = last < x_length ? x->digit(last) : 0;
2245   int msd_bits_consumed = n % kDigitBits;
2246   digit_t result_msd;
2247   if (msd_bits_consumed == 0) {
2248     digit_t new_borrow = 0;
2249     result_msd = digit_sub(0, msd, &new_borrow);
2250     result_msd = digit_sub(result_msd, borrow, &new_borrow);
2251   } else {
2252     int drop = kDigitBits - msd_bits_consumed;
2253     msd = (msd << drop) >> drop;
2254     digit_t minuend_msd = static_cast<digit_t>(1) << (kDigitBits - drop);
2255     digit_t new_borrow = 0;
2256     result_msd = digit_sub(minuend_msd, msd, &new_borrow);
2257     result_msd = digit_sub(result_msd, borrow, &new_borrow);
2258     DCHECK_EQ(new_borrow, 0);  // result < 2^n.
2259     // If all subtracted bits were zero, we have to get rid of the
2260     // materialized minuend_msd again.
2261     result_msd &= (minuend_msd - 1);
2262   }
2263   result->set_digit(last, result_msd);
2264   result->set_sign(result_sign);
2265   return MakeImmutable(result);
2266 }
2267 
FromInt64(Isolate * isolate,int64_t n)2268 Handle<BigInt> BigInt::FromInt64(Isolate* isolate, int64_t n) {
2269   if (n == 0) return MutableBigInt::Zero(isolate);
2270   STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2271   int length = 64 / kDigitBits;
2272   Handle<MutableBigInt> result =
2273       MutableBigInt::Cast(isolate->factory()->NewBigInt(length));
2274   bool sign = n < 0;
2275   result->initialize_bitfield(sign, length);
2276   uint64_t absolute;
2277   if (!sign) {
2278     absolute = static_cast<uint64_t>(n);
2279   } else {
2280     if (n == std::numeric_limits<int64_t>::min()) {
2281       absolute = static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) + 1;
2282     } else {
2283       absolute = static_cast<uint64_t>(-n);
2284     }
2285   }
2286   result->set_64_bits(absolute);
2287   return MutableBigInt::MakeImmutable(result);
2288 }
2289 
FromUint64(Isolate * isolate,uint64_t n)2290 Handle<BigInt> BigInt::FromUint64(Isolate* isolate, uint64_t n) {
2291   if (n == 0) return MutableBigInt::Zero(isolate);
2292   STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2293   int length = 64 / kDigitBits;
2294   Handle<MutableBigInt> result =
2295       MutableBigInt::Cast(isolate->factory()->NewBigInt(length));
2296   result->initialize_bitfield(false, length);
2297   result->set_64_bits(n);
2298   return MutableBigInt::MakeImmutable(result);
2299 }
2300 
FromWords64(Isolate * isolate,int sign_bit,int words64_count,const uint64_t * words)2301 MaybeHandle<BigInt> BigInt::FromWords64(Isolate* isolate, int sign_bit,
2302                                         int words64_count,
2303                                         const uint64_t* words) {
2304   if (words64_count < 0 || words64_count > kMaxLength / (64 / kDigitBits)) {
2305     THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
2306                     BigInt);
2307   }
2308   if (words64_count == 0) return MutableBigInt::Zero(isolate);
2309   STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2310   int length = (64 / kDigitBits) * words64_count;
2311   DCHECK_GT(length, 0);
2312   if (kDigitBits == 32 && words[words64_count - 1] <= (1ULL << 32)) length--;
2313 
2314   Handle<MutableBigInt> result;
2315   if (!MutableBigInt::New(isolate, length).ToHandle(&result)) {
2316     return MaybeHandle<BigInt>();
2317   }
2318 
2319   result->set_sign(sign_bit);
2320   if (kDigitBits == 64) {
2321     for (int i = 0; i < length; ++i) {
2322       result->set_digit(i, static_cast<digit_t>(words[i]));
2323     }
2324   } else {
2325     for (int i = 0; i < length; i += 2) {
2326       digit_t lo = static_cast<digit_t>(words[i / 2]);
2327       digit_t hi = static_cast<digit_t>(words[i / 2] >> 32);
2328       result->set_digit(i, lo);
2329       if (i + 1 < length) result->set_digit(i + 1, hi);
2330     }
2331   }
2332 
2333   return MutableBigInt::MakeImmutable(result);
2334 }
2335 
Words64Count()2336 int BigInt::Words64Count() {
2337   STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2338   return length() / (64 / kDigitBits) +
2339          (kDigitBits == 32 && length() % 2 == 1 ? 1 : 0);
2340 }
2341 
ToWordsArray64(int * sign_bit,int * words64_count,uint64_t * words)2342 void BigInt::ToWordsArray64(int* sign_bit, int* words64_count,
2343                             uint64_t* words) {
2344   DCHECK_NE(sign_bit, nullptr);
2345   DCHECK_NE(words64_count, nullptr);
2346   *sign_bit = sign();
2347   int available_words = *words64_count;
2348   *words64_count = Words64Count();
2349   if (available_words == 0) return;
2350   DCHECK_NE(words, nullptr);
2351 
2352   int len = length();
2353   if (kDigitBits == 64) {
2354     for (int i = 0; i < len && i < available_words; ++i) words[i] = digit(i);
2355   } else {
2356     for (int i = 0; i < len && available_words > 0; i += 2) {
2357       uint64_t lo = digit(i);
2358       uint64_t hi = (i + 1) < len ? digit(i + 1) : 0;
2359       words[i / 2] = lo | (hi << 32);
2360       available_words--;
2361     }
2362   }
2363 }
2364 
GetRawBits(BigIntBase * x,bool * lossless)2365 uint64_t MutableBigInt::GetRawBits(BigIntBase* x, bool* lossless) {
2366   if (lossless != nullptr) *lossless = true;
2367   if (x->is_zero()) return 0;
2368   int len = x->length();
2369   STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2370   if (lossless != nullptr && len > 64 / kDigitBits) *lossless = false;
2371   uint64_t raw = static_cast<uint64_t>(x->digit(0));
2372   if (kDigitBits == 32 && len > 1) {
2373     raw |= static_cast<uint64_t>(x->digit(1)) << 32;
2374   }
2375   // Simulate two's complement. MSVC dislikes "-raw".
2376   return x->sign() ? ((~raw) + 1u) : raw;
2377 }
2378 
AsInt64(bool * lossless)2379 int64_t BigInt::AsInt64(bool* lossless) {
2380   uint64_t raw = MutableBigInt::GetRawBits(this, lossless);
2381   int64_t result = static_cast<int64_t>(raw);
2382   if (lossless != nullptr && (result < 0) != sign()) *lossless = false;
2383   return result;
2384 }
2385 
AsUint64(bool * lossless)2386 uint64_t BigInt::AsUint64(bool* lossless) {
2387   uint64_t result = MutableBigInt::GetRawBits(this, lossless);
2388   if (lossless != nullptr && sign()) *lossless = false;
2389   return result;
2390 }
2391 
2392 // Digit arithmetic helpers.
2393 
2394 #if V8_TARGET_ARCH_32_BIT
2395 #define HAVE_TWODIGIT_T 1
2396 typedef uint64_t twodigit_t;
2397 #elif defined(__SIZEOF_INT128__)
2398 // Both Clang and GCC support this on x64.
2399 #define HAVE_TWODIGIT_T 1
2400 typedef __uint128_t twodigit_t;
2401 #endif
2402 
2403 // {carry} must point to an initialized digit_t and will either be incremented
2404 // by one or left alone.
digit_add(digit_t a,digit_t b,digit_t * carry)2405 inline BigInt::digit_t MutableBigInt::digit_add(digit_t a, digit_t b,
2406                                                 digit_t* carry) {
2407 #if HAVE_TWODIGIT_T
2408   twodigit_t result = static_cast<twodigit_t>(a) + static_cast<twodigit_t>(b);
2409   *carry += result >> kDigitBits;
2410   return static_cast<digit_t>(result);
2411 #else
2412   digit_t result = a + b;
2413   if (result < a) *carry += 1;
2414   return result;
2415 #endif
2416 }
2417 
2418 // {borrow} must point to an initialized digit_t and will either be incremented
2419 // by one or left alone.
digit_sub(digit_t a,digit_t b,digit_t * borrow)2420 inline BigInt::digit_t MutableBigInt::digit_sub(digit_t a, digit_t b,
2421                                                 digit_t* borrow) {
2422 #if HAVE_TWODIGIT_T
2423   twodigit_t result = static_cast<twodigit_t>(a) - static_cast<twodigit_t>(b);
2424   *borrow += (result >> kDigitBits) & 1;
2425   return static_cast<digit_t>(result);
2426 #else
2427   digit_t result = a - b;
2428   if (result > a) *borrow += 1;
2429   return static_cast<digit_t>(result);
2430 #endif
2431 }
2432 
2433 // Returns the low half of the result. High half is in {high}.
digit_mul(digit_t a,digit_t b,digit_t * high)2434 inline BigInt::digit_t MutableBigInt::digit_mul(digit_t a, digit_t b,
2435                                                 digit_t* high) {
2436 #if HAVE_TWODIGIT_T
2437   twodigit_t result = static_cast<twodigit_t>(a) * static_cast<twodigit_t>(b);
2438   *high = result >> kDigitBits;
2439   return static_cast<digit_t>(result);
2440 #else
2441   // Multiply in half-pointer-sized chunks.
2442   // For inputs [AH AL]*[BH BL], the result is:
2443   //
2444   //            [AL*BL]  // r_low
2445   //    +    [AL*BH]     // r_mid1
2446   //    +    [AH*BL]     // r_mid2
2447   //    + [AH*BH]        // r_high
2448   //    = [R4 R3 R2 R1]  // high = [R4 R3], low = [R2 R1]
2449   //
2450   // Where of course we must be careful with carries between the columns.
2451   digit_t a_low = a & kHalfDigitMask;
2452   digit_t a_high = a >> kHalfDigitBits;
2453   digit_t b_low = b & kHalfDigitMask;
2454   digit_t b_high = b >> kHalfDigitBits;
2455 
2456   digit_t r_low = a_low * b_low;
2457   digit_t r_mid1 = a_low * b_high;
2458   digit_t r_mid2 = a_high * b_low;
2459   digit_t r_high = a_high * b_high;
2460 
2461   digit_t carry = 0;
2462   digit_t low = digit_add(r_low, r_mid1 << kHalfDigitBits, &carry);
2463   low = digit_add(low, r_mid2 << kHalfDigitBits, &carry);
2464   *high =
2465       (r_mid1 >> kHalfDigitBits) + (r_mid2 >> kHalfDigitBits) + r_high + carry;
2466   return low;
2467 #endif
2468 }
2469 
2470 // Returns the quotient.
2471 // quotient = (high << kDigitBits + low - remainder) / divisor
digit_div(digit_t high,digit_t low,digit_t divisor,digit_t * remainder)2472 BigInt::digit_t MutableBigInt::digit_div(digit_t high, digit_t low,
2473                                          digit_t divisor, digit_t* remainder) {
2474   DCHECK(high < divisor);
2475 #if V8_TARGET_ARCH_X64 && (__GNUC__ || __clang__)
2476   digit_t quotient;
2477   digit_t rem;
2478   __asm__("divq  %[divisor]"
2479           // Outputs: {quotient} will be in rax, {rem} in rdx.
2480           : "=a"(quotient), "=d"(rem)
2481           // Inputs: put {high} into rdx, {low} into rax, and {divisor} into
2482           // any register or stack slot.
2483           : "d"(high), "a"(low), [divisor] "rm"(divisor));
2484   *remainder = rem;
2485   return quotient;
2486 #elif V8_TARGET_ARCH_IA32 && (__GNUC__ || __clang__)
2487   digit_t quotient;
2488   digit_t rem;
2489   __asm__("divl  %[divisor]"
2490           // Outputs: {quotient} will be in eax, {rem} in edx.
2491           : "=a"(quotient), "=d"(rem)
2492           // Inputs: put {high} into edx, {low} into eax, and {divisor} into
2493           // any register or stack slot.
2494           : "d"(high), "a"(low), [divisor] "rm"(divisor));
2495   *remainder = rem;
2496   return quotient;
2497 #else
2498   static const digit_t kHalfDigitBase = 1ull << kHalfDigitBits;
2499   // Adapted from Warren, Hacker's Delight, p. 152.
2500   int s = base::bits::CountLeadingZeros(divisor);
2501   DCHECK_NE(s, kDigitBits);  // {divisor} is not 0.
2502   divisor <<= s;
2503 
2504   digit_t vn1 = divisor >> kHalfDigitBits;
2505   digit_t vn0 = divisor & kHalfDigitMask;
2506   // {s} can be 0. {low >> kDigitBits} would be undefined behavior, so
2507   // we mask the shift amount with {kShiftMask}, and the result with
2508   // {s_zero_mask} which is 0 if s == 0 and all 1-bits otherwise.
2509   STATIC_ASSERT(sizeof(intptr_t) == sizeof(digit_t));
2510   const int kShiftMask = kDigitBits - 1;
2511   digit_t s_zero_mask =
2512       static_cast<digit_t>(static_cast<intptr_t>(-s) >> (kDigitBits - 1));
2513   digit_t un32 =
2514       (high << s) | ((low >> ((kDigitBits - s) & kShiftMask)) & s_zero_mask);
2515   digit_t un10 = low << s;
2516   digit_t un1 = un10 >> kHalfDigitBits;
2517   digit_t un0 = un10 & kHalfDigitMask;
2518   digit_t q1 = un32 / vn1;
2519   digit_t rhat = un32 - q1 * vn1;
2520 
2521   while (q1 >= kHalfDigitBase || q1 * vn0 > rhat * kHalfDigitBase + un1) {
2522     q1--;
2523     rhat += vn1;
2524     if (rhat >= kHalfDigitBase) break;
2525   }
2526 
2527   digit_t un21 = un32 * kHalfDigitBase + un1 - q1 * divisor;
2528   digit_t q0 = un21 / vn1;
2529   rhat = un21 - q0 * vn1;
2530 
2531   while (q0 >= kHalfDigitBase || q0 * vn0 > rhat * kHalfDigitBase + un0) {
2532     q0--;
2533     rhat += vn1;
2534     if (rhat >= kHalfDigitBase) break;
2535   }
2536 
2537   *remainder = (un21 * kHalfDigitBase + un0 - q0 * divisor) >> s;
2538   return q1 * kHalfDigitBase + q0;
2539 #endif
2540 }
2541 
2542 // Raises {base} to the power of {exponent}. Does not check for overflow.
digit_pow(digit_t base,digit_t exponent)2543 BigInt::digit_t MutableBigInt::digit_pow(digit_t base, digit_t exponent) {
2544   digit_t result = 1ull;
2545   while (exponent > 0) {
2546     if (exponent & 1) {
2547       result *= base;
2548     }
2549     exponent >>= 1;
2550     base *= base;
2551   }
2552   return result;
2553 }
2554 
2555 #undef HAVE_TWODIGIT_T
2556 
set_64_bits(uint64_t bits)2557 void MutableBigInt::set_64_bits(uint64_t bits) {
2558   STATIC_ASSERT(kDigitBits == 64 || kDigitBits == 32);
2559   if (kDigitBits == 64) {
2560     set_digit(0, static_cast<digit_t>(bits));
2561   } else {
2562     set_digit(0, static_cast<digit_t>(bits & 0xFFFFFFFFu));
2563     set_digit(1, static_cast<digit_t>(bits >> 32));
2564   }
2565 }
2566 
2567 #ifdef OBJECT_PRINT
BigIntPrint(std::ostream & os)2568 void BigInt::BigIntPrint(std::ostream& os) {
2569   DisallowHeapAllocation no_gc;
2570   HeapObject::PrintHeader(os, "BigInt");
2571   int len = length();
2572   os << "\n- length: " << len;
2573   os << "\n- sign: " << sign();
2574   if (len > 0) {
2575     os << "\n- digits:";
2576     for (int i = 0; i < len; i++) {
2577       os << "\n    0x" << std::hex << digit(i);
2578     }
2579   }
2580   os << std::dec << "\n";
2581 }
2582 #endif  // OBJECT_PRINT
2583 
2584 }  // namespace internal
2585 }  // namespace v8
2586