floattixf.c 2.5 KB

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