450 lines · c
1//===-- Implementation header for exp ---------------------------*- C++ -*-===//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-exception6//7//===----------------------------------------------------------------------===//8 9#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_EXP_H10#define LLVM_LIBC_SRC___SUPPORT_MATH_EXP_H11 12#include "exp_constants.h"13#include "exp_utils.h"14#include "src/__support/CPP/bit.h"15#include "src/__support/CPP/optional.h"16#include "src/__support/FPUtil/FEnvImpl.h"17#include "src/__support/FPUtil/FPBits.h"18#include "src/__support/FPUtil/PolyEval.h"19#include "src/__support/FPUtil/double_double.h"20#include "src/__support/FPUtil/dyadic_float.h"21#include "src/__support/FPUtil/multiply_add.h"22#include "src/__support/FPUtil/nearest_integer.h"23#include "src/__support/FPUtil/rounding_mode.h"24#include "src/__support/FPUtil/triple_double.h"25#include "src/__support/common.h"26#include "src/__support/integer_literals.h"27#include "src/__support/macros/config.h"28#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY29 30namespace LIBC_NAMESPACE_DECL {31 32using fputil::DoubleDouble;33using fputil::TripleDouble;34using Float128 = typename fputil::DyadicFloat<128>;35 36using LIBC_NAMESPACE::operator""_u128;37 38// log2(e)39static constexpr double LOG2_E = 0x1.71547652b82fep+0;40 41// Error bounds:42// Errors when using double precision.43static constexpr double EXP_ERR_D = 0x1.8p-63;44 45#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS46// Errors when using double-double precision.47static constexpr double EXP_ERR_DD = 0x1.0p-99;48#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS49 50// -2^-12 * log(2)51// > a = -2^-12 * log(2);52// > b = round(a, 30, RN);53// > c = round(a - b, 30, RN);54// > d = round(a - b - c, D, RN);55// Errors < 1.5 * 2^-13356static constexpr double MLOG_2_EXP2_M12_HI = -0x1.62e42ffp-13;57static constexpr double MLOG_2_EXP2_M12_MID = 0x1.718432a1b0e26p-47;58 59#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS60static constexpr double MLOG_2_EXP2_M12_MID_30 = 0x1.718432ap-47;61static constexpr double MLOG_2_EXP2_M12_LO = 0x1.b0e2633fe0685p-79;62#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS63 64namespace {65 66// Polynomial approximations with double precision:67// Return expm1(dx) / x ~ 1 + dx / 2 + dx^2 / 6 + dx^3 / 24.68// For |dx| < 2^-13 + 2^-30:69// | output - expm1(dx) / dx | < 2^-51.70LIBC_INLINE static double poly_approx_d(double dx) {71 // dx^272 double dx2 = dx * dx;73 // c0 = 1 + dx / 274 double c0 = fputil::multiply_add(dx, 0.5, 1.0);75 // c1 = 1/6 + dx / 2476 double c1 =77 fputil::multiply_add(dx, 0x1.5555555555555p-5, 0x1.5555555555555p-3);78 // p = dx^2 * c1 + c0 = 1 + dx / 2 + dx^2 / 6 + dx^3 / 2479 double p = fputil::multiply_add(dx2, c1, c0);80 return p;81}82 83#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS84// Polynomial approximation with double-double precision:85// Return exp(dx) ~ 1 + dx + dx^2 / 2 + ... + dx^6 / 72086// For |dx| < 2^-13 + 2^-30:87// | output - exp(dx) | < 2^-10188LIBC_INLINE static DoubleDouble poly_approx_dd(const DoubleDouble &dx) {89 // Taylor polynomial.90 constexpr DoubleDouble COEFFS[] = {91 {0, 0x1p0}, // 192 {0, 0x1p0}, // 193 {0, 0x1p-1}, // 1/294 {0x1.5555555555555p-57, 0x1.5555555555555p-3}, // 1/695 {0x1.5555555555555p-59, 0x1.5555555555555p-5}, // 1/2496 {0x1.1111111111111p-63, 0x1.1111111111111p-7}, // 1/12097 {-0x1.f49f49f49f49fp-65, 0x1.6c16c16c16c17p-10}, // 1/72098 };99 100 DoubleDouble p = fputil::polyeval(dx, COEFFS[0], COEFFS[1], COEFFS[2],101 COEFFS[3], COEFFS[4], COEFFS[5], COEFFS[6]);102 return p;103}104 105// Polynomial approximation with 128-bit precision:106// Return exp(dx) ~ 1 + dx + dx^2 / 2 + ... + dx^7 / 5040107// For |dx| < 2^-13 + 2^-30:108// | output - exp(dx) | < 2^-126.109LIBC_INLINE static Float128 poly_approx_f128(const Float128 &dx) {110 constexpr Float128 COEFFS_128[]{111 {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0112 {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0113 {Sign::POS, -128, 0x80000000'00000000'00000000'00000000_u128}, // 0.5114 {Sign::POS, -130, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1/6115 {Sign::POS, -132, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1/24116 {Sign::POS, -134, 0x88888888'88888888'88888888'88888889_u128}, // 1/120117 {Sign::POS, -137, 0xb60b60b6'0b60b60b'60b60b60'b60b60b6_u128}, // 1/720118 {Sign::POS, -140, 0xd00d00d0'0d00d00d'00d00d00'd00d00d0_u128}, // 1/5040119 };120 121 Float128 p = fputil::polyeval(dx, COEFFS_128[0], COEFFS_128[1], COEFFS_128[2],122 COEFFS_128[3], COEFFS_128[4], COEFFS_128[5],123 COEFFS_128[6], COEFFS_128[7]);124 return p;125}126 127// Compute exp(x) using 128-bit precision.128// TODO(lntue): investigate triple-double precision implementation for this129// step.130LIBC_INLINE static Float128 exp_f128(double x, double kd, int idx1, int idx2) {131 // Recalculate dx:132 133 double t1 = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact134 double t2 = kd * MLOG_2_EXP2_M12_MID_30; // exact135 double t3 = kd * MLOG_2_EXP2_M12_LO; // Error < 2^-133136 137 Float128 dx = fputil::quick_add(138 Float128(t1), fputil::quick_add(Float128(t2), Float128(t3)));139 140 // TODO: Skip recalculating exp_mid1 and exp_mid2.141 Float128 exp_mid1 =142 fputil::quick_add(Float128(EXP2_MID1[idx1].hi),143 fputil::quick_add(Float128(EXP2_MID1[idx1].mid),144 Float128(EXP2_MID1[idx1].lo)));145 146 Float128 exp_mid2 =147 fputil::quick_add(Float128(EXP2_MID2[idx2].hi),148 fputil::quick_add(Float128(EXP2_MID2[idx2].mid),149 Float128(EXP2_MID2[idx2].lo)));150 151 Float128 exp_mid = fputil::quick_mul(exp_mid1, exp_mid2);152 153 Float128 p = poly_approx_f128(dx);154 155 Float128 r = fputil::quick_mul(exp_mid, p);156 157 r.exponent += static_cast<int>(kd) >> 12;158 159 return r;160}161 162// Compute exp(x) with double-double precision.163LIBC_INLINE static DoubleDouble exp_double_double(double x, double kd,164 const DoubleDouble &exp_mid) {165 // Recalculate dx:166 // dx = x - k * 2^-12 * log(2)167 double t1 = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact168 double t2 = kd * MLOG_2_EXP2_M12_MID_30; // exact169 double t3 = kd * MLOG_2_EXP2_M12_LO; // Error < 2^-130170 171 DoubleDouble dx = fputil::exact_add(t1, t2);172 dx.lo += t3;173 174 // Degree-6 Taylor polynomial approximation in double-double precision.175 // | p - exp(x) | < 2^-100.176 DoubleDouble p = poly_approx_dd(dx);177 178 // Error bounds: 2^-99.179 DoubleDouble r = fputil::quick_mult(exp_mid, p);180 181 return r;182}183#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS184 185// Check for exceptional cases when186// |x| <= 2^-53 or x < log(2^-1075) or x >= 0x1.6232bdd7abcd3p+9187LIBC_INLINE static double set_exceptional(double x) {188 using FPBits = typename fputil::FPBits<double>;189 FPBits xbits(x);190 191 uint64_t x_u = xbits.uintval();192 uint64_t x_abs = xbits.abs().uintval();193 194 // |x| <= 2^-53195 if (x_abs <= 0x3ca0'0000'0000'0000ULL) {196 // exp(x) ~ 1 + x197 return 1 + x;198 }199 200 // x <= log(2^-1075) || x >= 0x1.6232bdd7abcd3p+9 or inf/nan.201 202 // x <= log(2^-1075) or -inf/nan203 if (x_u >= 0xc087'4910'd52d'3052ULL) {204 // exp(-Inf) = 0205 if (xbits.is_inf())206 return 0.0;207 208 // exp(nan) = nan209 if (xbits.is_nan())210 return x;211 212 if (fputil::quick_get_round() == FE_UPWARD)213 return FPBits::min_subnormal().get_val();214 fputil::set_errno_if_required(ERANGE);215 fputil::raise_except_if_required(FE_UNDERFLOW);216 return 0.0;217 }218 219 // x >= round(log(MAX_NORMAL), D, RU) = 0x1.62e42fefa39fp+9 or +inf/nan220 // x is finite221 if (x_u < 0x7ff0'0000'0000'0000ULL) {222 int rounding = fputil::quick_get_round();223 if (rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO)224 return FPBits::max_normal().get_val();225 226 fputil::set_errno_if_required(ERANGE);227 fputil::raise_except_if_required(FE_OVERFLOW);228 }229 // x is +inf or nan230 return x + FPBits::inf().get_val();231}232 233} // namespace234 235namespace math {236 237LIBC_INLINE static double exp(double x) {238 using FPBits = typename fputil::FPBits<double>;239 FPBits xbits(x);240 241 uint64_t x_u = xbits.uintval();242 243 // Upper bound: max normal number = 2^1023 * (2 - 2^-52)244 // > round(log (2^1023 ( 2 - 2^-52 )), D, RU) = 0x1.62e42fefa39fp+9245 // > round(log (2^1023 ( 2 - 2^-52 )), D, RD) = 0x1.62e42fefa39efp+9246 // > round(log (2^1023 ( 2 - 2^-52 )), D, RN) = 0x1.62e42fefa39efp+9247 // > round(exp(0x1.62e42fefa39fp+9), D, RN) = infty248 249 // Lower bound: min denormal number / 2 = 2^-1075250 // > round(log(2^-1075), D, RN) = -0x1.74910d52d3052p9251 252 // Another lower bound: min normal number = 2^-1022253 // > round(log(2^-1022), D, RN) = -0x1.6232bdd7abcd2p9254 255 // x < log(2^-1075) or x >= 0x1.6232bdd7abcd3p+9 or |x| < 2^-53.256 if (LIBC_UNLIKELY(x_u >= 0xc0874910d52d3052 ||257 (x_u < 0xbca0000000000000 && x_u >= 0x40862e42fefa39f0) ||258 x_u < 0x3ca0000000000000)) {259 return set_exceptional(x);260 }261 262 // Now log(2^-1075) <= x <= -2^-53 or 2^-53 <= x < log(2^1023 * (2 - 2^-52))263 264 // Range reduction:265 // Let x = log(2) * (hi + mid1 + mid2) + lo266 // in which:267 // hi is an integer268 // mid1 * 2^6 is an integer269 // mid2 * 2^12 is an integer270 // then:271 // exp(x) = 2^hi * 2^(mid1) * 2^(mid2) * exp(lo).272 // With this formula:273 // - multiplying by 2^hi is exact and cheap, simply by adding the exponent274 // field.275 // - 2^(mid1) and 2^(mid2) are stored in 2 x 64-element tables.276 // - exp(lo) ~ 1 + lo + a0 * lo^2 + ...277 //278 // They can be defined by:279 // hi + mid1 + mid2 = 2^(-12) * round(2^12 * log_2(e) * x)280 // If we store L2E = round(log2(e), D, RN), then:281 // log2(e) - L2E ~ 1.5 * 2^(-56)282 // So the errors when computing in double precision is:283 // | x * 2^12 * log_2(e) - D(x * 2^12 * L2E) | <=284 // <= | x * 2^12 * log_2(e) - x * 2^12 * L2E | +285 // + | x * 2^12 * L2E - D(x * 2^12 * L2E) |286 // <= 2^12 * ( |x| * 1.5 * 2^-56 + eps(x)) for RN287 // 2^12 * ( |x| * 1.5 * 2^-56 + 2*eps(x)) for other rounding modes.288 // So if:289 // hi + mid1 + mid2 = 2^(-12) * round(x * 2^12 * L2E) is computed entirely290 // in double precision, the reduced argument:291 // lo = x - log(2) * (hi + mid1 + mid2) is bounded by:292 // |lo| <= 2^-13 + (|x| * 1.5 * 2^-56 + 2*eps(x))293 // < 2^-13 + (1.5 * 2^9 * 1.5 * 2^-56 + 2*2^(9 - 52))294 // < 2^-13 + 2^-41295 //296 297 // The following trick computes the round(x * L2E) more efficiently298 // than using the rounding instructions, with the tradeoff for less accuracy,299 // and hence a slightly larger range for the reduced argument `lo`.300 //301 // To be precise, since |x| < |log(2^-1075)| < 1.5 * 2^9,302 // |x * 2^12 * L2E| < 1.5 * 2^9 * 1.5 < 2^23,303 // So we can fit the rounded result round(x * 2^12 * L2E) in int32_t.304 // Thus, the goal is to be able to use an additional addition and fixed width305 // shift to get an int32_t representing round(x * 2^12 * L2E).306 //307 // Assuming int32_t using 2-complement representation, since the mantissa part308 // of a double precision is unsigned with the leading bit hidden, if we add an309 // extra constant C = 2^e1 + 2^e2 with e1 > e2 >= 2^25 to the product, the310 // part that are < 2^e2 in resulted mantissa of (x*2^12*L2E + C) can be311 // considered as a proper 2-complement representations of x*2^12*L2E.312 //313 // One small problem with this approach is that the sum (x*2^12*L2E + C) in314 // double precision is rounded to the least significant bit of the dorminant315 // factor C. In order to minimize the rounding errors from this addition, we316 // want to minimize e1. Another constraint that we want is that after317 // shifting the mantissa so that the least significant bit of int32_t318 // corresponds to the unit bit of (x*2^12*L2E), the sign is correct without319 // any adjustment. So combining these 2 requirements, we can choose320 // C = 2^33 + 2^32, so that the sign bit corresponds to 2^31 bit, and hence321 // after right shifting the mantissa, the resulting int32_t has correct sign.322 // With this choice of C, the number of mantissa bits we need to shift to the323 // right is: 52 - 33 = 19.324 //325 // Moreover, since the integer right shifts are equivalent to rounding down,326 // we can add an extra 0.5 so that it will become round-to-nearest, tie-to-327 // +infinity. So in particular, we can compute:328 // hmm = x * 2^12 * L2E + C,329 // where C = 2^33 + 2^32 + 2^-1, then if330 // k = int32_t(lower 51 bits of double(x * 2^12 * L2E + C) >> 19),331 // the reduced argument:332 // lo = x - log(2) * 2^-12 * k is bounded by:333 // |lo| <= 2^-13 + 2^-41 + 2^-12*2^-19334 // = 2^-13 + 2^-31 + 2^-41.335 //336 // Finally, notice that k only uses the mantissa of x * 2^12 * L2E, so the337 // exponent 2^12 is not needed. So we can simply define338 // C = 2^(33 - 12) + 2^(32 - 12) + 2^(-13 - 12), and339 // k = int32_t(lower 51 bits of double(x * L2E + C) >> 19).340 341 // Rounding errors <= 2^-31 + 2^-41.342 double tmp = fputil::multiply_add(x, LOG2_E, 0x1.8000'0000'4p21);343 int k = static_cast<int>(cpp::bit_cast<uint64_t>(tmp) >> 19);344 double kd = static_cast<double>(k);345 346 uint32_t idx1 = (k >> 6) & 0x3f;347 uint32_t idx2 = k & 0x3f;348 int hi = k >> 12;349 350 bool denorm = (hi <= -1022);351 352 DoubleDouble exp_mid1{EXP2_MID1[idx1].mid, EXP2_MID1[idx1].hi};353 DoubleDouble exp_mid2{EXP2_MID2[idx2].mid, EXP2_MID2[idx2].hi};354 355 DoubleDouble exp_mid = fputil::quick_mult(exp_mid1, exp_mid2);356 357 // |x - (hi + mid1 + mid2) * log(2) - dx| < 2^11 * eps(M_LOG_2_EXP2_M12.lo)358 // = 2^11 * 2^-13 * 2^-52359 // = 2^-54.360 // |dx| < 2^-13 + 2^-30.361 double lo_h = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact362 double dx = fputil::multiply_add(kd, MLOG_2_EXP2_M12_MID, lo_h);363 364 // We use the degree-4 Taylor polynomial to approximate exp(lo):365 // exp(lo) ~ 1 + lo + lo^2 / 2 + lo^3 / 6 + lo^4 / 24 = 1 + lo * P(lo)366 // So that the errors are bounded by:367 // |P(lo) - expm1(lo)/lo| < |lo|^4 / 64 < 2^(-13 * 4) / 64 = 2^-58368 // Let P_ be an evaluation of P where all intermediate computations are in369 // double precision. Using either Horner's or Estrin's schemes, the evaluated370 // errors can be bounded by:371 // |P_(dx) - P(dx)| < 2^-51372 // => |dx * P_(dx) - expm1(lo) | < 1.5 * 2^-64373 // => 2^(mid1 + mid2) * |dx * P_(dx) - expm1(lo)| < 1.5 * 2^-63.374 // Since we approximate375 // 2^(mid1 + mid2) ~ exp_mid.hi + exp_mid.lo,376 // We use the expression:377 // (exp_mid.hi + exp_mid.lo) * (1 + dx * P_(dx)) ~378 // ~ exp_mid.hi + (exp_mid.hi * dx * P_(dx) + exp_mid.lo)379 // with errors bounded by 1.5 * 2^-63.380 381 double mid_lo = dx * exp_mid.hi;382 383 // Approximate expm1(dx)/dx ~ 1 + dx / 2 + dx^2 / 6 + dx^3 / 24.384 double p = poly_approx_d(dx);385 386 double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);387 388#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS389 if (LIBC_UNLIKELY(denorm)) {390 return ziv_test_denorm</*SKIP_ZIV_TEST=*/true>(hi, exp_mid.hi, lo,391 EXP_ERR_D)392 .value();393 } else {394 // to multiply by 2^hi, a fast way is to simply add hi to the exponent395 // field.396 int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;397 double r =398 cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(exp_mid.hi + lo));399 return r;400 }401#else402 if (LIBC_UNLIKELY(denorm)) {403 if (auto r = ziv_test_denorm(hi, exp_mid.hi, lo, EXP_ERR_D);404 LIBC_LIKELY(r.has_value()))405 return r.value();406 } else {407 double upper = exp_mid.hi + (lo + EXP_ERR_D);408 double lower = exp_mid.hi + (lo - EXP_ERR_D);409 410 if (LIBC_LIKELY(upper == lower)) {411 // to multiply by 2^hi, a fast way is to simply add hi to the exponent412 // field.413 int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;414 double r = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper));415 return r;416 }417 }418 419 // Use double-double420 DoubleDouble r_dd = exp_double_double(x, kd, exp_mid);421 422 if (LIBC_UNLIKELY(denorm)) {423 if (auto r = ziv_test_denorm(hi, r_dd.hi, r_dd.lo, EXP_ERR_DD);424 LIBC_LIKELY(r.has_value()))425 return r.value();426 } else {427 double upper_dd = r_dd.hi + (r_dd.lo + EXP_ERR_DD);428 double lower_dd = r_dd.hi + (r_dd.lo - EXP_ERR_DD);429 430 if (LIBC_LIKELY(upper_dd == lower_dd)) {431 int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;432 double r =433 cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper_dd));434 return r;435 }436 }437 438 // Use 128-bit precision439 Float128 r_f128 = exp_f128(x, kd, idx1, idx2);440 441 return static_cast<double>(r_f128);442#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS443}444 445} // namespace math446 447} // namespace LIBC_NAMESPACE_DECL448 449#endif // LLVM_LIBC_SRC___SUPPORT_MATH_EXP_H450