floattidf.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //===-- floattidf.c - Implement __floattidf -------------------------------===//
  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. // This file implements __floattidf for the compiler_rt library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "int_lib.h"
  13. #ifdef CRT_HAS_128BIT
  14. // Returns: convert a to a double, rounding toward even.
  15. // Assumption: double is a IEEE 64 bit floating point type
  16. // ti_int is a 128 bit integral type
  17. // seee eeee eeee mmmm mmmm mmmm mmmm mmmm | mmmm mmmm mmmm mmmm mmmm mmmm mmmm
  18. // mmmm
  19. COMPILER_RT_ABI double __floattidf(ti_int a) {
  20. if (a == 0)
  21. return 0.0;
  22. const unsigned N = sizeof(ti_int) * CHAR_BIT;
  23. const ti_int s = a >> (N - 1);
  24. a = (a ^ s) - s;
  25. int sd = N - __clzti2(a); // number of significant digits
  26. int e = sd - 1; // exponent
  27. if (sd > DBL_MANT_DIG) {
  28. // start: 0000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQxxxxxxxxxxxxxxxxxx
  29. // finish: 000000000000000000000000000000000000001xxxxxxxxxxxxxxxxxxxxxxPQR
  30. // 12345678901234567890123456
  31. // 1 = msb 1 bit
  32. // P = bit DBL_MANT_DIG-1 bits to the right of 1
  33. // Q = bit DBL_MANT_DIG bits to the right of 1
  34. // R = "or" of all bits to the right of Q
  35. switch (sd) {
  36. case DBL_MANT_DIG + 1:
  37. a <<= 1;
  38. break;
  39. case DBL_MANT_DIG + 2:
  40. break;
  41. default:
  42. a = ((tu_int)a >> (sd - (DBL_MANT_DIG + 2))) |
  43. ((a & ((tu_int)(-1) >> ((N + DBL_MANT_DIG + 2) - sd))) != 0);
  44. };
  45. // finish:
  46. a |= (a & 4) != 0; // Or P into R
  47. ++a; // round - this step may add a significant bit
  48. a >>= 2; // dump Q and R
  49. // a is now rounded to DBL_MANT_DIG or DBL_MANT_DIG+1 bits
  50. if (a & ((tu_int)1 << DBL_MANT_DIG)) {
  51. a >>= 1;
  52. ++e;
  53. }
  54. // a is now rounded to DBL_MANT_DIG bits
  55. } else {
  56. a <<= (DBL_MANT_DIG - sd);
  57. // a is now rounded to DBL_MANT_DIG bits
  58. }
  59. double_bits fb;
  60. fb.u.s.high = ((su_int)s & 0x80000000) | // sign
  61. ((e + 1023) << 20) | // exponent
  62. ((su_int)(a >> 32) & 0x000FFFFF); // mantissa-high
  63. fb.u.s.low = (su_int)a; // mantissa-low
  64. return fb.f;
  65. }
  66. #endif // CRT_HAS_128BIT