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