1// Copyright 2011 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 <stdint.h>
6
7#include <cmath>
8
9#include "src/base/logging.h"
10#include "src/utils.h"
11
12#include "src/double.h"
13#include "src/fixed-dtoa.h"
14
15namespace v8 {
16namespace internal {
17
18// Represents a 128bit type. This class should be replaced by a native type on
19// platforms that support 128bit integers.
20class UInt128 {
21 public:
22  UInt128() : high_bits_(0), low_bits_(0) { }
23  UInt128(uint64_t high, uint64_t low) : high_bits_(high), low_bits_(low) { }
24
25  void Multiply(uint32_t multiplicand) {
26    uint64_t accumulator;
27
28    accumulator = (low_bits_ & kMask32) * multiplicand;
29    uint32_t part = static_cast<uint32_t>(accumulator & kMask32);
30    accumulator >>= 32;
31    accumulator = accumulator + (low_bits_ >> 32) * multiplicand;
32    low_bits_ = (accumulator << 32) + part;
33    accumulator >>= 32;
34    accumulator = accumulator + (high_bits_ & kMask32) * multiplicand;
35    part = static_cast<uint32_t>(accumulator & kMask32);
36    accumulator >>= 32;
37    accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
38    high_bits_ = (accumulator << 32) + part;
39    DCHECK((accumulator >> 32) == 0);
40  }
41
42  void Shift(int shift_amount) {
43    DCHECK(-64 <= shift_amount && shift_amount <= 64);
44    if (shift_amount == 0) {
45      return;
46    } else if (shift_amount == -64) {
47      high_bits_ = low_bits_;
48      low_bits_ = 0;
49    } else if (shift_amount == 64) {
50      low_bits_ = high_bits_;
51      high_bits_ = 0;
52    } else if (shift_amount <= 0) {
53      high_bits_ <<= -shift_amount;
54      high_bits_ += low_bits_ >> (64 + shift_amount);
55      low_bits_ <<= -shift_amount;
56    } else {
57      low_bits_ >>= shift_amount;
58      low_bits_ += high_bits_ << (64 - shift_amount);
59      high_bits_ >>= shift_amount;
60    }
61  }
62
63  // Modifies *this to *this MOD (2^power).
64  // Returns *this DIV (2^power).
65  int DivModPowerOf2(int power) {
66    if (power >= 64) {
67      int result = static_cast<int>(high_bits_ >> (power - 64));
68      high_bits_ -= static_cast<uint64_t>(result) << (power - 64);
69      return result;
70    } else {
71      uint64_t part_low = low_bits_ >> power;
72      uint64_t part_high = high_bits_ << (64 - power);
73      int result = static_cast<int>(part_low + part_high);
74      high_bits_ = 0;
75      low_bits_ -= part_low << power;
76      return result;
77    }
78  }
79
80  bool IsZero() const {
81    return high_bits_ == 0 && low_bits_ == 0;
82  }
83
84  int BitAt(int position) {
85    if (position >= 64) {
86      return static_cast<int>(high_bits_ >> (position - 64)) & 1;
87    } else {
88      return static_cast<int>(low_bits_ >> position) & 1;
89    }
90  }
91
92 private:
93  static const uint64_t kMask32 = 0xFFFFFFFF;
94  // Value == (high_bits_ << 64) + low_bits_
95  uint64_t high_bits_;
96  uint64_t low_bits_;
97};
98
99
100static const int kDoubleSignificandSize = 53;  // Includes the hidden bit.
101
102
103static void FillDigits32FixedLength(uint32_t number, int requested_length,
104                                    Vector<char> buffer, int* length) {
105  for (int i = requested_length - 1; i >= 0; --i) {
106    buffer[(*length) + i] = '0' + number % 10;
107    number /= 10;
108  }
109  *length += requested_length;
110}
111
112
113static void FillDigits32(uint32_t number, Vector<char> buffer, int* length) {
114  int number_length = 0;
115  // We fill the digits in reverse order and exchange them afterwards.
116  while (number != 0) {
117    int digit = number % 10;
118    number /= 10;
119    buffer[(*length) + number_length] = '0' + digit;
120    number_length++;
121  }
122  // Exchange the digits.
123  int i = *length;
124  int j = *length + number_length - 1;
125  while (i < j) {
126    char tmp = buffer[i];
127    buffer[i] = buffer[j];
128    buffer[j] = tmp;
129    i++;
130    j--;
131  }
132  *length += number_length;
133}
134
135
136static void FillDigits64FixedLength(uint64_t number, int requested_length,
137                                    Vector<char> buffer, int* length) {
138  const uint32_t kTen7 = 10000000;
139  // For efficiency cut the number into 3 uint32_t parts, and print those.
140  uint32_t part2 = static_cast<uint32_t>(number % kTen7);
141  number /= kTen7;
142  uint32_t part1 = static_cast<uint32_t>(number % kTen7);
143  uint32_t part0 = static_cast<uint32_t>(number / kTen7);
144
145  FillDigits32FixedLength(part0, 3, buffer, length);
146  FillDigits32FixedLength(part1, 7, buffer, length);
147  FillDigits32FixedLength(part2, 7, buffer, length);
148}
149
150
151static void FillDigits64(uint64_t number, Vector<char> buffer, int* length) {
152  const uint32_t kTen7 = 10000000;
153  // For efficiency cut the number into 3 uint32_t parts, and print those.
154  uint32_t part2 = static_cast<uint32_t>(number % kTen7);
155  number /= kTen7;
156  uint32_t part1 = static_cast<uint32_t>(number % kTen7);
157  uint32_t part0 = static_cast<uint32_t>(number / kTen7);
158
159  if (part0 != 0) {
160    FillDigits32(part0, buffer, length);
161    FillDigits32FixedLength(part1, 7, buffer, length);
162    FillDigits32FixedLength(part2, 7, buffer, length);
163  } else if (part1 != 0) {
164    FillDigits32(part1, buffer, length);
165    FillDigits32FixedLength(part2, 7, buffer, length);
166  } else {
167    FillDigits32(part2, buffer, length);
168  }
169}
170
171
172static void RoundUp(Vector<char> buffer, int* length, int* decimal_point) {
173  // An empty buffer represents 0.
174  if (*length == 0) {
175    buffer[0] = '1';
176    *decimal_point = 1;
177    *length = 1;
178    return;
179  }
180  // Round the last digit until we either have a digit that was not '9' or until
181  // we reached the first digit.
182  buffer[(*length) - 1]++;
183  for (int i = (*length) - 1; i > 0; --i) {
184    if (buffer[i] != '0' + 10) {
185      return;
186    }
187    buffer[i] = '0';
188    buffer[i - 1]++;
189  }
190  // If the first digit is now '0' + 10, we would need to set it to '0' and add
191  // a '1' in front. However we reach the first digit only if all following
192  // digits had been '9' before rounding up. Now all trailing digits are '0' and
193  // we simply switch the first digit to '1' and update the decimal-point
194  // (indicating that the point is now one digit to the right).
195  if (buffer[0] == '0' + 10) {
196    buffer[0] = '1';
197    (*decimal_point)++;
198  }
199}
200
201
202// The given fractionals number represents a fixed-point number with binary
203// point at bit (-exponent).
204// Preconditions:
205//   -128 <= exponent <= 0.
206//   0 <= fractionals * 2^exponent < 1
207//   The buffer holds the result.
208// The function will round its result. During the rounding-process digits not
209// generated by this function might be updated, and the decimal-point variable
210// might be updated. If this function generates the digits 99 and the buffer
211// already contained "199" (thus yielding a buffer of "19999") then a
212// rounding-up will change the contents of the buffer to "20000".
213static void FillFractionals(uint64_t fractionals, int exponent,
214                            int fractional_count, Vector<char> buffer,
215                            int* length, int* decimal_point) {
216  DCHECK(-128 <= exponent && exponent <= 0);
217  // 'fractionals' is a fixed-point number, with binary point at bit
218  // (-exponent). Inside the function the non-converted remainder of fractionals
219  // is a fixed-point number, with binary point at bit 'point'.
220  if (-exponent <= 64) {
221    // One 64 bit number is sufficient.
222    DCHECK(fractionals >> 56 == 0);
223    int point = -exponent;
224    for (int i = 0; i < fractional_count; ++i) {
225      if (fractionals == 0) break;
226      // Instead of multiplying by 10 we multiply by 5 and adjust the point
227      // location. This way the fractionals variable will not overflow.
228      // Invariant at the beginning of the loop: fractionals < 2^point.
229      // Initially we have: point <= 64 and fractionals < 2^56
230      // After each iteration the point is decremented by one.
231      // Note that 5^3 = 125 < 128 = 2^7.
232      // Therefore three iterations of this loop will not overflow fractionals
233      // (even without the subtraction at the end of the loop body). At this
234      // time point will satisfy point <= 61 and therefore fractionals < 2^point
235      // and any further multiplication of fractionals by 5 will not overflow.
236      fractionals *= 5;
237      point--;
238      int digit = static_cast<int>(fractionals >> point);
239      buffer[*length] = '0' + digit;
240      (*length)++;
241      fractionals -= static_cast<uint64_t>(digit) << point;
242    }
243    // If the first bit after the point is set we have to round up.
244    if (((fractionals >> (point - 1)) & 1) == 1) {
245      RoundUp(buffer, length, decimal_point);
246    }
247  } else {  // We need 128 bits.
248    DCHECK(64 < -exponent && -exponent <= 128);
249    UInt128 fractionals128 = UInt128(fractionals, 0);
250    fractionals128.Shift(-exponent - 64);
251    int point = 128;
252    for (int i = 0; i < fractional_count; ++i) {
253      if (fractionals128.IsZero()) break;
254      // As before: instead of multiplying by 10 we multiply by 5 and adjust the
255      // point location.
256      // This multiplication will not overflow for the same reasons as before.
257      fractionals128.Multiply(5);
258      point--;
259      int digit = fractionals128.DivModPowerOf2(point);
260      buffer[*length] = '0' + digit;
261      (*length)++;
262    }
263    if (fractionals128.BitAt(point - 1) == 1) {
264      RoundUp(buffer, length, decimal_point);
265    }
266  }
267}
268
269
270// Removes leading and trailing zeros.
271// If leading zeros are removed then the decimal point position is adjusted.
272static void TrimZeros(Vector<char> buffer, int* length, int* decimal_point) {
273  while (*length > 0 && buffer[(*length) - 1] == '0') {
274    (*length)--;
275  }
276  int first_non_zero = 0;
277  while (first_non_zero < *length && buffer[first_non_zero] == '0') {
278    first_non_zero++;
279  }
280  if (first_non_zero != 0) {
281    for (int i = first_non_zero; i < *length; ++i) {
282      buffer[i - first_non_zero] = buffer[i];
283    }
284    *length -= first_non_zero;
285    *decimal_point -= first_non_zero;
286  }
287}
288
289
290bool FastFixedDtoa(double v,
291                   int fractional_count,
292                   Vector<char> buffer,
293                   int* length,
294                   int* decimal_point) {
295  const uint32_t kMaxUInt32 = 0xFFFFFFFF;
296  uint64_t significand = Double(v).Significand();
297  int exponent = Double(v).Exponent();
298  // v = significand * 2^exponent (with significand a 53bit integer).
299  // If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
300  // don't know how to compute the representation. 2^73 ~= 9.5*10^21.
301  // If necessary this limit could probably be increased, but we don't need
302  // more.
303  if (exponent > 20) return false;
304  if (fractional_count > 20) return false;
305  *length = 0;
306  // At most kDoubleSignificandSize bits of the significand are non-zero.
307  // Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
308  // bits:  0..11*..0xxx..53*..xx
309  if (exponent + kDoubleSignificandSize > 64) {
310    // The exponent must be > 11.
311    //
312    // We know that v = significand * 2^exponent.
313    // And the exponent > 11.
314    // We simplify the task by dividing v by 10^17.
315    // The quotient delivers the first digits, and the remainder fits into a 64
316    // bit number.
317    // Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
318    const uint64_t kFive17 = V8_2PART_UINT64_C(0xB1, A2BC2EC5);  // 5^17
319    uint64_t divisor = kFive17;
320    int divisor_power = 17;
321    uint64_t dividend = significand;
322    uint32_t quotient;
323    uint64_t remainder;
324    // Let v = f * 2^e with f == significand and e == exponent.
325    // Then need q (quotient) and r (remainder) as follows:
326    //   v            = q * 10^17       + r
327    //   f * 2^e      = q * 10^17       + r
328    //   f * 2^e      = q * 5^17 * 2^17 + r
329    // If e > 17 then
330    //   f * 2^(e-17) = q * 5^17        + r/2^17
331    // else
332    //   f  = q * 5^17 * 2^(17-e) + r/2^e
333    if (exponent > divisor_power) {
334      // We only allow exponents of up to 20 and therefore (17 - e) <= 3
335      dividend <<= exponent - divisor_power;
336      quotient = static_cast<uint32_t>(dividend / divisor);
337      remainder = (dividend % divisor) << divisor_power;
338    } else {
339      divisor <<= divisor_power - exponent;
340      quotient = static_cast<uint32_t>(dividend / divisor);
341      remainder = (dividend % divisor) << exponent;
342    }
343    FillDigits32(quotient, buffer, length);
344    FillDigits64FixedLength(remainder, divisor_power, buffer, length);
345    *decimal_point = *length;
346  } else if (exponent >= 0) {
347    // 0 <= exponent <= 11
348    significand <<= exponent;
349    FillDigits64(significand, buffer, length);
350    *decimal_point = *length;
351  } else if (exponent > -kDoubleSignificandSize) {
352    // We have to cut the number.
353    uint64_t integrals = significand >> -exponent;
354    uint64_t fractionals = significand - (integrals << -exponent);
355    if (integrals > kMaxUInt32) {
356      FillDigits64(integrals, buffer, length);
357    } else {
358      FillDigits32(static_cast<uint32_t>(integrals), buffer, length);
359    }
360    *decimal_point = *length;
361    FillFractionals(fractionals, exponent, fractional_count,
362                    buffer, length, decimal_point);
363  } else if (exponent < -128) {
364    // This configuration (with at most 20 digits) means that all digits must be
365    // 0.
366    DCHECK(fractional_count <= 20);
367    buffer[0] = '\0';
368    *length = 0;
369    *decimal_point = -fractional_count;
370  } else {
371    *decimal_point = 0;
372    FillFractionals(significand, exponent, fractional_count,
373                    buffer, length, decimal_point);
374  }
375  TrimZeros(buffer, length, decimal_point);
376  buffer[*length] = '\0';
377  if ((*length) == 0) {
378    // The string is empty and the decimal_point thus has no importance. Mimick
379    // Gay's dtoa and and set it to -fractional_count.
380    *decimal_point = -fractional_count;
381  }
382  return true;
383}
384
385}  // namespace internal
386}  // namespace v8
387