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