mirrored from https://chromium.googlesource.com/v8/v8.git
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
bigint.cc
2478 lines (2309 loc) · 93.2 KB
/
bigint.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Parts of the implementation below:
// Copyright (c) 2014 the Dart project authors. Please see the AUTHORS file [1]
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file [2].
//
// [1] https://github.com/dart-lang/sdk/blob/master/AUTHORS
// [2] https://github.com/dart-lang/sdk/blob/master/LICENSE
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file [3].
//
// [3] https://golang.org/LICENSE
#include "src/objects/bigint.h"
#include "src/double.h"
#include "src/objects-inl.h"
namespace v8 {
namespace internal {
// The MutableBigInt class is an implementation detail designed to prevent
// accidental mutation of a BigInt after its construction. Step-by-step
// construction of a BigInt must happen in terms of MutableBigInt, the
// final result is then passed through MutableBigInt::MakeImmutable and not
// modified further afterwards.
// Many of the functions in this class use arguments of type {BigIntBase},
// indicating that they will be used in a read-only capacity, and both
// {BigInt} and {MutableBigInt} objects can be passed in.
class MutableBigInt : public FreshlyAllocatedBigInt {
public:
// Bottleneck for converting MutableBigInts to BigInts.
static MaybeHandle<BigInt> MakeImmutable(MaybeHandle<MutableBigInt> maybe);
static Handle<BigInt> MakeImmutable(Handle<MutableBigInt> result);
// Allocation helpers.
static MaybeHandle<MutableBigInt> New(Isolate* isolate, int length,
PretenureFlag pretenure = NOT_TENURED);
static Handle<BigInt> NewFromInt(Isolate* isolate, int value);
static Handle<BigInt> NewFromDouble(Isolate* isolate, double value);
void InitializeDigits(int length, byte value = 0);
static Handle<MutableBigInt> Copy(Handle<BigIntBase> source);
static Handle<BigInt> Zero(Isolate* isolate) {
// TODO(jkummerow): Consider caching a canonical zero-BigInt.
return MakeImmutable(New(isolate, 0)).ToHandleChecked();
}
static Handle<MutableBigInt> Cast(Handle<FreshlyAllocatedBigInt> bigint) {
SLOW_DCHECK(bigint->IsBigInt());
return Handle<MutableBigInt>::cast(bigint);
}
// Internal helpers.
static MaybeHandle<MutableBigInt> BitwiseAnd(Handle<BigInt> x,
Handle<BigInt> y);
static MaybeHandle<MutableBigInt> BitwiseXor(Handle<BigInt> x,
Handle<BigInt> y);
static MaybeHandle<MutableBigInt> BitwiseOr(Handle<BigInt> x,
Handle<BigInt> y);
static Handle<BigInt> TruncateToNBits(int n, Handle<BigInt> x);
static Handle<BigInt> TruncateAndSubFromPowerOfTwo(int n, Handle<BigInt> x,
bool result_sign);
static MaybeHandle<BigInt> AbsoluteAdd(Handle<BigInt> x, Handle<BigInt> y,
bool result_sign);
static Handle<BigInt> AbsoluteSub(Handle<BigInt> x, Handle<BigInt> y,
bool result_sign);
static MaybeHandle<MutableBigInt> AbsoluteAddOne(
Handle<BigIntBase> x, bool sign, MutableBigInt* result_storage = nullptr);
static Handle<MutableBigInt> AbsoluteSubOne(Handle<BigIntBase> x);
static MaybeHandle<MutableBigInt> AbsoluteSubOne(Handle<BigIntBase> x,
int result_length);
enum ExtraDigitsHandling { kCopy, kSkip };
enum SymmetricOp { kSymmetric, kNotSymmetric };
static inline Handle<MutableBigInt> AbsoluteBitwiseOp(
Handle<BigIntBase> x, Handle<BigIntBase> y, MutableBigInt* result_storage,
ExtraDigitsHandling extra_digits, SymmetricOp symmetric,
std::function<digit_t(digit_t, digit_t)> op);
static Handle<MutableBigInt> AbsoluteAnd(
Handle<BigIntBase> x, Handle<BigIntBase> y,
MutableBigInt* result_storage = nullptr);
static Handle<MutableBigInt> AbsoluteAndNot(
Handle<BigIntBase> x, Handle<BigIntBase> y,
MutableBigInt* result_storage = nullptr);
static Handle<MutableBigInt> AbsoluteOr(
Handle<BigIntBase> x, Handle<BigIntBase> y,
MutableBigInt* result_storage = nullptr);
static Handle<MutableBigInt> AbsoluteXor(
Handle<BigIntBase> x, Handle<BigIntBase> y,
MutableBigInt* result_storage = nullptr);
static int AbsoluteCompare(Handle<BigIntBase> x, Handle<BigIntBase> y);
static void MultiplyAccumulate(Handle<BigIntBase> multiplicand,
digit_t multiplier,
Handle<MutableBigInt> accumulator,
int accumulator_index);
static void InternalMultiplyAdd(BigIntBase* source, digit_t factor,
digit_t summand, int n,
MutableBigInt* result);
void InplaceMultiplyAdd(uintptr_t factor, uintptr_t summand);
// Specialized helpers for Divide/Remainder.
static void AbsoluteDivSmall(Handle<BigIntBase> x, digit_t divisor,
Handle<MutableBigInt>* quotient,
digit_t* remainder);
static bool AbsoluteDivLarge(Handle<BigIntBase> dividend,
Handle<BigIntBase> divisor,
Handle<MutableBigInt>* quotient,
Handle<MutableBigInt>* remainder);
static bool ProductGreaterThan(digit_t factor1, digit_t factor2, digit_t high,
digit_t low);
digit_t InplaceAdd(Handle<BigIntBase> summand, int start_index);
digit_t InplaceSub(Handle<BigIntBase> subtrahend, int start_index);
void InplaceRightShift(int shift);
enum SpecialLeftShiftMode {
kSameSizeResult,
kAlwaysAddOneDigit,
};
static MaybeHandle<MutableBigInt> SpecialLeftShift(Handle<BigIntBase> x,
int shift,
SpecialLeftShiftMode mode);
// Specialized helpers for shift operations.
static MaybeHandle<BigInt> LeftShiftByAbsolute(Handle<BigIntBase> x,
Handle<BigIntBase> y);
static Handle<BigInt> RightShiftByAbsolute(Handle<BigIntBase> x,
Handle<BigIntBase> y);
static Handle<BigInt> RightShiftByMaximum(Isolate* isolate, bool sign);
static Maybe<digit_t> ToShiftAmount(Handle<BigIntBase> x);
static MaybeHandle<String> ToStringBasePowerOfTwo(Handle<BigIntBase> x,
int radix);
static MaybeHandle<String> ToStringGeneric(Handle<BigIntBase> x, int radix);
static double ToDouble(Handle<BigIntBase> x);
enum Rounding { kRoundDown, kTie, kRoundUp };
static Rounding DecideRounding(Handle<BigIntBase> x, int mantissa_bits_unset,
int digit_index, uint64_t current_digit);
// Returns the least significant 64 bits, simulating two's complement
// representation.
static uint64_t GetRawBits(BigIntBase* x, bool* lossless);
// Digit arithmetic helpers.
static inline digit_t digit_add(digit_t a, digit_t b, digit_t* carry);
static inline digit_t digit_sub(digit_t a, digit_t b, digit_t* borrow);
static inline digit_t digit_mul(digit_t a, digit_t b, digit_t* high);
static inline digit_t digit_div(digit_t high, digit_t low, digit_t divisor,
digit_t* remainder);
static digit_t digit_pow(digit_t base, digit_t exponent);
static inline bool digit_ismax(digit_t x) {
return static_cast<digit_t>(~x) == 0;
}
// Internal field setters. Non-mutable BigInts don't have these.
#include "src/objects/object-macros.h"
inline void set_sign(bool new_sign) {
intptr_t bitfield = READ_INTPTR_FIELD(this, kBitfieldOffset);
bitfield = SignBits::update(static_cast<uint32_t>(bitfield), new_sign);
WRITE_INTPTR_FIELD(this, kBitfieldOffset, bitfield);
}
inline void set_length(int new_length) {
intptr_t bitfield = READ_INTPTR_FIELD(this, kBitfieldOffset);
bitfield = LengthBits::update(static_cast<uint32_t>(bitfield), new_length);
WRITE_INTPTR_FIELD(this, kBitfieldOffset, bitfield);
}
inline void initialize_bitfield(bool sign, int length) {
intptr_t bitfield = LengthBits::encode(length) | SignBits::encode(sign);
WRITE_INTPTR_FIELD(this, kBitfieldOffset, bitfield);
}
inline void set_digit(int n, digit_t value) {
SLOW_DCHECK(0 <= n && n < length());
Address address = FIELD_ADDR(this, kDigitsOffset + n * kDigitSize);
(*reinterpret_cast<digit_t*>(address)) = value;
}
#include "src/objects/object-macros-undef.h"
void set_64_bits(uint64_t bits);
};
MaybeHandle<MutableBigInt> MutableBigInt::New(Isolate* isolate, int length,
PretenureFlag pretenure) {
if (length > BigInt::kMaxLength) {
THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
MutableBigInt);
}
Handle<MutableBigInt> result =
Cast(isolate->factory()->NewBigInt(length, pretenure));
result->initialize_bitfield(false, length);
#if DEBUG
result->InitializeDigits(length, 0xBF);
#endif
return result;
}
Handle<BigInt> MutableBigInt::NewFromInt(Isolate* isolate, int value) {
if (value == 0) return Zero(isolate);
Handle<MutableBigInt> result = Cast(isolate->factory()->NewBigInt(1));
bool sign = value < 0;
result->initialize_bitfield(sign, 1);
if (!sign) {
result->set_digit(0, value);
} else {
if (value == kMinInt) {
STATIC_ASSERT(kMinInt == -kMaxInt - 1);
result->set_digit(0, static_cast<BigInt::digit_t>(kMaxInt) + 1);
} else {
result->set_digit(0, -value);
}
}
return MakeImmutable(result);
}
Handle<BigInt> MutableBigInt::NewFromDouble(Isolate* isolate, double value) {
DCHECK_EQ(value, std::floor(value));
if (value == 0) return Zero(isolate);
bool sign = value < 0; // -0 was already handled above.
uint64_t double_bits = bit_cast<uint64_t>(value);
int raw_exponent =
static_cast<int>(double_bits >> Double::kPhysicalSignificandSize) & 0x7FF;
DCHECK_NE(raw_exponent, 0x7FF);
DCHECK_GE(raw_exponent, 0x3FF);
int exponent = raw_exponent - 0x3FF;
int digits = exponent / kDigitBits + 1;
Handle<MutableBigInt> result = Cast(isolate->factory()->NewBigInt(digits));
result->initialize_bitfield(sign, digits);
// We construct a BigInt from the double {value} by shifting its mantissa
// according to its exponent and mapping the bit pattern onto digits.
//
// <----------- bitlength = exponent + 1 ----------->
// <----- 52 ------> <------ trailing zeroes ------>
// mantissa: 1yyyyyyyyyyyyyyyyy 0000000000000000000000000000000
// digits: 0001xxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
// <--> <------>
// msd_topbit kDigitBits
//
uint64_t mantissa =
(double_bits & Double::kSignificandMask) | Double::kHiddenBit;
const int kMantissaTopBit = Double::kSignificandSize - 1; // 0-indexed.
// 0-indexed position of most significant bit in the most significant digit.
int msd_topbit = exponent % kDigitBits;
// Number of unused bits in {mantissa}. We'll keep them shifted to the
// left (i.e. most significant part) of the underlying uint64_t.
int remaining_mantissa_bits = 0;
// Next digit under construction.
digit_t digit;
// First, build the MSD by shifting the mantissa appropriately.
if (msd_topbit < kMantissaTopBit) {
remaining_mantissa_bits = kMantissaTopBit - msd_topbit;
digit = mantissa >> remaining_mantissa_bits;
mantissa = mantissa << (64 - remaining_mantissa_bits);
} else {
DCHECK_GE(msd_topbit, kMantissaTopBit);
digit = mantissa << (msd_topbit - kMantissaTopBit);
mantissa = 0;
}
result->set_digit(digits - 1, digit);
// Then fill in the rest of the digits.
for (int digit_index = digits - 2; digit_index >= 0; digit_index--) {
if (remaining_mantissa_bits > 0) {
remaining_mantissa_bits -= kDigitBits;
if (sizeof(digit) == 4) {
digit = mantissa >> 32;
mantissa = mantissa << 32;
} else {
DCHECK_EQ(sizeof(digit), 8);
digit = mantissa;
mantissa = 0;
}
} else {
digit = 0;
}
result->set_digit(digit_index, digit);
}
return MakeImmutable(result);
}
Handle<MutableBigInt> MutableBigInt::Copy(Handle<BigIntBase> source) {
int length = source->length();
// Allocating a BigInt of the same length as an existing BigInt cannot throw.
Handle<MutableBigInt> result =
New(source->GetIsolate(), length).ToHandleChecked();
memcpy(reinterpret_cast<void*>(result->address() + BigIntBase::kHeaderSize),
reinterpret_cast<void*>(source->address() + BigIntBase::kHeaderSize),
BigInt::SizeFor(length) - BigIntBase::kHeaderSize);
return result;
}
void MutableBigInt::InitializeDigits(int length, byte value) {
memset(reinterpret_cast<void*>(reinterpret_cast<Address>(this) +
kDigitsOffset - kHeapObjectTag),
value, length * kDigitSize);
}
MaybeHandle<BigInt> MutableBigInt::MakeImmutable(
MaybeHandle<MutableBigInt> maybe) {
Handle<MutableBigInt> result;
if (!maybe.ToHandle(&result)) return MaybeHandle<BigInt>();
return MakeImmutable(result);
}
Handle<BigInt> MutableBigInt::MakeImmutable(Handle<MutableBigInt> result) {
// Check if we need to right-trim any leading zero-digits.
int old_length = result->length();
int new_length = old_length;
while (new_length > 0 && result->digit(new_length - 1) == 0) new_length--;
int to_trim = old_length - new_length;
if (to_trim != 0) {
int size_delta = to_trim * kDigitSize;
Address new_end = result->address() + BigInt::SizeFor(new_length);
Heap* heap = result->GetHeap();
heap->CreateFillerObjectAt(new_end, size_delta, ClearRecordedSlots::kNo);
result->set_length(new_length);
// Canonicalize -0n.
if (new_length == 0) {
result->set_sign(false);
// TODO(jkummerow): If we cache a canonical 0n, return that here.
}
}
DCHECK_IMPLIES(result->length() > 0,
result->digit(result->length() - 1) != 0); // MSD is non-zero.
return Handle<BigInt>(reinterpret_cast<BigInt**>(result.location()));
}
Handle<BigInt> BigInt::Zero(Isolate* isolate) {
return MutableBigInt::Zero(isolate);
}
Handle<BigInt> BigInt::UnaryMinus(Handle<BigInt> x) {
// Special case: There is no -0n.
if (x->is_zero()) {
return x;
}
Handle<MutableBigInt> result = MutableBigInt::Copy(x);
result->set_sign(!x->sign());
return MutableBigInt::MakeImmutable(result);
}
MaybeHandle<BigInt> BigInt::BitwiseNot(Handle<BigInt> x) {
MaybeHandle<MutableBigInt> result;
if (x->sign()) {
// ~(-x) == ~(~(x-1)) == x-1
result = MutableBigInt::AbsoluteSubOne(x, x->length());
} else {
// ~x == -x-1 == -(x+1)
result = MutableBigInt::AbsoluteAddOne(x, true);
}
return MutableBigInt::MakeImmutable(result);
}
MaybeHandle<BigInt> BigInt::Exponentiate(Handle<BigInt> base,
Handle<BigInt> exponent) {
Isolate* isolate = base->GetIsolate();
// 1. If exponent is < 0, throw a RangeError exception.
if (exponent->sign()) {
THROW_NEW_ERROR(isolate,
NewRangeError(MessageTemplate::kBigIntNegativeExponent),
BigInt);
}
// 2. If base is 0n and exponent is 0n, return 1n.
if (exponent->is_zero()) {
return MutableBigInt::NewFromInt(isolate, 1);
}
// 3. Return a BigInt representing the mathematical value of base raised
// to the power exponent.
if (base->is_zero()) return base;
if (base->length() == 1 && base->digit(0) == 1) {
// (-1) ** even_number == 1.
if (base->sign() && (exponent->digit(0) & 1) == 0) {
return UnaryMinus(base);
}
// (-1) ** odd_number == -1; 1 ** anything == 1.
return base;
}
// For all bases >= 2, very large exponents would lead to unrepresentable
// results.
STATIC_ASSERT(kMaxLengthBits < std::numeric_limits<digit_t>::max());
if (exponent->length() > 1) {
THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
BigInt);
}
digit_t exp_value = exponent->digit(0);
if (exp_value == 1) return base;
if (exp_value >= kMaxLengthBits) {
THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntTooBig),
BigInt);
}
STATIC_ASSERT(kMaxLengthBits <= kMaxInt);
int n = static_cast<int>(exp_value);
if (base->length() == 1 && base->digit(0) == 2) {
// Fast path for 2^n.
int needed_digits = 1 + (n / kDigitBits);
Handle<MutableBigInt> result;
if (!MutableBigInt::New(isolate, needed_digits).ToHandle(&result)) {
return MaybeHandle<BigInt>();
}
result->InitializeDigits(needed_digits);
// All bits are zero. Now set the n-th bit.
digit_t msd = static_cast<digit_t>(1) << (n % kDigitBits);
result->set_digit(needed_digits - 1, msd);
// Result is negative for odd powers of -2n.
if (base->sign()) result->set_sign((n & 1) != 0);
return MutableBigInt::MakeImmutable(result);
}
Handle<BigInt> result;
Handle<BigInt> running_square = base;
// This implicitly sets the result's sign correctly.
if (n & 1) result = base;
n >>= 1;
for (; n != 0; n >>= 1) {
MaybeHandle<BigInt> maybe_result = Multiply(running_square, running_square);
if (!maybe_result.ToHandle(&running_square)) return maybe_result;
if (n & 1) {
if (result.is_null()) {
result = running_square;
} else {
maybe_result = Multiply(result, running_square);
if (!maybe_result.ToHandle(&result)) return maybe_result;
}
}
}
return result;
}
MaybeHandle<BigInt> BigInt::Multiply(Handle<BigInt> x, Handle<BigInt> y) {
if (x->is_zero()) return x;
if (y->is_zero()) return y;
int result_length = x->length() + y->length();
Handle<MutableBigInt> result;
if (!MutableBigInt::New(x->GetIsolate(), result_length).ToHandle(&result)) {
return MaybeHandle<BigInt>();
}
result->InitializeDigits(result_length);
for (int i = 0; i < x->length(); i++) {
MutableBigInt::MultiplyAccumulate(y, x->digit(i), result, i);
}
result->set_sign(x->sign() != y->sign());
return MutableBigInt::MakeImmutable(result);
}
MaybeHandle<BigInt> BigInt::Divide(Handle<BigInt> x, Handle<BigInt> y) {
// 1. If y is 0n, throw a RangeError exception.
if (y->is_zero()) {
THROW_NEW_ERROR(y->GetIsolate(),
NewRangeError(MessageTemplate::kBigIntDivZero), BigInt);
}
// 2. Let quotient be the mathematical value of x divided by y.
// 3. Return a BigInt representing quotient rounded towards 0 to the next
// integral value.
if (MutableBigInt::AbsoluteCompare(x, y) < 0) {
return Zero(x->GetIsolate());
}
Handle<MutableBigInt> quotient;
bool result_sign = x->sign() != y->sign();
if (y->length() == 1) {
digit_t divisor = y->digit(0);
if (divisor == 1) {
return result_sign == x->sign() ? x : UnaryMinus(x);
}
digit_t remainder;
MutableBigInt::AbsoluteDivSmall(x, divisor, "ient, &remainder);
} else {
if (!MutableBigInt::AbsoluteDivLarge(x, y, "ient, nullptr)) {
return MaybeHandle<BigInt>();
}
}
quotient->set_sign(x->sign() != y->sign());
return MutableBigInt::MakeImmutable(quotient);
}
MaybeHandle<BigInt> BigInt::Remainder(Handle<BigInt> x, Handle<BigInt> y) {
Isolate* isolate = x->GetIsolate();
// 1. If y is 0n, throw a RangeError exception.
if (y->is_zero()) {
THROW_NEW_ERROR(isolate, NewRangeError(MessageTemplate::kBigIntDivZero),
BigInt);
}
// 2. Return the BigInt representing x modulo y.
// See https://github.com/tc39/proposal-bigint/issues/84 though.
if (MutableBigInt::AbsoluteCompare(x, y) < 0) return x;
Handle<MutableBigInt> remainder;
if (y->length() == 1) {
digit_t divisor = y->digit(0);
if (divisor == 1) return Zero(isolate);
digit_t remainder_digit;
MutableBigInt::AbsoluteDivSmall(x, divisor, nullptr, &remainder_digit);
if (remainder_digit == 0) {
return Zero(isolate);
}
remainder = MutableBigInt::New(isolate, 1).ToHandleChecked();
remainder->set_digit(0, remainder_digit);
} else {
if (!MutableBigInt::AbsoluteDivLarge(x, y, nullptr, &remainder)) {
return MaybeHandle<BigInt>();
}
}
remainder->set_sign(x->sign());
return MutableBigInt::MakeImmutable(remainder);
}
MaybeHandle<BigInt> BigInt::Add(Handle<BigInt> x, Handle<BigInt> y) {
bool xsign = x->sign();
if (xsign == y->sign()) {
// x + y == x + y
// -x + -y == -(x + y)
return MutableBigInt::AbsoluteAdd(x, y, xsign);
}
// x + -y == x - y == -(y - x)
// -x + y == y - x == -(x - y)
if (MutableBigInt::AbsoluteCompare(x, y) >= 0) {
return MutableBigInt::AbsoluteSub(x, y, xsign);
}
return MutableBigInt::AbsoluteSub(y, x, !xsign);
}
MaybeHandle<BigInt> BigInt::Subtract(Handle<BigInt> x, Handle<BigInt> y) {
bool xsign = x->sign();
if (xsign != y->sign()) {
// x - (-y) == x + y
// (-x) - y == -(x + y)
return MutableBigInt::AbsoluteAdd(x, y, xsign);
}
// x - y == -(y - x)
// (-x) - (-y) == y - x == -(x - y)
if (MutableBigInt::AbsoluteCompare(x, y) >= 0) {
return MutableBigInt::AbsoluteSub(x, y, xsign);
}
return MutableBigInt::AbsoluteSub(y, x, !xsign);
}
MaybeHandle<BigInt> BigInt::LeftShift(Handle<BigInt> x, Handle<BigInt> y) {
if (y->is_zero() || x->is_zero()) return x;
if (y->sign()) return MutableBigInt::RightShiftByAbsolute(x, y);
return MutableBigInt::LeftShiftByAbsolute(x, y);
}
MaybeHandle<BigInt> BigInt::SignedRightShift(Handle<BigInt> x,
Handle<BigInt> y) {
if (y->is_zero() || x->is_zero()) return x;
if (y->sign()) return MutableBigInt::LeftShiftByAbsolute(x, y);
return MutableBigInt::RightShiftByAbsolute(x, y);
}
MaybeHandle<BigInt> BigInt::UnsignedRightShift(Handle<BigInt> x,
Handle<BigInt> y) {
THROW_NEW_ERROR(x->GetIsolate(), NewTypeError(MessageTemplate::kBigIntShr),
BigInt);
}
namespace {
// Produces comparison result for {left_negative} == sign(x) != sign(y).
ComparisonResult UnequalSign(bool left_negative) {
return left_negative ? ComparisonResult::kLessThan
: ComparisonResult::kGreaterThan;
}
// Produces result for |x| > |y|, with {both_negative} == sign(x) == sign(y);
ComparisonResult AbsoluteGreater(bool both_negative) {
return both_negative ? ComparisonResult::kLessThan
: ComparisonResult::kGreaterThan;
}
// Produces result for |x| < |y|, with {both_negative} == sign(x) == sign(y).
ComparisonResult AbsoluteLess(bool both_negative) {
return both_negative ? ComparisonResult::kGreaterThan
: ComparisonResult::kLessThan;
}
} // namespace
// (Never returns kUndefined.)
ComparisonResult BigInt::CompareToBigInt(Handle<BigInt> x, Handle<BigInt> y) {
bool x_sign = x->sign();
if (x_sign != y->sign()) return UnequalSign(x_sign);
int result = MutableBigInt::AbsoluteCompare(x, y);
if (result > 0) return AbsoluteGreater(x_sign);
if (result < 0) return AbsoluteLess(x_sign);
return ComparisonResult::kEqual;
}
bool BigInt::EqualToBigInt(BigInt* x, BigInt* y) {
if (x->sign() != y->sign()) return false;
if (x->length() != y->length()) return false;
for (int i = 0; i < x->length(); i++) {
if (x->digit(i) != y->digit(i)) return false;
}
return true;
}
MaybeHandle<BigInt> BigInt::BitwiseAnd(Handle<BigInt> x, Handle<BigInt> y) {
return MutableBigInt::MakeImmutable(MutableBigInt::BitwiseAnd(x, y));
}
MaybeHandle<MutableBigInt> MutableBigInt::BitwiseAnd(Handle<BigInt> x,
Handle<BigInt> y) {
if (!x->sign() && !y->sign()) {
return AbsoluteAnd(x, y);
} else if (x->sign() && y->sign()) {
int result_length = Max(x->length(), y->length()) + 1;
// (-x) & (-y) == ~(x-1) & ~(y-1) == ~((x-1) | (y-1))
// == -(((x-1) | (y-1)) + 1)
Handle<MutableBigInt> result;
if (!AbsoluteSubOne(x, result_length).ToHandle(&result)) {
return MaybeHandle<MutableBigInt>();
}
Handle<MutableBigInt> y_1 = AbsoluteSubOne(y);
result = AbsoluteOr(result, y_1, *result);
return AbsoluteAddOne(result, true, *result);
} else {
DCHECK(x->sign() != y->sign());
// Assume that x is the positive BigInt.
if (x->sign()) std::swap(x, y);
// x & (-y) == x & ~(y-1) == x &~ (y-1)
return AbsoluteAndNot(x, AbsoluteSubOne(y));
}
}
MaybeHandle<BigInt> BigInt::BitwiseXor(Handle<BigInt> x, Handle<BigInt> y) {
return MutableBigInt::MakeImmutable(MutableBigInt::BitwiseXor(x, y));
}
MaybeHandle<MutableBigInt> MutableBigInt::BitwiseXor(Handle<BigInt> x,
Handle<BigInt> y) {
if (!x->sign() && !y->sign()) {
return AbsoluteXor(x, y);
} else if (x->sign() && y->sign()) {
int result_length = Max(x->length(), y->length());
// (-x) ^ (-y) == ~(x-1) ^ ~(y-1) == (x-1) ^ (y-1)
Handle<MutableBigInt> result =
AbsoluteSubOne(x, result_length).ToHandleChecked();
Handle<MutableBigInt> y_1 = AbsoluteSubOne(y);
return AbsoluteXor(result, y_1, *result);
} else {
DCHECK(x->sign() != y->sign());
int result_length = Max(x->length(), y->length()) + 1;
// Assume that x is the positive BigInt.
if (x->sign()) std::swap(x, y);
// x ^ (-y) == x ^ ~(y-1) == ~(x ^ (y-1)) == -((x ^ (y-1)) + 1)
Handle<MutableBigInt> result;
if (!AbsoluteSubOne(y, result_length).ToHandle(&result)) {
return MaybeHandle<MutableBigInt>();
}
result = AbsoluteXor(result, x, *result);
return AbsoluteAddOne(result, true, *result);
}
}
MaybeHandle<BigInt> BigInt::BitwiseOr(Handle<BigInt> x, Handle<BigInt> y) {
return MutableBigInt::MakeImmutable(MutableBigInt::BitwiseOr(x, y));
}
MaybeHandle<MutableBigInt> MutableBigInt::BitwiseOr(Handle<BigInt> x,
Handle<BigInt> y) {
int result_length = Max(x->length(), y->length());
if (!x->sign() && !y->sign()) {
return AbsoluteOr(x, y);
} else if (x->sign() && y->sign()) {
// (-x) | (-y) == ~(x-1) | ~(y-1) == ~((x-1) & (y-1))
// == -(((x-1) & (y-1)) + 1)
Handle<MutableBigInt> result =
AbsoluteSubOne(x, result_length).ToHandleChecked();
Handle<MutableBigInt> y_1 = AbsoluteSubOne(y);
result = AbsoluteAnd(result, y_1, *result);
return AbsoluteAddOne(result, true, *result);
} else {
DCHECK(x->sign() != y->sign());
// Assume that x is the positive BigInt.
if (x->sign()) std::swap(x, y);
// x | (-y) == x | ~(y-1) == ~((y-1) &~ x) == -(((y-1) &~ x) + 1)
Handle<MutableBigInt> result =
AbsoluteSubOne(y, result_length).ToHandleChecked();
result = AbsoluteAndNot(result, x, *result);
return AbsoluteAddOne(result, true, *result);
}
}
MaybeHandle<BigInt> BigInt::Increment(Handle<BigInt> x) {
if (x->sign()) {
Handle<MutableBigInt> result = MutableBigInt::AbsoluteSubOne(x);
result->set_sign(true);
return MutableBigInt::MakeImmutable(result);
} else {
return MutableBigInt::MakeImmutable(
MutableBigInt::AbsoluteAddOne(x, false));
}
}
MaybeHandle<BigInt> BigInt::Decrement(Handle<BigInt> x) {
MaybeHandle<MutableBigInt> result;
if (x->sign()) {
result = MutableBigInt::AbsoluteAddOne(x, true);
} else if (x->is_zero()) {
// TODO(jkummerow): Consider caching a canonical -1n BigInt.
return MutableBigInt::NewFromInt(x->GetIsolate(), -1);
} else {
result = MutableBigInt::AbsoluteSubOne(x);
}
return MutableBigInt::MakeImmutable(result);
}
ComparisonResult BigInt::CompareToString(Handle<BigInt> x, Handle<String> y) {
Isolate* isolate = x->GetIsolate();
// a. Let ny be StringToBigInt(y);
MaybeHandle<BigInt> maybe_ny = StringToBigInt(isolate, y);
// b. If ny is NaN, return undefined.
Handle<BigInt> ny;
if (!maybe_ny.ToHandle(&ny)) {
DCHECK(!isolate->has_pending_exception());
return ComparisonResult::kUndefined;
}
// c. Return BigInt::lessThan(x, ny).
return CompareToBigInt(x, ny);
}
bool BigInt::EqualToString(Handle<BigInt> x, Handle<String> y) {
Isolate* isolate = x->GetIsolate();
// a. Let n be StringToBigInt(y).
MaybeHandle<BigInt> maybe_n = StringToBigInt(isolate, y);
// b. If n is NaN, return false.
Handle<BigInt> n;
if (!maybe_n.ToHandle(&n)) {
DCHECK(!isolate->has_pending_exception());
return false;
}
// c. Return the result of x == n.
return EqualToBigInt(*x, *n);
}
bool BigInt::EqualToNumber(Handle<BigInt> x, Handle<Object> y) {
DCHECK(y->IsNumber());
// a. If x or y are any of NaN, +∞, or -∞, return false.
// b. If the mathematical value of x is equal to the mathematical value of y,
// return true, otherwise return false.
if (y->IsSmi()) {
int value = Smi::ToInt(*y);
if (value == 0) return x->is_zero();
// Any multi-digit BigInt is bigger than a Smi.
STATIC_ASSERT(sizeof(digit_t) >= sizeof(value));
return (x->length() == 1) && (x->sign() == (value < 0)) &&
(x->digit(0) ==
static_cast<digit_t>(std::abs(static_cast<int64_t>(value))));
}
DCHECK(y->IsHeapNumber());
double value = Handle<HeapNumber>::cast(y)->value();
return CompareToDouble(x, value) == ComparisonResult::kEqual;
}
ComparisonResult BigInt::CompareToNumber(Handle<BigInt> x, Handle<Object> y) {
DCHECK(y->IsNumber());
if (y->IsSmi()) {
bool x_sign = x->sign();
int y_value = Smi::ToInt(*y);
bool y_sign = (y_value < 0);
if (x_sign != y_sign) return UnequalSign(x_sign);
if (x->is_zero()) {
DCHECK(!y_sign);
return y_value == 0 ? ComparisonResult::kEqual
: ComparisonResult::kLessThan;
}
// Any multi-digit BigInt is bigger than a Smi.
STATIC_ASSERT(sizeof(digit_t) >= sizeof(y_value));
if (x->length() > 1) return AbsoluteGreater(x_sign);
digit_t abs_value = std::abs(static_cast<int64_t>(y_value));
digit_t x_digit = x->digit(0);
if (x_digit > abs_value) return AbsoluteGreater(x_sign);
if (x_digit < abs_value) return AbsoluteLess(x_sign);
return ComparisonResult::kEqual;
}
DCHECK(y->IsHeapNumber());
double value = Handle<HeapNumber>::cast(y)->value();
return CompareToDouble(x, value);
}
ComparisonResult BigInt::CompareToDouble(Handle<BigInt> x, double y) {
if (std::isnan(y)) return ComparisonResult::kUndefined;
if (y == V8_INFINITY) return ComparisonResult::kLessThan;
if (y == -V8_INFINITY) return ComparisonResult::kGreaterThan;
bool x_sign = x->sign();
// Note that this is different from the double's sign bit for -0. That's
// intentional because -0 must be treated like 0.
bool y_sign = (y < 0);
if (x_sign != y_sign) return UnequalSign(x_sign);
if (y == 0) {
DCHECK(!x_sign);
return x->is_zero() ? ComparisonResult::kEqual
: ComparisonResult::kGreaterThan;
}
if (x->is_zero()) {
DCHECK(!y_sign);
return ComparisonResult::kLessThan;
}
uint64_t double_bits = bit_cast<uint64_t>(y);
int raw_exponent =
static_cast<int>(double_bits >> Double::kPhysicalSignificandSize) & 0x7FF;
uint64_t mantissa = double_bits & Double::kSignificandMask;
// Non-finite doubles are handled above.
DCHECK_NE(raw_exponent, 0x7FF);
int exponent = raw_exponent - 0x3FF;
if (exponent < 0) {
// The absolute value of the double is less than 1. Only 0n has an
// absolute value smaller than that, but we've already covered that case.
DCHECK(!x->is_zero());
return AbsoluteGreater(x_sign);
}
int x_length = x->length();
digit_t x_msd = x->digit(x_length - 1);
int msd_leading_zeros = base::bits::CountLeadingZeros(x_msd);
int x_bitlength = x_length * kDigitBits - msd_leading_zeros;
int y_bitlength = exponent + 1;
if (x_bitlength < y_bitlength) return AbsoluteLess(x_sign);
if (x_bitlength > y_bitlength) return AbsoluteGreater(x_sign);
// At this point, we know that signs and bit lengths (i.e. position of
// the most significant bit in exponent-free representation) are identical.
// {x} is not zero, {y} is finite and not denormal.
// Now we virtually convert the double to an integer by shifting its
// mantissa according to its exponent, so it will align with the BigInt {x},
// and then we compare them bit for bit until we find a difference or the
// least significant bit.
// <----- 52 ------> <-- virtual trailing zeroes -->
// y / mantissa: 1yyyyyyyyyyyyyyyyy 0000000000000000000000000000000
// x / digits: 0001xxxx xxxxxxxx xxxxxxxx ...
// <--> <------>
// msd_topbit kDigitBits
//
mantissa |= Double::kHiddenBit;
const int kMantissaTopBit = 52; // 0-indexed.
// 0-indexed position of {x}'s most significant bit within the {msd}.
int msd_topbit = kDigitBits - 1 - msd_leading_zeros;
DCHECK_EQ(msd_topbit, (x_bitlength - 1) % kDigitBits);
// Shifted chunk of {mantissa} for comparing with {digit}.
digit_t compare_mantissa;
// Number of unprocessed bits in {mantissa}. We'll keep them shifted to
// the left (i.e. most significant part) of the underlying uint64_t.
int remaining_mantissa_bits = 0;
// First, compare the most significant digit against the beginning of
// the mantissa.
if (msd_topbit < kMantissaTopBit) {
remaining_mantissa_bits = (kMantissaTopBit - msd_topbit);
compare_mantissa = mantissa >> remaining_mantissa_bits;
mantissa = mantissa << (64 - remaining_mantissa_bits);
} else {
DCHECK_GE(msd_topbit, kMantissaTopBit);
compare_mantissa = mantissa << (msd_topbit - kMantissaTopBit);
mantissa = 0;
}
if (x_msd > compare_mantissa) return AbsoluteGreater(x_sign);
if (x_msd < compare_mantissa) return AbsoluteLess(x_sign);
// Then, compare additional digits against any remaining mantissa bits.
for (int digit_index = x_length - 2; digit_index >= 0; digit_index--) {
if (remaining_mantissa_bits > 0) {
remaining_mantissa_bits -= kDigitBits;
if (sizeof(mantissa) != sizeof(x_msd)) {
compare_mantissa = mantissa >> (64 - kDigitBits);
// "& 63" to appease compilers. kDigitBits is 32 here anyway.
mantissa = mantissa << (kDigitBits & 63);
} else {
compare_mantissa = mantissa;
mantissa = 0;
}
} else {
compare_mantissa = 0;
}
digit_t digit = x->digit(digit_index);
if (digit > compare_mantissa) return AbsoluteGreater(x_sign);
if (digit < compare_mantissa) return AbsoluteLess(x_sign);
}
// Integer parts are equal; check whether {y} has a fractional part.
if (mantissa != 0) {
DCHECK_GT(remaining_mantissa_bits, 0);
return AbsoluteLess(x_sign);
}
return ComparisonResult::kEqual;
}
MaybeHandle<String> BigInt::ToString(Handle<BigInt> bigint, int radix) {
Isolate* isolate = bigint->GetIsolate();
if (bigint->is_zero()) {
return isolate->factory()->NewStringFromStaticChars("0");
}
if (base::bits::IsPowerOfTwo(radix)) {
return MutableBigInt::ToStringBasePowerOfTwo(bigint, radix);
}
return MutableBigInt::ToStringGeneric(bigint, radix);
}
MaybeHandle<BigInt> BigInt::FromNumber(Isolate* isolate,
Handle<Object> number) {
DCHECK(number->IsNumber());
if (number->IsSmi()) {
return MutableBigInt::NewFromInt(isolate, Smi::ToInt(*number));
}
double value = HeapNumber::cast(*number)->value();
if (!std::isfinite(value) || (DoubleToInteger(value) != value)) {
THROW_NEW_ERROR(isolate,
NewRangeError(MessageTemplate::kBigIntFromNumber, number),
BigInt);
}
return MutableBigInt::NewFromDouble(isolate, value);
}
MaybeHandle<BigInt> BigInt::FromObject(Isolate* isolate, Handle<Object> obj) {
if (obj->IsJSReceiver()) {
ASSIGN_RETURN_ON_EXCEPTION(
isolate, obj,
JSReceiver::ToPrimitive(Handle<JSReceiver>::cast(obj),
ToPrimitiveHint::kNumber),
BigInt);
}
if (obj->IsBoolean()) {
return MutableBigInt::NewFromInt(isolate, obj->BooleanValue());
}
if (obj->IsBigInt()) {
return Handle<BigInt>::cast(obj);
}
if (obj->IsString()) {
Handle<BigInt> n;
if (!StringToBigInt(isolate, Handle<String>::cast(obj)).ToHandle(&n)) {
THROW_NEW_ERROR(isolate,
NewSyntaxError(MessageTemplate::kBigIntFromObject, obj),
BigInt);
}
return n;
}
THROW_NEW_ERROR(
isolate, NewTypeError(MessageTemplate::kBigIntFromObject, obj), BigInt);
}
Handle<Object> BigInt::ToNumber(Handle<BigInt> x) {
Isolate* isolate = x->GetIsolate();
if (x->is_zero()) return Handle<Smi>(Smi::kZero, isolate);
if (x->length() == 1 && x->digit(0) < Smi::kMaxValue) {
int value = static_cast<int>(x->digit(0));
if (x->sign()) value = -value;
return Handle<Smi>(Smi::FromInt(value), isolate);
}
double result = MutableBigInt::ToDouble(x);
return isolate->factory()->NewHeapNumber(result);
}
double MutableBigInt::ToDouble(Handle<BigIntBase> x) {
if (x->is_zero()) return 0.0;
int x_length = x->length();
digit_t x_msd = x->digit(x_length - 1);
int msd_leading_zeros = base::bits::CountLeadingZeros(x_msd);
int x_bitlength = x_length * kDigitBits - msd_leading_zeros;
if (x_bitlength > 1024) return x->sign() ? -V8_INFINITY : V8_INFINITY;
uint64_t exponent = x_bitlength - 1;
// We need the most significant bit shifted to the position of a double's
// "hidden bit". We also need to hide that MSB, so we shift it out.
uint64_t current_digit = x_msd;
int digit_index = x_length - 1;
int shift = msd_leading_zeros + 1 + (64 - kDigitBits);
DCHECK_LE(1, shift);
DCHECK_LE(shift, 64);
uint64_t mantissa = (shift == 64) ? 0 : current_digit << shift;
mantissa >>= 12;
int mantissa_bits_unset = shift - 12;
// If not all mantissa bits are defined yet, get more digits as needed.
if (mantissa_bits_unset >= kDigitBits && digit_index > 0) {
digit_index--;
current_digit = static_cast<uint64_t>(x->digit(digit_index));
mantissa |= (current_digit << (mantissa_bits_unset - kDigitBits));
mantissa_bits_unset -= kDigitBits;
}
if (mantissa_bits_unset > 0 && digit_index > 0) {
DCHECK_LT(mantissa_bits_unset, kDigitBits);
digit_index--;
current_digit = static_cast<uint64_t>(x->digit(digit_index));
mantissa |= (current_digit >> (kDigitBits - mantissa_bits_unset));
mantissa_bits_unset -= kDigitBits;
}
// If there are unconsumed digits left, we may have to round.
Rounding rounding =
DecideRounding(x, mantissa_bits_unset, digit_index, current_digit);
if (rounding == kRoundUp || (rounding == kTie && (mantissa & 1) == 1)) {
mantissa++;
// Incrementing the mantissa can overflow the mantissa bits. In that case