blob: 0ed1b0d914791280dea19a54837ebc6673f164ec [file] [log] [blame]
Ben Murdochf87a2032010-10-22 12:50:53 +01001// Copyright 2010 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include <stdarg.h>
29#include <limits.h>
30
31#include "v8.h"
32
33#include "strtod.h"
John Reck59135872010-11-02 12:39:01 -070034#include "cached-powers.h"
35#include "double.h"
Ben Murdochf87a2032010-10-22 12:50:53 +010036
37namespace v8 {
38namespace internal {
39
40// 2^53 = 9007199254740992.
41// Any integer with at most 15 decimal digits will hence fit into a double
42// (which has a 53bit significand) without loss of precision.
43static const int kMaxExactDoubleIntegerDecimalDigits = 15;
John Reck59135872010-11-02 12:39:01 -070044// 2^64 = 18446744073709551616 > 10^19
Ben Murdochf87a2032010-10-22 12:50:53 +010045static const int kMaxUint64DecimalDigits = 19;
John Reck59135872010-11-02 12:39:01 -070046
Ben Murdochf87a2032010-10-22 12:50:53 +010047// Max double: 1.7976931348623157 x 10^308
48// Min non-zero double: 4.9406564584124654 x 10^-324
49// Any x >= 10^309 is interpreted as +infinity.
50// Any x <= 10^-324 is interpreted as 0.
51// Note that 2.5e-324 (despite being smaller than the min double) will be read
52// as non-zero (equal to the min non-zero double).
53static const int kMaxDecimalPower = 309;
54static const int kMinDecimalPower = -324;
55
John Reck59135872010-11-02 12:39:01 -070056// 2^64 = 18446744073709551616
57static const uint64_t kMaxUint64 = V8_2PART_UINT64_C(0xFFFFFFFF, FFFFFFFF);
58
59
Ben Murdochf87a2032010-10-22 12:50:53 +010060static const double exact_powers_of_ten[] = {
61 1.0, // 10^0
62 10.0,
63 100.0,
64 1000.0,
65 10000.0,
66 100000.0,
67 1000000.0,
68 10000000.0,
69 100000000.0,
70 1000000000.0,
71 10000000000.0, // 10^10
72 100000000000.0,
73 1000000000000.0,
74 10000000000000.0,
75 100000000000000.0,
76 1000000000000000.0,
77 10000000000000000.0,
78 100000000000000000.0,
79 1000000000000000000.0,
80 10000000000000000000.0,
81 100000000000000000000.0, // 10^20
82 1000000000000000000000.0,
83 // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
84 10000000000000000000000.0
85};
86
87static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten);
88
89
90extern "C" double gay_strtod(const char* s00, const char** se);
91
92static double old_strtod(Vector<const char> buffer, int exponent) {
93 // gay_strtod is broken on Linux,x86. For numbers with few decimal digits
94 // the computation is done using floating-point operations which (on Linux)
95 // are prone to double-rounding errors.
96 // By adding several zeroes to the buffer gay_strtod falls back to a slower
97 // (but correct) algorithm.
98 const int kInsertedZeroesCount = 20;
99 char gay_buffer[1024];
100 Vector<char> gay_buffer_vector(gay_buffer, sizeof(gay_buffer));
101 int pos = 0;
102 for (int i = 0; i < buffer.length(); ++i) {
103 gay_buffer_vector[pos++] = buffer[i];
104 }
105 for (int i = 0; i < kInsertedZeroesCount; ++i) {
106 gay_buffer_vector[pos++] = '0';
107 }
108 exponent -= kInsertedZeroesCount;
109 gay_buffer_vector[pos++] = 'e';
110 if (exponent < 0) {
111 gay_buffer_vector[pos++] = '-';
112 exponent = -exponent;
113 }
114 const int kNumberOfExponentDigits = 5;
115 for (int i = kNumberOfExponentDigits - 1; i >= 0; i--) {
116 gay_buffer_vector[pos + i] = exponent % 10 + '0';
117 exponent /= 10;
118 }
119 pos += kNumberOfExponentDigits;
120 gay_buffer_vector[pos] = '\0';
121 return gay_strtod(gay_buffer, NULL);
122}
123
124
125static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) {
126 for (int i = 0; i < buffer.length(); i++) {
127 if (buffer[i] != '0') {
John Reck59135872010-11-02 12:39:01 -0700128 return buffer.SubVector(i, buffer.length());
Ben Murdochf87a2032010-10-22 12:50:53 +0100129 }
130 }
131 return Vector<const char>(buffer.start(), 0);
132}
133
134
135static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) {
136 for (int i = buffer.length() - 1; i >= 0; --i) {
137 if (buffer[i] != '0') {
John Reck59135872010-11-02 12:39:01 -0700138 return buffer.SubVector(0, i + 1);
Ben Murdochf87a2032010-10-22 12:50:53 +0100139 }
140 }
141 return Vector<const char>(buffer.start(), 0);
142}
143
144
John Reck59135872010-11-02 12:39:01 -0700145// Reads digits from the buffer and converts them to a uint64.
146// Reads in as many digits as fit into a uint64.
147// When the string starts with "1844674407370955161" no further digit is read.
148// Since 2^64 = 18446744073709551616 it would still be possible read another
149// digit if it was less or equal than 6, but this would complicate the code.
150static uint64_t ReadUint64(Vector<const char> buffer,
151 int* number_of_read_digits) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100152 uint64_t result = 0;
John Reck59135872010-11-02 12:39:01 -0700153 int i = 0;
154 while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
155 int digit = buffer[i++] - '0';
Ben Murdochf87a2032010-10-22 12:50:53 +0100156 ASSERT(0 <= digit && digit <= 9);
157 result = 10 * result + digit;
158 }
John Reck59135872010-11-02 12:39:01 -0700159 *number_of_read_digits = i;
Ben Murdochf87a2032010-10-22 12:50:53 +0100160 return result;
161}
162
163
John Reck59135872010-11-02 12:39:01 -0700164// Reads a DiyFp from the buffer.
165// The returned DiyFp is not necessarily normalized.
166// If remaining_decimals is zero then the returned DiyFp is accurate.
167// Otherwise it has been rounded and has error of at most 1/2 ulp.
168static void ReadDiyFp(Vector<const char> buffer,
169 DiyFp* result,
170 int* remaining_decimals) {
171 int read_digits;
172 uint64_t significand = ReadUint64(buffer, &read_digits);
173 if (buffer.length() == read_digits) {
174 *result = DiyFp(significand, 0);
175 *remaining_decimals = 0;
176 } else {
177 // Round the significand.
178 if (buffer[read_digits] >= '5') {
179 significand++;
180 }
181 // Compute the binary exponent.
182 int exponent = 0;
183 *result = DiyFp(significand, exponent);
184 *remaining_decimals = buffer.length() - read_digits;
185 }
186}
187
188
Ben Murdochf87a2032010-10-22 12:50:53 +0100189static bool DoubleStrtod(Vector<const char> trimmed,
190 int exponent,
191 double* result) {
192#if (defined(V8_TARGET_ARCH_IA32) || defined(USE_SIMULATOR)) && !defined(WIN32)
193 // On x86 the floating-point stack can be 64 or 80 bits wide. If it is
194 // 80 bits wide (as is the case on Linux) then double-rounding occurs and the
195 // result is not accurate.
196 // We know that Windows32 uses 64 bits and is therefore accurate.
197 // Note that the ARM simulator is compiled for 32bits. It therefore exhibits
198 // the same problem.
199 return false;
200#endif
201 if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
John Reck59135872010-11-02 12:39:01 -0700202 int read_digits;
Ben Murdochf87a2032010-10-22 12:50:53 +0100203 // The trimmed input fits into a double.
204 // If the 10^exponent (resp. 10^-exponent) fits into a double too then we
205 // can compute the result-double simply by multiplying (resp. dividing) the
206 // two numbers.
207 // This is possible because IEEE guarantees that floating-point operations
208 // return the best possible approximation.
209 if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
210 // 10^-exponent fits into a double.
John Reck59135872010-11-02 12:39:01 -0700211 *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
212 ASSERT(read_digits == trimmed.length());
Ben Murdochf87a2032010-10-22 12:50:53 +0100213 *result /= exact_powers_of_ten[-exponent];
214 return true;
215 }
216 if (0 <= exponent && exponent < kExactPowersOfTenSize) {
217 // 10^exponent fits into a double.
John Reck59135872010-11-02 12:39:01 -0700218 *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
219 ASSERT(read_digits == trimmed.length());
Ben Murdochf87a2032010-10-22 12:50:53 +0100220 *result *= exact_powers_of_ten[exponent];
221 return true;
222 }
223 int remaining_digits =
224 kMaxExactDoubleIntegerDecimalDigits - trimmed.length();
225 if ((0 <= exponent) &&
226 (exponent - remaining_digits < kExactPowersOfTenSize)) {
227 // The trimmed string was short and we can multiply it with
228 // 10^remaining_digits. As a result the remaining exponent now fits
229 // into a double too.
John Reck59135872010-11-02 12:39:01 -0700230 *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
231 ASSERT(read_digits == trimmed.length());
Ben Murdochf87a2032010-10-22 12:50:53 +0100232 *result *= exact_powers_of_ten[remaining_digits];
233 *result *= exact_powers_of_ten[exponent - remaining_digits];
234 return true;
235 }
236 }
237 return false;
238}
239
240
John Reck59135872010-11-02 12:39:01 -0700241// Returns 10^exponent as an exact DiyFp.
242// The given exponent must be in the range [1; kDecimalExponentDistance[.
243static DiyFp AdjustmentPowerOfTen(int exponent) {
244 ASSERT(0 < exponent);
245 ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
246 // Simply hardcode the remaining powers for the given decimal exponent
247 // distance.
248 ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
249 switch (exponent) {
250 case 1: return DiyFp(V8_2PART_UINT64_C(0xa0000000, 00000000), -60);
251 case 2: return DiyFp(V8_2PART_UINT64_C(0xc8000000, 00000000), -57);
252 case 3: return DiyFp(V8_2PART_UINT64_C(0xfa000000, 00000000), -54);
253 case 4: return DiyFp(V8_2PART_UINT64_C(0x9c400000, 00000000), -50);
254 case 5: return DiyFp(V8_2PART_UINT64_C(0xc3500000, 00000000), -47);
255 case 6: return DiyFp(V8_2PART_UINT64_C(0xf4240000, 00000000), -44);
256 case 7: return DiyFp(V8_2PART_UINT64_C(0x98968000, 00000000), -40);
257 default:
258 UNREACHABLE();
259 return DiyFp(0, 0);
260 }
261}
262
263
264// If the function returns true then the result is the correct double.
265// Otherwise it is either the correct double or the double that is just below
266// the correct double.
267static bool DiyFpStrtod(Vector<const char> buffer,
268 int exponent,
269 double* result) {
270 DiyFp input;
271 int remaining_decimals;
272 ReadDiyFp(buffer, &input, &remaining_decimals);
273 // Since we may have dropped some digits the input is not accurate.
274 // If remaining_decimals is different than 0 than the error is at most
275 // .5 ulp (unit in the last place).
276 // We don't want to deal with fractions and therefore keep a common
277 // denominator.
278 const int kDenominatorLog = 3;
279 const int kDenominator = 1 << kDenominatorLog;
280 // Move the remaining decimals into the exponent.
281 exponent += remaining_decimals;
282 int error = (remaining_decimals == 0 ? 0 : kDenominator / 2);
283
284 int old_e = input.e();
285 input.Normalize();
286 error <<= old_e - input.e();
287
288 ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
289 if (exponent < PowersOfTenCache::kMinDecimalExponent) {
290 *result = 0.0;
291 return true;
292 }
293 DiyFp cached_power;
294 int cached_decimal_exponent;
295 PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent,
296 &cached_power,
297 &cached_decimal_exponent);
298
299 if (cached_decimal_exponent != exponent) {
300 int adjustment_exponent = exponent - cached_decimal_exponent;
301 DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent);
302 input.Multiply(adjustment_power);
303 if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
304 // The product of input with the adjustment power fits into a 64 bit
305 // integer.
306 ASSERT(DiyFp::kSignificandSize == 64);
307 } else {
308 // The adjustment power is exact. There is hence only an error of 0.5.
309 error += kDenominator / 2;
310 }
311 }
312
313 input.Multiply(cached_power);
314 // The error introduced by a multiplication of a*b equals
315 // error_a + error_b + error_a*error_b/2^64 + 0.5
316 // Substituting a with 'input' and b with 'cached_power' we have
317 // error_b = 0.5 (all cached powers have an error of less than 0.5 ulp),
318 // error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64
319 int error_b = kDenominator / 2;
320 int error_ab = (error == 0 ? 0 : 1); // We round up to 1.
321 int fixed_error = kDenominator / 2;
322 error += error_b + error_ab + fixed_error;
323
324 old_e = input.e();
325 input.Normalize();
326 error <<= old_e - input.e();
327
328 // See if the double's significand changes if we add/subtract the error.
329 int order_of_magnitude = DiyFp::kSignificandSize + input.e();
330 int effective_significand_size =
331 Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude);
332 int precision_digits_count =
333 DiyFp::kSignificandSize - effective_significand_size;
334 if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) {
335 // This can only happen for very small denormals. In this case the
336 // half-way multiplied by the denominator exceeds the range of an uint64.
337 // Simply shift everything to the right.
338 int shift_amount = (precision_digits_count + kDenominatorLog) -
339 DiyFp::kSignificandSize + 1;
340 input.set_f(input.f() >> shift_amount);
341 input.set_e(input.e() + shift_amount);
342 // We add 1 for the lost precision of error, and kDenominator for
343 // the lost precision of input.f().
344 error = (error >> shift_amount) + 1 + kDenominator;
345 precision_digits_count -= shift_amount;
346 }
347 // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
348 ASSERT(DiyFp::kSignificandSize == 64);
349 ASSERT(precision_digits_count < 64);
350 uint64_t one64 = 1;
351 uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
352 uint64_t precision_bits = input.f() & precision_bits_mask;
353 uint64_t half_way = one64 << (precision_digits_count - 1);
354 precision_bits *= kDenominator;
355 half_way *= kDenominator;
356 DiyFp rounded_input(input.f() >> precision_digits_count,
357 input.e() + precision_digits_count);
358 if (precision_bits >= half_way + error) {
359 rounded_input.set_f(rounded_input.f() + 1);
360 }
361 // If the last_bits are too close to the half-way case than we are too
362 // inaccurate and round down. In this case we return false so that we can
363 // fall back to a more precise algorithm.
364
365 *result = Double(rounded_input).value();
366 if (half_way - error < precision_bits && precision_bits < half_way + error) {
367 // Too imprecise. The caller will have to fall back to a slower version.
368 // However the returned number is guaranteed to be either the correct
369 // double, or the next-lower double.
370 return false;
371 } else {
372 return true;
373 }
374}
375
376
Ben Murdochf87a2032010-10-22 12:50:53 +0100377double Strtod(Vector<const char> buffer, int exponent) {
378 Vector<const char> left_trimmed = TrimLeadingZeros(buffer);
379 Vector<const char> trimmed = TrimTrailingZeros(left_trimmed);
380 exponent += left_trimmed.length() - trimmed.length();
381 if (trimmed.length() == 0) return 0.0;
382 if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) return V8_INFINITY;
383 if (exponent + trimmed.length() <= kMinDecimalPower) return 0.0;
John Reck59135872010-11-02 12:39:01 -0700384
Ben Murdochf87a2032010-10-22 12:50:53 +0100385 double result;
John Reck59135872010-11-02 12:39:01 -0700386 if (DoubleStrtod(trimmed, exponent, &result) ||
387 DiyFpStrtod(trimmed, exponent, &result)) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100388 return result;
389 }
390 return old_strtod(trimmed, exponent);
391}
392
393} } // namespace v8::internal