Home | History | Annotate | Download | only in src
      1 // Copyright 2012 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 #include <stdarg.h>
      6 #include <cmath>
      7 
      8 #include "src/globals.h"
      9 #include "src/utils.h"
     10 #include "src/strtod.h"
     11 #include "src/bignum.h"
     12 #include "src/cached-powers.h"
     13 #include "src/double.h"
     14 
     15 namespace v8 {
     16 namespace internal {
     17 
     18 // 2^53 = 9007199254740992.
     19 // Any integer with at most 15 decimal digits will hence fit into a double
     20 // (which has a 53bit significand) without loss of precision.
     21 static const int kMaxExactDoubleIntegerDecimalDigits = 15;
     22 // 2^64 = 18446744073709551616 > 10^19
     23 static const int kMaxUint64DecimalDigits = 19;
     24 
     25 // Max double: 1.7976931348623157 x 10^308
     26 // Min non-zero double: 4.9406564584124654 x 10^-324
     27 // Any x >= 10^309 is interpreted as +infinity.
     28 // Any x <= 10^-324 is interpreted as 0.
     29 // Note that 2.5e-324 (despite being smaller than the min double) will be read
     30 // as non-zero (equal to the min non-zero double).
     31 static const int kMaxDecimalPower = 309;
     32 static const int kMinDecimalPower = -324;
     33 
     34 // 2^64 = 18446744073709551616
     35 static const uint64_t kMaxUint64 = V8_2PART_UINT64_C(0xFFFFFFFF, FFFFFFFF);
     36 
     37 
     38 static const double exact_powers_of_ten[] = {
     39   1.0,  // 10^0
     40   10.0,
     41   100.0,
     42   1000.0,
     43   10000.0,
     44   100000.0,
     45   1000000.0,
     46   10000000.0,
     47   100000000.0,
     48   1000000000.0,
     49   10000000000.0,  // 10^10
     50   100000000000.0,
     51   1000000000000.0,
     52   10000000000000.0,
     53   100000000000000.0,
     54   1000000000000000.0,
     55   10000000000000000.0,
     56   100000000000000000.0,
     57   1000000000000000000.0,
     58   10000000000000000000.0,
     59   100000000000000000000.0,  // 10^20
     60   1000000000000000000000.0,
     61   // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
     62   10000000000000000000000.0
     63 };
     64 static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten);
     65 
     66 // Maximum number of significant digits in the decimal representation.
     67 // In fact the value is 772 (see conversions.cc), but to give us some margin
     68 // we round up to 780.
     69 static const int kMaxSignificantDecimalDigits = 780;
     70 
     71 static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) {
     72   for (int i = 0; i < buffer.length(); i++) {
     73     if (buffer[i] != '0') {
     74       return buffer.SubVector(i, buffer.length());
     75     }
     76   }
     77   return Vector<const char>(buffer.start(), 0);
     78 }
     79 
     80 
     81 static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) {
     82   for (int i = buffer.length() - 1; i >= 0; --i) {
     83     if (buffer[i] != '0') {
     84       return buffer.SubVector(0, i + 1);
     85     }
     86   }
     87   return Vector<const char>(buffer.start(), 0);
     88 }
     89 
     90 
     91 static void TrimToMaxSignificantDigits(Vector<const char> buffer,
     92                                        int exponent,
     93                                        char* significant_buffer,
     94                                        int* significant_exponent) {
     95   for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) {
     96     significant_buffer[i] = buffer[i];
     97   }
     98   // The input buffer has been trimmed. Therefore the last digit must be
     99   // different from '0'.
    100   ASSERT(buffer[buffer.length() - 1] != '0');
    101   // Set the last digit to be non-zero. This is sufficient to guarantee
    102   // correct rounding.
    103   significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
    104   *significant_exponent =
    105       exponent + (buffer.length() - kMaxSignificantDecimalDigits);
    106 }
    107 
    108 
    109 // Reads digits from the buffer and converts them to a uint64.
    110 // Reads in as many digits as fit into a uint64.
    111 // When the string starts with "1844674407370955161" no further digit is read.
    112 // Since 2^64 = 18446744073709551616 it would still be possible read another
    113 // digit if it was less or equal than 6, but this would complicate the code.
    114 static uint64_t ReadUint64(Vector<const char> buffer,
    115                            int* number_of_read_digits) {
    116   uint64_t result = 0;
    117   int i = 0;
    118   while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
    119     int digit = buffer[i++] - '0';
    120     ASSERT(0 <= digit && digit <= 9);
    121     result = 10 * result + digit;
    122   }
    123   *number_of_read_digits = i;
    124   return result;
    125 }
    126 
    127 
    128 // Reads a DiyFp from the buffer.
    129 // The returned DiyFp is not necessarily normalized.
    130 // If remaining_decimals is zero then the returned DiyFp is accurate.
    131 // Otherwise it has been rounded and has error of at most 1/2 ulp.
    132 static void ReadDiyFp(Vector<const char> buffer,
    133                       DiyFp* result,
    134                       int* remaining_decimals) {
    135   int read_digits;
    136   uint64_t significand = ReadUint64(buffer, &read_digits);
    137   if (buffer.length() == read_digits) {
    138     *result = DiyFp(significand, 0);
    139     *remaining_decimals = 0;
    140   } else {
    141     // Round the significand.
    142     if (buffer[read_digits] >= '5') {
    143       significand++;
    144     }
    145     // Compute the binary exponent.
    146     int exponent = 0;
    147     *result = DiyFp(significand, exponent);
    148     *remaining_decimals = buffer.length() - read_digits;
    149   }
    150 }
    151 
    152 
    153 static bool DoubleStrtod(Vector<const char> trimmed,
    154                          int exponent,
    155                          double* result) {
    156 #if (V8_TARGET_ARCH_IA32 || V8_TARGET_ARCH_X87 || defined(USE_SIMULATOR)) && \
    157     !defined(_MSC_VER)
    158   // On x86 the floating-point stack can be 64 or 80 bits wide. If it is
    159   // 80 bits wide (as is the case on Linux) then double-rounding occurs and the
    160   // result is not accurate.
    161   // We know that Windows32 with MSVC, unlike with MinGW32, uses 64 bits and is
    162   // therefore accurate.
    163   // Note that the ARM and MIPS simulators are compiled for 32bits. They
    164   // therefore exhibit the same problem.
    165   return false;
    166 #endif
    167   if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
    168     int read_digits;
    169     // The trimmed input fits into a double.
    170     // If the 10^exponent (resp. 10^-exponent) fits into a double too then we
    171     // can compute the result-double simply by multiplying (resp. dividing) the
    172     // two numbers.
    173     // This is possible because IEEE guarantees that floating-point operations
    174     // return the best possible approximation.
    175     if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
    176       // 10^-exponent fits into a double.
    177       *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
    178       ASSERT(read_digits == trimmed.length());
    179       *result /= exact_powers_of_ten[-exponent];
    180       return true;
    181     }
    182     if (0 <= exponent && exponent < kExactPowersOfTenSize) {
    183       // 10^exponent fits into a double.
    184       *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
    185       ASSERT(read_digits == trimmed.length());
    186       *result *= exact_powers_of_ten[exponent];
    187       return true;
    188     }
    189     int remaining_digits =
    190         kMaxExactDoubleIntegerDecimalDigits - trimmed.length();
    191     if ((0 <= exponent) &&
    192         (exponent - remaining_digits < kExactPowersOfTenSize)) {
    193       // The trimmed string was short and we can multiply it with
    194       // 10^remaining_digits. As a result the remaining exponent now fits
    195       // into a double too.
    196       *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
    197       ASSERT(read_digits == trimmed.length());
    198       *result *= exact_powers_of_ten[remaining_digits];
    199       *result *= exact_powers_of_ten[exponent - remaining_digits];
    200       return true;
    201     }
    202   }
    203   return false;
    204 }
    205 
    206 
    207 // Returns 10^exponent as an exact DiyFp.
    208 // The given exponent must be in the range [1; kDecimalExponentDistance[.
    209 static DiyFp AdjustmentPowerOfTen(int exponent) {
    210   ASSERT(0 < exponent);
    211   ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
    212   // Simply hardcode the remaining powers for the given decimal exponent
    213   // distance.
    214   ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
    215   switch (exponent) {
    216     case 1: return DiyFp(V8_2PART_UINT64_C(0xa0000000, 00000000), -60);
    217     case 2: return DiyFp(V8_2PART_UINT64_C(0xc8000000, 00000000), -57);
    218     case 3: return DiyFp(V8_2PART_UINT64_C(0xfa000000, 00000000), -54);
    219     case 4: return DiyFp(V8_2PART_UINT64_C(0x9c400000, 00000000), -50);
    220     case 5: return DiyFp(V8_2PART_UINT64_C(0xc3500000, 00000000), -47);
    221     case 6: return DiyFp(V8_2PART_UINT64_C(0xf4240000, 00000000), -44);
    222     case 7: return DiyFp(V8_2PART_UINT64_C(0x98968000, 00000000), -40);
    223     default:
    224       UNREACHABLE();
    225       return DiyFp(0, 0);
    226   }
    227 }
    228 
    229 
    230 // If the function returns true then the result is the correct double.
    231 // Otherwise it is either the correct double or the double that is just below
    232 // the correct double.
    233 static bool DiyFpStrtod(Vector<const char> buffer,
    234                         int exponent,
    235                         double* result) {
    236   DiyFp input;
    237   int remaining_decimals;
    238   ReadDiyFp(buffer, &input, &remaining_decimals);
    239   // Since we may have dropped some digits the input is not accurate.
    240   // If remaining_decimals is different than 0 than the error is at most
    241   // .5 ulp (unit in the last place).
    242   // We don't want to deal with fractions and therefore keep a common
    243   // denominator.
    244   const int kDenominatorLog = 3;
    245   const int kDenominator = 1 << kDenominatorLog;
    246   // Move the remaining decimals into the exponent.
    247   exponent += remaining_decimals;
    248   int error = (remaining_decimals == 0 ? 0 : kDenominator / 2);
    249 
    250   int old_e = input.e();
    251   input.Normalize();
    252   error <<= old_e - input.e();
    253 
    254   ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
    255   if (exponent < PowersOfTenCache::kMinDecimalExponent) {
    256     *result = 0.0;
    257     return true;
    258   }
    259   DiyFp cached_power;
    260   int cached_decimal_exponent;
    261   PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent,
    262                                                      &cached_power,
    263                                                      &cached_decimal_exponent);
    264 
    265   if (cached_decimal_exponent != exponent) {
    266     int adjustment_exponent = exponent - cached_decimal_exponent;
    267     DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent);
    268     input.Multiply(adjustment_power);
    269     if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
    270       // The product of input with the adjustment power fits into a 64 bit
    271       // integer.
    272       ASSERT(DiyFp::kSignificandSize == 64);
    273     } else {
    274       // The adjustment power is exact. There is hence only an error of 0.5.
    275       error += kDenominator / 2;
    276     }
    277   }
    278 
    279   input.Multiply(cached_power);
    280   // The error introduced by a multiplication of a*b equals
    281   //   error_a + error_b + error_a*error_b/2^64 + 0.5
    282   // Substituting a with 'input' and b with 'cached_power' we have
    283   //   error_b = 0.5  (all cached powers have an error of less than 0.5 ulp),
    284   //   error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64
    285   int error_b = kDenominator / 2;
    286   int error_ab = (error == 0 ? 0 : 1);  // We round up to 1.
    287   int fixed_error = kDenominator / 2;
    288   error += error_b + error_ab + fixed_error;
    289 
    290   old_e = input.e();
    291   input.Normalize();
    292   error <<= old_e - input.e();
    293 
    294   // See if the double's significand changes if we add/subtract the error.
    295   int order_of_magnitude = DiyFp::kSignificandSize + input.e();
    296   int effective_significand_size =
    297       Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude);
    298   int precision_digits_count =
    299       DiyFp::kSignificandSize - effective_significand_size;
    300   if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) {
    301     // This can only happen for very small denormals. In this case the
    302     // half-way multiplied by the denominator exceeds the range of an uint64.
    303     // Simply shift everything to the right.
    304     int shift_amount = (precision_digits_count + kDenominatorLog) -
    305         DiyFp::kSignificandSize + 1;
    306     input.set_f(input.f() >> shift_amount);
    307     input.set_e(input.e() + shift_amount);
    308     // We add 1 for the lost precision of error, and kDenominator for
    309     // the lost precision of input.f().
    310     error = (error >> shift_amount) + 1 + kDenominator;
    311     precision_digits_count -= shift_amount;
    312   }
    313   // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
    314   ASSERT(DiyFp::kSignificandSize == 64);
    315   ASSERT(precision_digits_count < 64);
    316   uint64_t one64 = 1;
    317   uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
    318   uint64_t precision_bits = input.f() & precision_bits_mask;
    319   uint64_t half_way = one64 << (precision_digits_count - 1);
    320   precision_bits *= kDenominator;
    321   half_way *= kDenominator;
    322   DiyFp rounded_input(input.f() >> precision_digits_count,
    323                       input.e() + precision_digits_count);
    324   if (precision_bits >= half_way + error) {
    325     rounded_input.set_f(rounded_input.f() + 1);
    326   }
    327   // If the last_bits are too close to the half-way case than we are too
    328   // inaccurate and round down. In this case we return false so that we can
    329   // fall back to a more precise algorithm.
    330 
    331   *result = Double(rounded_input).value();
    332   if (half_way - error < precision_bits && precision_bits < half_way + error) {
    333     // Too imprecise. The caller will have to fall back to a slower version.
    334     // However the returned number is guaranteed to be either the correct
    335     // double, or the next-lower double.
    336     return false;
    337   } else {
    338     return true;
    339   }
    340 }
    341 
    342 
    343 // Returns the correct double for the buffer*10^exponent.
    344 // The variable guess should be a close guess that is either the correct double
    345 // or its lower neighbor (the nearest double less than the correct one).
    346 // Preconditions:
    347 //   buffer.length() + exponent <= kMaxDecimalPower + 1
    348 //   buffer.length() + exponent > kMinDecimalPower
    349 //   buffer.length() <= kMaxDecimalSignificantDigits
    350 static double BignumStrtod(Vector<const char> buffer,
    351                            int exponent,
    352                            double guess) {
    353   if (guess == V8_INFINITY) {
    354     return guess;
    355   }
    356 
    357   DiyFp upper_boundary = Double(guess).UpperBoundary();
    358 
    359   ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1);
    360   ASSERT(buffer.length() + exponent > kMinDecimalPower);
    361   ASSERT(buffer.length() <= kMaxSignificantDecimalDigits);
    362   // Make sure that the Bignum will be able to hold all our numbers.
    363   // Our Bignum implementation has a separate field for exponents. Shifts will
    364   // consume at most one bigit (< 64 bits).
    365   // ln(10) == 3.3219...
    366   ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits);
    367   Bignum input;
    368   Bignum boundary;
    369   input.AssignDecimalString(buffer);
    370   boundary.AssignUInt64(upper_boundary.f());
    371   if (exponent >= 0) {
    372     input.MultiplyByPowerOfTen(exponent);
    373   } else {
    374     boundary.MultiplyByPowerOfTen(-exponent);
    375   }
    376   if (upper_boundary.e() > 0) {
    377     boundary.ShiftLeft(upper_boundary.e());
    378   } else {
    379     input.ShiftLeft(-upper_boundary.e());
    380   }
    381   int comparison = Bignum::Compare(input, boundary);
    382   if (comparison < 0) {
    383     return guess;
    384   } else if (comparison > 0) {
    385     return Double(guess).NextDouble();
    386   } else if ((Double(guess).Significand() & 1) == 0) {
    387     // Round towards even.
    388     return guess;
    389   } else {
    390     return Double(guess).NextDouble();
    391   }
    392 }
    393 
    394 
    395 double Strtod(Vector<const char> buffer, int exponent) {
    396   Vector<const char> left_trimmed = TrimLeadingZeros(buffer);
    397   Vector<const char> trimmed = TrimTrailingZeros(left_trimmed);
    398   exponent += left_trimmed.length() - trimmed.length();
    399   if (trimmed.length() == 0) return 0.0;
    400   if (trimmed.length() > kMaxSignificantDecimalDigits) {
    401     char significant_buffer[kMaxSignificantDecimalDigits];
    402     int significant_exponent;
    403     TrimToMaxSignificantDigits(trimmed, exponent,
    404                                significant_buffer, &significant_exponent);
    405     return Strtod(Vector<const char>(significant_buffer,
    406                                      kMaxSignificantDecimalDigits),
    407                   significant_exponent);
    408   }
    409   if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) return V8_INFINITY;
    410   if (exponent + trimmed.length() <= kMinDecimalPower) return 0.0;
    411 
    412   double guess;
    413   if (DoubleStrtod(trimmed, exponent, &guess) ||
    414       DiyFpStrtod(trimmed, exponent, &guess)) {
    415     return guess;
    416   }
    417   return BignumStrtod(trimmed, exponent, guess);
    418 }
    419 
    420 } }  // namespace v8::internal
    421