floattisf.c 2.3 KB

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