1 //===-- Single-precision e^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 "src/math/expf.h" 10 #include "exp_utils.h" 11 #include "math_utils.h" 12 13 #include "src/__support/common.h" 14 #include <math.h> 15 16 #include <stdint.h> 17 18 #define InvLn2N exp2f_data.invln2_scaled 19 #define T exp2f_data.tab 20 #define C exp2f_data.poly_scaled 21 #define SHIFT exp2f_data.shift 22 23 namespace __llvm_libc { 24 25 LLVM_LIBC_FUNCTION(float, expf, (float x)) { 26 uint32_t abstop; 27 uint64_t ki, t; 28 // double_t for better performance on targets with FLT_EVAL_METHOD == 2. 29 double_t kd, xd, z, r, r2, y, s; 30 31 xd = static_cast<double_t>(x); 32 abstop = top12_bits(x) & 0x7ff; 33 if (unlikely(abstop >= top12_bits(88.0f))) { 34 // |x| >= 88 or x is nan. 35 if (as_uint32_bits(x) == as_uint32_bits(-INFINITY)) 36 return 0.0f; 37 if (abstop >= top12_bits(INFINITY)) 38 return x + x; 39 if (x > as_float(0x42b17217)) // x > log(0x1p128) ~= 88.72 40 return overflow<float>(0); 41 if (x < as_float(0xc2cff1b4)) // x < log(0x1p-150) ~= -103.97 42 return underflow<float>(0); 43 if (x < as_float(0xc2ce8ecf)) // x < log(0x1p-149) ~= -103.28 44 return may_underflow<float>(0); 45 } 46 47 // x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k. 48 z = InvLn2N * xd; 49 50 // Round and convert z to int, the result is in [-150*N, 128*N] and 51 // ideally nearest int is used, otherwise the magnitude of r can be 52 // bigger which gives larger approximation error. 53 kd = static_cast<double>(z + SHIFT); 54 ki = as_uint64_bits(kd); 55 kd -= SHIFT; 56 r = z - kd; 57 58 // exp(x) = 2^(k/N) * 2^(r/N) ~= s *(C0*r^3 + C1*r^2 + C2*r + 1) 59 t = T[ki % N]; 60 t += ki << (52 - EXP2F_TABLE_BITS); 61 s = as_double(t); 62 z = C[0] * r + C[1]; 63 r2 = r * r; 64 y = C[2] * r + 1; 65 y = z * r2 + y; 66 y = y * s; 67 return static_cast<float>(y); 68 } 69 70 } // namespace __llvm_libc 71