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