1 //===-- Single-precision 2^x function -------------------------------------===//
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 #include "exp_utils.h"
10 #include "math_utils.h"
11 
12 #include "src/__support/common.h"
13 #include <math.h>
14 
15 #include <stdint.h>
16 
17 #define T exp2f_data.tab
18 #define C exp2f_data.poly
19 #define SHIFT exp2f_data.shift_scaled
20 
21 namespace __llvm_libc {
22 
LLVM_LIBC_ENTRYPOINT(exp2f)23 float LLVM_LIBC_ENTRYPOINT(exp2f)(float x) {
24   uint32_t abstop;
25   uint64_t ki, t;
26   // double_t for better performance on targets with FLT_EVAL_METHOD==2.
27   double_t kd, xd, z, r, r2, y, s;
28 
29   xd = static_cast<double_t>(x);
30   abstop = top12_bits(x) & 0x7ff;
31   if (unlikely(abstop >= top12_bits(128.0f))) {
32     // |x| >= 128 or x is nan.
33     if (as_uint32_bits(x) == as_uint32_bits(-INFINITY))
34       return 0.0f;
35     if (abstop >= top12_bits(INFINITY))
36       return x + x;
37     if (x > 0.0f)
38       return overflow<float>(0);
39     if (x <= -150.0f)
40       return underflow<float>(0);
41     if (x < -149.0f)
42       return may_underflow<float>(0);
43   }
44 
45   // x = k/N + r with r in [-1/(2N), 1/(2N)] and int k.
46   kd = static_cast<double>(xd + SHIFT);
47   ki = as_uint64_bits(kd);
48   kd -= SHIFT; // k/N for int k.
49   r = xd - kd;
50 
51   // exp2(x) = 2^(k/N) * 2^r ~= s * (C0*r^3 + C1*r^2 + C2*r + 1)
52   t = T[ki % N];
53   t += ki << (52 - EXP2F_TABLE_BITS);
54   s = as_double(t);
55   z = C[0] * r + C[1];
56   r2 = r * r;
57   y = C[2] * r + 1;
58   y = z * r2 + y;
59   y = y * s;
60   return static_cast<float>(y);
61 }
62 
63 } // namespace __llvm_libc
64