1 //===-- String to float conversion utils ------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef LIBC_SRC_SUPPORT_STR_TO_FLOAT_H 10 #define LIBC_SRC_SUPPORT_STR_TO_FLOAT_H 11 12 #include "src/__support/CPP/Limits.h" 13 #include "src/__support/FPUtil/FPBits.h" 14 #include "src/__support/ctype_utils.h" 15 #include "src/__support/detailed_powers_of_ten.h" 16 #include "src/__support/high_precision_decimal.h" 17 #include "src/__support/str_to_integer.h" 18 #include <errno.h> 19 20 namespace __llvm_libc { 21 namespace internal { 22 23 template <class T> uint32_t inline leading_zeroes(T inputNumber) { 24 constexpr uint32_t BITS_IN_T = sizeof(T) * 8; 25 if (inputNumber == 0) { 26 return BITS_IN_T; 27 } 28 uint32_t cur_guess = BITS_IN_T / 2; 29 uint32_t range_size = BITS_IN_T / 2; 30 // while either shifting by curGuess does not get rid of all of the bits or 31 // shifting by one less also gets rid of all of the bits then we have not 32 // found the first bit. 33 while (((inputNumber >> cur_guess) > 0) || 34 ((inputNumber >> (cur_guess - 1)) == 0)) { 35 // Binary search for the first set bit 36 range_size /= 2; 37 if (range_size == 0) { 38 break; 39 } 40 if ((inputNumber >> cur_guess) > 0) { 41 cur_guess += range_size; 42 } else { 43 cur_guess -= range_size; 44 } 45 } 46 if (inputNumber >> cur_guess > 0) { 47 cur_guess++; 48 } 49 return BITS_IN_T - cur_guess; 50 } 51 52 template <> uint32_t inline leading_zeroes<uint32_t>(uint32_t inputNumber) { 53 return inputNumber == 0 ? 32 : __builtin_clz(inputNumber); 54 } 55 56 template <> uint32_t inline leading_zeroes<uint64_t>(uint64_t inputNumber) { 57 return inputNumber == 0 ? 64 : __builtin_clzll(inputNumber); 58 } 59 60 static inline uint64_t low64(__uint128_t num) { 61 return static_cast<uint64_t>(num & 0xffffffffffffffff); 62 } 63 64 static inline uint64_t high64(__uint128_t num) { 65 return static_cast<uint64_t>(num >> 64); 66 } 67 68 template <class T> inline void set_implicit_bit(fputil::FPBits<T> &result) { 69 return; 70 } 71 72 #if defined(SPECIAL_X86_LONG_DOUBLE) 73 template <> 74 inline void set_implicit_bit<long double>(fputil::FPBits<long double> &result) { 75 result.set_implicit_bit(result.get_unbiased_exponent() != 0); 76 } 77 #endif 78 79 // This Eisel-Lemire implementation is based on the algorithm described in the 80 // paper Number Parsing at a Gigabyte per Second, Software: Practice and 81 // Experience 51 (8), 2021 (https://arxiv.org/abs/2101.11408), as well as the 82 // description by Nigel Tao 83 // (https://nigeltao.github.io/blog/2020/eisel-lemire.html) and the golang 84 // implementation, also by Nigel Tao 85 // (https://github.com/golang/go/blob/release-branch.go1.16/src/strconv/eisel_lemire.go#L25) 86 // for some optimizations as well as handling 32 bit floats. 87 template <class T> 88 static inline bool 89 eisel_lemire(typename fputil::FPBits<T>::UIntType mantissa, int32_t exp10, 90 typename fputil::FPBits<T>::UIntType *outputMantissa, 91 uint32_t *outputExp2) { 92 93 using BitsType = typename fputil::FPBits<T>::UIntType; 94 constexpr uint32_t BITS_IN_MANTISSA = sizeof(mantissa) * 8; 95 96 if (sizeof(T) > 8) { // This algorithm cannot handle anything longer than a 97 // double, so we skip straight to the fallback. 98 return false; 99 } 100 101 // Exp10 Range 102 if (exp10 < DETAILED_POWERS_OF_TEN_MIN_EXP_10 || 103 exp10 > DETAILED_POWERS_OF_TEN_MAX_EXP_10) { 104 return false; 105 } 106 107 // Normalization 108 uint32_t clz = leading_zeroes<BitsType>(mantissa); 109 mantissa <<= clz; 110 111 uint32_t exp2 = exp10_to_exp2(exp10) + BITS_IN_MANTISSA + 112 fputil::FloatProperties<T>::EXPONENT_BIAS - clz; 113 114 // Multiplication 115 const uint64_t *power_of_ten = 116 DETAILED_POWERS_OF_TEN[exp10 - DETAILED_POWERS_OF_TEN_MIN_EXP_10]; 117 118 __uint128_t first_approx = static_cast<__uint128_t>(mantissa) * 119 static_cast<__uint128_t>(power_of_ten[1]); 120 121 // Wider Approximation 122 __uint128_t final_approx; 123 // The halfway constant is used to check if the bits that will be shifted away 124 // intially are all 1. For doubles this is 64 (bitstype size) - 52 (final 125 // mantissa size) - 3 (we shift away the last two bits separately for 126 // accuracy, and the most significant bit is ignored.) = 9 bits. Similarly, 127 // it's 6 bits for floats in this case. 128 const uint64_t halfway_constant = 129 (uint64_t(1) << (BITS_IN_MANTISSA - 130 fputil::FloatProperties<T>::MANTISSA_WIDTH - 3)) - 131 1; 132 if ((high64(first_approx) & halfway_constant) == halfway_constant && 133 low64(first_approx) + mantissa < mantissa) { 134 __uint128_t low_bits = static_cast<__uint128_t>(mantissa) * 135 static_cast<__uint128_t>(power_of_ten[0]); 136 __uint128_t second_approx = 137 first_approx + static_cast<__uint128_t>(high64(low_bits)); 138 139 if ((high64(second_approx) & halfway_constant) == halfway_constant && 140 low64(second_approx) + 1 == 0 && 141 low64(low_bits) + mantissa < mantissa) { 142 return false; 143 } 144 final_approx = second_approx; 145 } else { 146 final_approx = first_approx; 147 } 148 149 // Shifting to 54 bits for doubles and 25 bits for floats 150 BitsType msb = high64(final_approx) >> (BITS_IN_MANTISSA - 1); 151 BitsType final_mantissa = high64(final_approx) >> 152 (msb + BITS_IN_MANTISSA - 153 (fputil::FloatProperties<T>::MANTISSA_WIDTH + 3)); 154 exp2 -= 1 ^ msb; // same as !msb 155 156 // Half-way ambiguity 157 if (low64(final_approx) == 0 && 158 (high64(final_approx) & halfway_constant) == 0 && 159 (final_mantissa & 3) == 1) { 160 return false; 161 } 162 163 // From 54 to 53 bits for doubles and 25 to 24 bits for floats 164 final_mantissa += final_mantissa & 1; 165 final_mantissa >>= 1; 166 if ((final_mantissa >> (fputil::FloatProperties<T>::MANTISSA_WIDTH + 1)) > 167 0) { 168 final_mantissa >>= 1; 169 ++exp2; 170 } 171 172 // The if block is equivalent to (but has fewer branches than): 173 // if exp2 <= 0 || exp2 >= 0x7FF { etc } 174 if (exp2 - 1 >= (1 << fputil::FloatProperties<T>::EXPONENT_WIDTH) - 2) { 175 return false; 176 } 177 178 *outputMantissa = final_mantissa; 179 *outputExp2 = exp2; 180 return true; 181 } 182 183 #if !defined(LONG_DOUBLE_IS_DOUBLE) 184 template <> 185 inline bool eisel_lemire<long double>( 186 typename fputil::FPBits<long double>::UIntType mantissa, int32_t exp10, 187 typename fputil::FPBits<long double>::UIntType *outputMantissa, 188 uint32_t *outputExp2) { 189 using BitsType = typename fputil::FPBits<long double>::UIntType; 190 constexpr uint32_t BITS_IN_MANTISSA = sizeof(mantissa) * 8; 191 192 // Exp10 Range 193 // This doesn't reach very far into the range for long doubles, since it's 194 // sized for doubles and their 11 exponent bits, and not for long doubles and 195 // their 15 exponent bits (max exponent of ~300 for double vs ~5000 for long 196 // double). This is a known tradeoff, and was made because a proper long 197 // double table would be approximately 16 times larger. This would have 198 // significant memory and storage costs all the time to speed up a relatively 199 // uncommon path. In addition the exp10_to_exp2 function only approximates 200 // multiplying by log(10)/log(2), and that approximation may not be accurate 201 // out to the full long double range. 202 if (exp10 < DETAILED_POWERS_OF_TEN_MIN_EXP_10 || 203 exp10 > DETAILED_POWERS_OF_TEN_MAX_EXP_10) { 204 return false; 205 } 206 207 // Normalization 208 uint32_t clz = leading_zeroes<BitsType>(mantissa); 209 mantissa <<= clz; 210 211 uint32_t exp2 = exp10_to_exp2(exp10) + BITS_IN_MANTISSA + 212 fputil::FloatProperties<long double>::EXPONENT_BIAS - clz; 213 214 // Multiplication 215 const uint64_t *power_of_ten = 216 DETAILED_POWERS_OF_TEN[exp10 - DETAILED_POWERS_OF_TEN_MIN_EXP_10]; 217 218 // Since the input mantissa is more than 64 bits, we have to multiply with the 219 // full 128 bits of the power of ten to get an approximation with the same 220 // number of significant bits. This means that we only get the one 221 // approximation, and that approximation is 256 bits long. 222 __uint128_t approx_upper = static_cast<__uint128_t>(high64(mantissa)) * 223 static_cast<__uint128_t>(power_of_ten[1]); 224 225 __uint128_t approx_middle = static_cast<__uint128_t>(high64(mantissa)) * 226 static_cast<__uint128_t>(power_of_ten[0]) + 227 static_cast<__uint128_t>(low64(mantissa)) * 228 static_cast<__uint128_t>(power_of_ten[1]); 229 230 __uint128_t approx_lower = static_cast<__uint128_t>(low64(mantissa)) * 231 static_cast<__uint128_t>(power_of_ten[0]); 232 233 __uint128_t final_approx_lower = 234 approx_lower + (static_cast<__uint128_t>(low64(approx_middle)) << 64); 235 __uint128_t final_approx_upper = approx_upper + high64(approx_middle) + 236 (final_approx_lower < approx_lower ? 1 : 0); 237 238 // The halfway constant is used to check if the bits that will be shifted away 239 // intially are all 1. For 80 bit floats this is 128 (bitstype size) - 64 240 // (final mantissa size) - 3 (we shift away the last two bits separately for 241 // accuracy, and the most significant bit is ignored.) = 61 bits. Similarly, 242 // it's 12 bits for 128 bit floats in this case. 243 constexpr __uint128_t HALFWAY_CONSTANT = 244 (__uint128_t(1) << (BITS_IN_MANTISSA - 245 fputil::FloatProperties<long double>::MANTISSA_WIDTH - 246 3)) - 247 1; 248 249 if ((final_approx_upper & HALFWAY_CONSTANT) == HALFWAY_CONSTANT && 250 final_approx_lower + mantissa < mantissa) { 251 return false; 252 } 253 254 // Shifting to 65 bits for 80 bit floats and 113 bits for 128 bit floats 255 BitsType msb = final_approx_upper >> (BITS_IN_MANTISSA - 1); 256 BitsType final_mantissa = 257 final_approx_upper >> 258 (msb + BITS_IN_MANTISSA - 259 (fputil::FloatProperties<long double>::MANTISSA_WIDTH + 3)); 260 exp2 -= 1 ^ msb; // same as !msb 261 262 // Half-way ambiguity 263 if (final_approx_lower == 0 && (final_approx_upper & HALFWAY_CONSTANT) == 0 && 264 (final_mantissa & 3) == 1) { 265 return false; 266 } 267 268 // From 65 to 64 bits for 80 bit floats and 113 to 112 bits for 128 bit 269 // floats 270 final_mantissa += final_mantissa & 1; 271 final_mantissa >>= 1; 272 if ((final_mantissa >> 273 (fputil::FloatProperties<long double>::MANTISSA_WIDTH + 1)) > 0) { 274 final_mantissa >>= 1; 275 ++exp2; 276 } 277 278 // The if block is equivalent to (but has fewer branches than): 279 // if exp2 <= 0 || exp2 >= MANTISSA_MAX { etc } 280 if (exp2 - 1 >= 281 (1 << fputil::FloatProperties<long double>::EXPONENT_WIDTH) - 2) { 282 return false; 283 } 284 285 *outputMantissa = final_mantissa; 286 *outputExp2 = exp2; 287 return true; 288 } 289 #endif 290 291 // The nth item in POWERS_OF_TWO represents the greatest power of two less than 292 // 10^n. This tells us how much we can safely shift without overshooting. 293 constexpr uint8_t POWERS_OF_TWO[19] = { 294 0, 3, 6, 9, 13, 16, 19, 23, 26, 29, 33, 36, 39, 43, 46, 49, 53, 56, 59, 295 }; 296 constexpr int32_t NUM_POWERS_OF_TWO = 297 sizeof(POWERS_OF_TWO) / sizeof(POWERS_OF_TWO[0]); 298 299 // Takes a mantissa and base 10 exponent and converts it into its closest 300 // floating point type T equivalent. This is the fallback algorithm used when 301 // the Eisel-Lemire algorithm fails, it's slower but more accurate. It's based 302 // on the Simple Decimal Conversion algorithm by Nigel Tao, described at this 303 // link: https://nigeltao.github.io/blog/2020/parse-number-f64-simple.html 304 template <class T> 305 static inline void 306 simple_decimal_conversion(const char *__restrict numStart, 307 typename fputil::FPBits<T>::UIntType *outputMantissa, 308 uint32_t *outputExp2) { 309 310 int32_t exp2 = 0; 311 HighPrecisionDecimal hpd = HighPrecisionDecimal(numStart); 312 313 if (hpd.get_num_digits() == 0) { 314 *outputMantissa = 0; 315 *outputExp2 = 0; 316 return; 317 } 318 319 // If the exponent is too large and can't be represented in this size of 320 // float, return inf. 321 if (hpd.get_decimal_point() > 0 && 322 exp10_to_exp2(hpd.get_decimal_point() - 1) > 323 static_cast<int64_t>(fputil::FloatProperties<T>::EXPONENT_BIAS)) { 324 *outputMantissa = 0; 325 *outputExp2 = fputil::FPBits<T>::MAX_EXPONENT; 326 errno = ERANGE; 327 return; 328 } 329 // If the exponent is too small even for a subnormal, return 0. 330 if (hpd.get_decimal_point() < 0 && 331 exp10_to_exp2(-hpd.get_decimal_point()) > 332 static_cast<int64_t>(fputil::FloatProperties<T>::EXPONENT_BIAS + 333 fputil::FloatProperties<T>::MANTISSA_WIDTH)) { 334 *outputMantissa = 0; 335 *outputExp2 = 0; 336 errno = ERANGE; 337 return; 338 } 339 340 // Right shift until the number is smaller than 1. 341 while (hpd.get_decimal_point() > 0) { 342 int32_t shift_amount = 0; 343 if (hpd.get_decimal_point() >= NUM_POWERS_OF_TWO) { 344 shift_amount = 60; 345 } else { 346 shift_amount = POWERS_OF_TWO[hpd.get_decimal_point()]; 347 } 348 exp2 += shift_amount; 349 hpd.shift(-shift_amount); 350 } 351 352 // Left shift until the number is between 1/2 and 1 353 while (hpd.get_decimal_point() < 0 || 354 (hpd.get_decimal_point() == 0 && hpd.get_digits()[0] < 5)) { 355 int32_t shift_amount = 0; 356 357 if (-hpd.get_decimal_point() >= NUM_POWERS_OF_TWO) { 358 shift_amount = 60; 359 } else if (hpd.get_decimal_point() != 0) { 360 shift_amount = POWERS_OF_TWO[-hpd.get_decimal_point()]; 361 } else { // This handles the case of the number being between .1 and .5 362 shift_amount = 1; 363 } 364 exp2 -= shift_amount; 365 hpd.shift(shift_amount); 366 } 367 368 // Left shift once so that the number is between 1 and 2 369 --exp2; 370 hpd.shift(1); 371 372 // Get the biased exponent 373 exp2 += fputil::FloatProperties<T>::EXPONENT_BIAS; 374 375 // Handle the exponent being too large (and return inf). 376 if (exp2 >= fputil::FPBits<T>::MAX_EXPONENT) { 377 *outputMantissa = 0; 378 *outputExp2 = fputil::FPBits<T>::MAX_EXPONENT; 379 errno = ERANGE; 380 return; 381 } 382 383 // Shift left to fill the mantissa 384 hpd.shift(fputil::FloatProperties<T>::MANTISSA_WIDTH); 385 typename fputil::FPBits<T>::UIntType final_mantissa = 386 hpd.round_to_integer_type<typename fputil::FPBits<T>::UIntType>(); 387 388 // Handle subnormals 389 if (exp2 <= 0) { 390 // Shift right until there is a valid exponent 391 while (exp2 < 0) { 392 hpd.shift(-1); 393 ++exp2; 394 } 395 // Shift right one more time to compensate for the left shift to get it 396 // between 1 and 2. 397 hpd.shift(-1); 398 final_mantissa = 399 hpd.round_to_integer_type<typename fputil::FPBits<T>::UIntType>(); 400 401 // Check if by shifting right we've caused this to round to a normal number. 402 if ((final_mantissa >> fputil::FloatProperties<T>::MANTISSA_WIDTH) != 0) { 403 ++exp2; 404 } 405 } 406 407 // Check if rounding added a bit, and shift down if that's the case. 408 if (final_mantissa == typename fputil::FPBits<T>::UIntType(2) 409 << fputil::FloatProperties<T>::MANTISSA_WIDTH) { 410 final_mantissa >>= 1; 411 ++exp2; 412 413 // Check if this rounding causes exp2 to go out of range and make the result 414 // INF. If this is the case, then finalMantissa and exp2 are already the 415 // correct values for an INF result. 416 if (exp2 >= fputil::FPBits<T>::MAX_EXPONENT) { 417 errno = ERANGE; // NOLINT 418 } 419 } 420 421 if (exp2 == 0) { 422 errno = ERANGE; 423 } 424 425 *outputMantissa = final_mantissa; 426 *outputExp2 = exp2; 427 } 428 429 // This class is used for templating the constants for Clinger's Fast Path, 430 // described as a method of approximation in 431 // Clinger WD. How to Read Floating Point Numbers Accurately. SIGPLAN Not 1990 432 // Jun;25(6):92–101. https://doi.org/10.1145/93548.93557. 433 // As well as the additions by Gay that extend the useful range by the number of 434 // exact digits stored by the float type, described in 435 // Gay DM, Correctly rounded binary-decimal and decimal-binary conversions; 436 // 1990. AT&T Bell Laboratories Numerical Analysis Manuscript 90-10. 437 template <class T> class ClingerConsts; 438 439 template <> class ClingerConsts<float> { 440 public: 441 static constexpr float POWERS_OF_TEN_ARRAY[] = {1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 442 1e6, 1e7, 1e8, 1e9, 1e10}; 443 static constexpr int32_t EXACT_POWERS_OF_TEN = 10; 444 static constexpr int32_t DIGITS_IN_MANTISSA = 7; 445 static constexpr float MAX_EXACT_INT = 16777215.0; 446 }; 447 448 template <> class ClingerConsts<double> { 449 public: 450 static constexpr double POWERS_OF_TEN_ARRAY[] = { 451 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 452 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22}; 453 static constexpr int32_t EXACT_POWERS_OF_TEN = 22; 454 static constexpr int32_t DIGITS_IN_MANTISSA = 15; 455 static constexpr double MAX_EXACT_INT = 9007199254740991.0; 456 }; 457 458 #if defined(LONG_DOUBLE_IS_DOUBLE) 459 template <> class ClingerConsts<long double> { 460 public: 461 static constexpr long double POWERS_OF_TEN_ARRAY[] = 462 ClingerConsts<double>::POWERS_OF_TEN_ARRAY; 463 static constexpr int32_t EXACT_POWERS_OF_TEN = 464 ClingerConsts<double>::EXACT_POWERS_OF_TEN; 465 static constexpr int32_t DIGITS_IN_MANTISSA = 466 ClingerConsts<double>::DIGITS_IN_MANTISSA; 467 static constexpr long double MAX_EXACT_INT = 468 ClingerConsts<double>::MAX_EXACT_INT; 469 }; 470 #elif defined(SPECIAL_X86_LONG_DOUBLE) 471 template <> class ClingerConsts<long double> { 472 public: 473 static constexpr long double POWERS_OF_TEN_ARRAY[] = { 474 1e0L, 1e1L, 1e2L, 1e3L, 1e4L, 1e5L, 1e6L, 1e7L, 1e8L, 1e9L, 475 1e10L, 1e11L, 1e12L, 1e13L, 1e14L, 1e15L, 1e16L, 1e17L, 1e18L, 1e19L, 476 1e20L, 1e21L, 1e22L, 1e23L, 1e24L, 1e25L, 1e26L, 1e27L}; 477 static constexpr int32_t EXACT_POWERS_OF_TEN = 27; 478 static constexpr int32_t DIGITS_IN_MANTISSA = 21; 479 static constexpr long double MAX_EXACT_INT = 18446744073709551615.0L; 480 }; 481 #else 482 template <> class ClingerConsts<long double> { 483 public: 484 static constexpr long double POWERS_OF_TEN_ARRAY[] = { 485 1e0L, 1e1L, 1e2L, 1e3L, 1e4L, 1e5L, 1e6L, 1e7L, 1e8L, 1e9L, 486 1e10L, 1e11L, 1e12L, 1e13L, 1e14L, 1e15L, 1e16L, 1e17L, 1e18L, 1e19L, 487 1e20L, 1e21L, 1e22L, 1e23L, 1e24L, 1e25L, 1e26L, 1e27L, 1e28L, 1e29L, 488 1e30L, 1e31L, 1e32L, 1e33L, 1e34L, 1e35L, 1e36L, 1e37L, 1e38L, 1e39L, 489 1e40L, 1e41L, 1e42L, 1e43L, 1e44L, 1e45L, 1e46L, 1e47L, 1e48L}; 490 static constexpr int32_t EXACT_POWERS_OF_TEN = 48; 491 static constexpr int32_t DIGITS_IN_MANTISSA = 33; 492 static constexpr long double MAX_EXACT_INT = 493 10384593717069655257060992658440191.0L; 494 }; 495 #endif 496 497 // Take an exact mantissa and exponent and attempt to convert it using only 498 // exact floating point arithmetic. This only handles numbers with low 499 // exponents, but handles them quickly. This is an implementation of Clinger's 500 // Fast Path, as described above. 501 template <class T> 502 static inline bool 503 clinger_fast_path(typename fputil::FPBits<T>::UIntType mantissa, int32_t exp10, 504 typename fputil::FPBits<T>::UIntType *outputMantissa, 505 uint32_t *outputExp2) { 506 if (mantissa >> fputil::FloatProperties<T>::MANTISSA_WIDTH > 0) { 507 return false; 508 } 509 510 fputil::FPBits<T> result; 511 T float_mantissa = static_cast<T>(mantissa); 512 513 if (exp10 == 0) { 514 result = fputil::FPBits<T>(float_mantissa); 515 } 516 if (exp10 > 0) { 517 if (exp10 > ClingerConsts<T>::EXACT_POWERS_OF_TEN + 518 ClingerConsts<T>::DIGITS_IN_MANTISSA) { 519 return false; 520 } 521 if (exp10 > ClingerConsts<T>::EXACT_POWERS_OF_TEN) { 522 float_mantissa = float_mantissa * 523 ClingerConsts<T>::POWERS_OF_TEN_ARRAY 524 [exp10 - ClingerConsts<T>::EXACT_POWERS_OF_TEN]; 525 exp10 = ClingerConsts<T>::EXACT_POWERS_OF_TEN; 526 } 527 if (float_mantissa > ClingerConsts<T>::MAX_EXACT_INT) { 528 return false; 529 } 530 result = fputil::FPBits<T>(float_mantissa * 531 ClingerConsts<T>::POWERS_OF_TEN_ARRAY[exp10]); 532 } else if (exp10 < 0) { 533 if (-exp10 > ClingerConsts<T>::EXACT_POWERS_OF_TEN) { 534 return false; 535 } 536 result = fputil::FPBits<T>(float_mantissa / 537 ClingerConsts<T>::POWERS_OF_TEN_ARRAY[-exp10]); 538 } 539 *outputMantissa = result.get_mantissa(); 540 *outputExp2 = result.get_unbiased_exponent(); 541 return true; 542 } 543 544 // Takes a mantissa and base 10 exponent and converts it into its closest 545 // floating point type T equivalient. First we try the Eisel-Lemire algorithm, 546 // then if that fails then we fall back to a more accurate algorithm for 547 // accuracy. The resulting mantissa and exponent are placed in outputMantissa 548 // and outputExp2. 549 template <class T> 550 static inline void 551 decimal_exp_to_float(typename fputil::FPBits<T>::UIntType mantissa, 552 int32_t exp10, const char *__restrict numStart, 553 bool truncated, 554 typename fputil::FPBits<T>::UIntType *outputMantissa, 555 uint32_t *outputExp2) { 556 // If the exponent is too large and can't be represented in this size of 557 // float, return inf. These bounds are very loose, but are mostly serving as a 558 // first pass. Some close numbers getting through is okay. 559 if (exp10 > 560 static_cast<int64_t>(fputil::FloatProperties<T>::EXPONENT_BIAS) / 3) { 561 *outputMantissa = 0; 562 *outputExp2 = fputil::FPBits<T>::MAX_EXPONENT; 563 errno = ERANGE; 564 return; 565 } 566 // If the exponent is too small even for a subnormal, return 0. 567 if (exp10 < 0 && 568 -static_cast<int64_t>(exp10) > 569 static_cast<int64_t>(fputil::FloatProperties<T>::EXPONENT_BIAS + 570 fputil::FloatProperties<T>::MANTISSA_WIDTH) / 571 2) { 572 *outputMantissa = 0; 573 *outputExp2 = 0; 574 errno = ERANGE; 575 return; 576 } 577 578 if (!truncated) { 579 if (clinger_fast_path<T>(mantissa, exp10, outputMantissa, outputExp2)) { 580 return; 581 } 582 } 583 584 // Try Eisel-Lemire 585 if (eisel_lemire<T>(mantissa, exp10, outputMantissa, outputExp2)) { 586 if (!truncated) { 587 return; 588 } 589 // If the mantissa is truncated, then the result may be off by the LSB, so 590 // check if rounding the mantissa up changes the result. If not, then it's 591 // safe, else use the fallback. 592 typename fputil::FPBits<T>::UIntType first_mantissa = *outputMantissa; 593 uint32_t first_exp2 = *outputExp2; 594 if (eisel_lemire<T>(mantissa + 1, exp10, outputMantissa, outputExp2)) { 595 if (*outputMantissa == first_mantissa && *outputExp2 == first_exp2) { 596 return; 597 } 598 } 599 } 600 601 simple_decimal_conversion<T>(numStart, outputMantissa, outputExp2); 602 603 return; 604 } 605 606 // Takes a mantissa and base 2 exponent and converts it into its closest 607 // floating point type T equivalient. Since the exponent is already in the right 608 // form, this is mostly just shifting and rounding. This is used for hexadecimal 609 // numbers since a base 16 exponent multiplied by 4 is the base 2 exponent. 610 template <class T> 611 static inline void 612 binary_exp_to_float(typename fputil::FPBits<T>::UIntType mantissa, int32_t exp2, 613 bool truncated, 614 typename fputil::FPBits<T>::UIntType *outputMantissa, 615 uint32_t *outputExp2) { 616 using BitsType = typename fputil::FPBits<T>::UIntType; 617 618 // This is the number of leading zeroes a properly normalized float of type T 619 // should have. 620 constexpr int32_t NUMBITS = sizeof(BitsType) * 8; 621 constexpr int32_t INF_EXP = 622 (1 << fputil::FloatProperties<T>::EXPONENT_WIDTH) - 1; 623 624 // Normalization step 1: Bring the leading bit to the highest bit of BitsType. 625 uint32_t amount_to_shift_left = leading_zeroes<BitsType>(mantissa); 626 mantissa <<= amount_to_shift_left; 627 628 // Keep exp2 representing the exponent of the lowest bit of BitsType. 629 exp2 -= amount_to_shift_left; 630 631 // biasedExponent represents the biased exponent of the most significant bit. 632 int32_t biased_exponent = 633 exp2 + NUMBITS + fputil::FPBits<T>::EXPONENT_BIAS - 1; 634 635 // Handle numbers that're too large and get squashed to inf 636 if (biased_exponent >= INF_EXP) { 637 // This indicates an overflow, so we make the result INF and set errno. 638 *outputExp2 = (1 << fputil::FloatProperties<T>::EXPONENT_WIDTH) - 1; 639 *outputMantissa = 0; 640 errno = ERANGE; 641 return; 642 } 643 644 uint32_t amount_to_shift_right = 645 NUMBITS - fputil::FloatProperties<T>::MANTISSA_WIDTH - 1; 646 647 // Handle subnormals. 648 if (biased_exponent <= 0) { 649 amount_to_shift_right += 1 - biased_exponent; 650 biased_exponent = 0; 651 652 if (amount_to_shift_right > NUMBITS) { 653 // Return 0 if the exponent is too small. 654 *outputMantissa = 0; 655 *outputExp2 = 0; 656 errno = ERANGE; 657 return; 658 } 659 } 660 661 BitsType round_bit_mask = BitsType(1) << (amount_to_shift_right - 1); 662 BitsType sticky_mask = round_bit_mask - 1; 663 bool round_bit = mantissa & round_bit_mask; 664 bool sticky_bit = static_cast<bool>(mantissa & sticky_mask) || truncated; 665 666 if (amount_to_shift_right < NUMBITS) { 667 // Shift the mantissa and clear the implicit bit. 668 mantissa >>= amount_to_shift_right; 669 mantissa &= fputil::FloatProperties<T>::MANTISSA_MASK; 670 } else { 671 mantissa = 0; 672 } 673 bool least_significant_bit = mantissa & BitsType(1); 674 // Perform rounding-to-nearest, tie-to-even. 675 if (round_bit && (least_significant_bit || sticky_bit)) { 676 ++mantissa; 677 } 678 679 if (mantissa > fputil::FloatProperties<T>::MANTISSA_MASK) { 680 // Rounding causes the exponent to increase. 681 ++biased_exponent; 682 683 if (biased_exponent == INF_EXP) { 684 errno = ERANGE; 685 } 686 } 687 688 if (biased_exponent == 0) { 689 errno = ERANGE; 690 } 691 692 *outputMantissa = mantissa & fputil::FloatProperties<T>::MANTISSA_MASK; 693 *outputExp2 = biased_exponent; 694 } 695 696 // checks if the next 4 characters of the string pointer are the start of a 697 // hexadecimal floating point number. Does not advance the string pointer. 698 static inline bool is_float_hex_start(const char *__restrict src, 699 const char decimalPoint) { 700 if (!(*src == '0' && (*(src + 1) | 32) == 'x')) { 701 return false; 702 } 703 if (*(src + 2) == decimalPoint) { 704 return isalnum(*(src + 3)) && b36_char_to_int(*(src + 3)) < 16; 705 } else { 706 return isalnum(*(src + 2)) && b36_char_to_int(*(src + 2)) < 16; 707 } 708 } 709 710 // Takes the start of a string representing a decimal float, as well as the 711 // local decimalPoint. It returns if it suceeded in parsing any digits, and if 712 // the return value is true then the outputs are pointer to the end of the 713 // number, and the mantissa and exponent for the closest float T representation. 714 // If the return value is false, then it is assumed that there is no number 715 // here. 716 template <class T> 717 static inline bool 718 decimal_string_to_float(const char *__restrict src, const char DECIMAL_POINT, 719 char **__restrict strEnd, 720 typename fputil::FPBits<T>::UIntType *outputMantissa, 721 uint32_t *outputExponent) { 722 using BitsType = typename fputil::FPBits<T>::UIntType; 723 constexpr uint32_t BASE = 10; 724 constexpr char EXPONENT_MARKER = 'e'; 725 726 const char *__restrict num_start = src; 727 bool truncated = false; 728 bool seen_digit = false; 729 bool after_decimal = false; 730 BitsType mantissa = 0; 731 int32_t exponent = 0; 732 733 // The goal for the first step of parsing is to convert the number in src to 734 // the format mantissa * (base ^ exponent) 735 736 // The loop fills the mantissa with as many digits as it can hold 737 const BitsType bitstype_max_div_by_base = 738 __llvm_libc::cpp::NumericLimits<BitsType>::max() / BASE; 739 while (true) { 740 if (isdigit(*src)) { 741 uint32_t digit = *src - '0'; 742 seen_digit = true; 743 744 if (mantissa < bitstype_max_div_by_base) { 745 mantissa = (mantissa * BASE) + digit; 746 if (after_decimal) { 747 --exponent; 748 } 749 } else { 750 if (digit > 0) 751 truncated = true; 752 if (!after_decimal) 753 ++exponent; 754 } 755 756 ++src; 757 continue; 758 } 759 if (*src == DECIMAL_POINT) { 760 if (after_decimal) { 761 break; // this means that *src points to a second decimal point, ending 762 // the number. 763 } 764 after_decimal = true; 765 ++src; 766 continue; 767 } 768 // The character is neither a digit nor a decimal point. 769 break; 770 } 771 772 if (!seen_digit) 773 return false; 774 775 if ((*src | 32) == EXPONENT_MARKER) { 776 if (*(src + 1) == '+' || *(src + 1) == '-' || isdigit(*(src + 1))) { 777 ++src; 778 char *temp_str_end; 779 int32_t add_to_exponent = strtointeger<int32_t>(src, &temp_str_end, 10); 780 if (add_to_exponent > 100000) 781 add_to_exponent = 100000; 782 else if (add_to_exponent < -100000) 783 add_to_exponent = -100000; 784 785 src = temp_str_end; 786 exponent += add_to_exponent; 787 } 788 } 789 790 *strEnd = const_cast<char *>(src); 791 if (mantissa == 0) { // if we have a 0, then also 0 the exponent. 792 *outputMantissa = 0; 793 *outputExponent = 0; 794 } else { 795 decimal_exp_to_float<T>(mantissa, exponent, num_start, truncated, 796 outputMantissa, outputExponent); 797 } 798 return true; 799 } 800 801 // Takes the start of a string representing a hexadecimal float, as well as the 802 // local decimal point. It returns if it suceeded in parsing any digits, and if 803 // the return value is true then the outputs are pointer to the end of the 804 // number, and the mantissa and exponent for the closest float T representation. 805 // If the return value is false, then it is assumed that there is no number 806 // here. 807 template <class T> 808 static inline bool hexadecimal_string_to_float( 809 const char *__restrict src, const char DECIMAL_POINT, 810 char **__restrict strEnd, 811 typename fputil::FPBits<T>::UIntType *outputMantissa, 812 uint32_t *outputExponent) { 813 using BitsType = typename fputil::FPBits<T>::UIntType; 814 constexpr uint32_t BASE = 16; 815 constexpr char EXPONENT_MARKER = 'p'; 816 817 bool truncated = false; 818 bool seen_digit = false; 819 bool after_decimal = false; 820 BitsType mantissa = 0; 821 int32_t exponent = 0; 822 823 // The goal for the first step of parsing is to convert the number in src to 824 // the format mantissa * (base ^ exponent) 825 826 // The loop fills the mantissa with as many digits as it can hold 827 const BitsType bitstype_max_div_by_base = 828 __llvm_libc::cpp::NumericLimits<BitsType>::max() / BASE; 829 while (true) { 830 if (isalnum(*src)) { 831 uint32_t digit = b36_char_to_int(*src); 832 if (digit < BASE) 833 seen_digit = true; 834 else 835 break; 836 837 if (mantissa < bitstype_max_div_by_base) { 838 mantissa = (mantissa * BASE) + digit; 839 if (after_decimal) 840 --exponent; 841 } else { 842 if (digit > 0) 843 truncated = true; 844 if (!after_decimal) 845 ++exponent; 846 } 847 ++src; 848 continue; 849 } 850 if (*src == DECIMAL_POINT) { 851 if (after_decimal) { 852 break; // this means that *src points to a second decimal point, ending 853 // the number. 854 } 855 after_decimal = true; 856 ++src; 857 continue; 858 } 859 // The character is neither a hexadecimal digit nor a decimal point. 860 break; 861 } 862 863 if (!seen_digit) 864 return false; 865 866 // Convert the exponent from having a base of 16 to having a base of 2. 867 exponent *= 4; 868 869 if ((*src | 32) == EXPONENT_MARKER) { 870 if (*(src + 1) == '+' || *(src + 1) == '-' || isdigit(*(src + 1))) { 871 ++src; 872 char *temp_str_end; 873 int32_t add_to_exponent = strtointeger<int32_t>(src, &temp_str_end, 10); 874 if (add_to_exponent > 100000) 875 add_to_exponent = 100000; 876 else if (add_to_exponent < -100000) 877 add_to_exponent = -100000; 878 src = temp_str_end; 879 exponent += add_to_exponent; 880 } 881 } 882 *strEnd = const_cast<char *>(src); 883 if (mantissa == 0) { // if we have a 0, then also 0 the exponent. 884 *outputMantissa = 0; 885 *outputExponent = 0; 886 } else { 887 binary_exp_to_float<T>(mantissa, exponent, truncated, outputMantissa, 888 outputExponent); 889 } 890 return true; 891 } 892 893 // Takes a pointer to a string and a pointer to a string pointer. This function 894 // is used as the backend for all of the string to float functions. 895 template <class T> 896 static inline T strtofloatingpoint(const char *__restrict src, 897 char **__restrict strEnd) { 898 using BitsType = typename fputil::FPBits<T>::UIntType; 899 fputil::FPBits<T> result = fputil::FPBits<T>(); 900 const char *original_src = src; 901 bool seen_digit = false; 902 src = first_non_whitespace(src); 903 904 if (*src == '+' || *src == '-') { 905 if (*src == '-') { 906 result.set_sign(true); 907 } 908 ++src; 909 } 910 911 static constexpr char DECIMAL_POINT = '.'; 912 static const char *inf_string = "infinity"; 913 static const char *nan_string = "nan"; 914 915 // bool truncated = false; 916 917 if (isdigit(*src) || *src == DECIMAL_POINT) { // regular number 918 int base = 10; 919 if (is_float_hex_start(src, DECIMAL_POINT)) { 920 base = 16; 921 src += 2; 922 seen_digit = true; 923 } 924 char *new_str_end = nullptr; 925 926 BitsType output_mantissa = 0; 927 uint32_t output_exponent = 0; 928 if (base == 16) { 929 seen_digit = hexadecimal_string_to_float<T>( 930 src, DECIMAL_POINT, &new_str_end, &output_mantissa, &output_exponent); 931 } else { // base is 10 932 seen_digit = decimal_string_to_float<T>( 933 src, DECIMAL_POINT, &new_str_end, &output_mantissa, &output_exponent); 934 } 935 936 if (seen_digit) { 937 src += new_str_end - src; 938 result.set_mantissa(output_mantissa); 939 result.set_unbiased_exponent(output_exponent); 940 } 941 } else if ((*src | 32) == 'n') { // NaN 942 if ((src[1] | 32) == nan_string[1] && (src[2] | 32) == nan_string[2]) { 943 seen_digit = true; 944 src += 3; 945 BitsType nan_mantissa = 0; 946 // this handles the case of `NaN(n-character-sequence)`, where the 947 // n-character-sequence is made of 0 or more letters and numbers in any 948 // order. 949 if (*src == '(') { 950 const char *left_paren = src; 951 ++src; 952 while (isalnum(*src)) 953 ++src; 954 if (*src == ')') { 955 ++src; 956 char *temp_src = 0; 957 if (isdigit(*(left_paren + 1))) { 958 // This is to prevent errors when BitsType is larger than 64 bits, 959 // since strtointeger only supports up to 64 bits. This is actually 960 // more than is required by the specification, which says for the 961 // input type "NAN(n-char-sequence)" that "the meaning of 962 // the n-char sequence is implementation-defined." 963 nan_mantissa = static_cast<BitsType>( 964 strtointeger<uint64_t>(left_paren + 1, &temp_src, 0)); 965 if (*temp_src != ')') 966 nan_mantissa = 0; 967 } 968 } else 969 src = left_paren; 970 } 971 nan_mantissa |= fputil::FloatProperties<T>::QUIET_NAN_MASK; 972 if (result.get_sign()) { 973 result = fputil::FPBits<T>(result.build_nan(nan_mantissa)); 974 result.set_sign(true); 975 } else { 976 result.set_sign(false); 977 result = fputil::FPBits<T>(result.build_nan(nan_mantissa)); 978 } 979 } 980 } else if ((*src | 32) == 'i') { // INF 981 if ((src[1] | 32) == inf_string[1] && (src[2] | 32) == inf_string[2]) { 982 seen_digit = true; 983 if (result.get_sign()) 984 result = result.neg_inf(); 985 else 986 result = result.inf(); 987 if ((src[3] | 32) == inf_string[3] && (src[4] | 32) == inf_string[4] && 988 (src[5] | 32) == inf_string[5] && (src[6] | 32) == inf_string[6] && 989 (src[7] | 32) == inf_string[7]) { 990 // if the string is "INFINITY" then strEnd needs to be set to src + 8. 991 src += 8; 992 } else { 993 src += 3; 994 } 995 } 996 } 997 if (!seen_digit) { // If there is nothing to actually parse, then return 0. 998 if (strEnd != nullptr) 999 *strEnd = const_cast<char *>(original_src); 1000 return T(0); 1001 } 1002 1003 if (strEnd != nullptr) 1004 *strEnd = const_cast<char *>(src); 1005 1006 // This function only does something if T is long double and the platform uses 1007 // special 80 bit long doubles. Otherwise it should be inlined out. 1008 set_implicit_bit<T>(result); 1009 1010 return T(result); 1011 } 1012 1013 } // namespace internal 1014 } // namespace __llvm_libc 1015 1016 #endif // LIBC_SRC_SUPPORT_STR_TO_FLOAT_H 1017