[libc-commits] [libc] [llvm] [libc][math] Optimize exp and share double-precision evaluation with exp2. (PR #233018)
via libc-commits
libc-commits at lists.llvm.org
Thu Oct 22 12:00:20 PDT 2026
https://github.com/lntue updated https://github.com/llvm/llvm-project/pull/233018
>From f96ed5f408b6a731c527feb2973874e3ab070a55 Mon Sep 17 00:00:00 2001
From: Tue Ly <lntue.h at gmail.com>
Date: Tue, 20 Oct 2026 14:47:59 +0000
Subject: [PATCH 1/3] [libc][math] Optimize exp and share double-precision
evaluation with exp2.
Refactor double-precision exp to share most of the computations with exp2,
and adding support for `LIBC_MATH_HAS_SMALL_TABLES` and
`LIBC_MATH_HAS_SKIP_ACCURATE_PASS`.
Assisted by: Gemini is used for performance and code size analysis and refactoring.
---
libc/src/__support/FPUtil/fp_bitwise.h | 49 ++
libc/src/__support/math/CMakeLists.txt | 52 +-
libc/src/__support/math/exp.h | 446 +-----------------
libc/src/__support/math/exp2_accurate_128.h | 63 ++-
libc/src/__support/math/exp2_double_eval.h | 6 +-
libc/src/__support/math/exp_double_eval.h | 153 ++++++
libc/src/__support/math/exp_double_utils.h | 11 +-
libc/src/__support/math/exp_utils.h | 164 +++----
.../src/__support/FPUtil/fp_bitwise_test.cpp | 21 +
libc/test/src/math/CMakeLists.txt | 4 +
libc/test/src/math/exp_test.cpp | 248 ++++++----
libc/test/src/math/smoke/CMakeLists.txt | 3 +
libc/test/src/math/smoke/exp_test.cpp | 115 +++--
.../llvm-project-overlay/libc/BUILD.bazel | 52 +-
.../libc/test/src/math/BUILD.bazel | 8 +-
.../libc/test/src/math/smoke/BUILD.bazel | 8 +-
16 files changed, 696 insertions(+), 707 deletions(-)
create mode 100644 libc/src/__support/math/exp_double_eval.h
diff --git a/libc/src/__support/FPUtil/fp_bitwise.h b/libc/src/__support/FPUtil/fp_bitwise.h
index 5902b8e30aac5d..2615cb97510c25 100644
--- a/libc/src/__support/FPUtil/fp_bitwise.h
+++ b/libc/src/__support/FPUtil/fp_bitwise.h
@@ -184,6 +184,55 @@ fp_not(T a) {
return res.get_val();
}
+// Directly add an integer `hi` to the exponent field of a floating-point value
+// `r`. It is equivalent to scaling `r` by 2^hi when both `r` and the resulting
+// bits are normal.
+// The default implementation bit-casts `r` to its unsigned storage type, shifts
+// `hi` to the exponent field, adds the shifted `hi` to `r`'s bits, and
+// bit-casts the result back to `T`.
+// When SSE2 or AArch64 NEON is available, `float` and `double` use SIMD
+// intrinsics to keep `r` in the FP/SIMD register and perform the shift and
+// integer addition directly in the FP/SIMD registers, avoiding a GPR
+// round-trip.
+template <typename T>
+LIBC_ALWAYS_INLINE constexpr cpp::enable_if_t<cpp::is_floating_point_v<T>, T>
+scale_exp2(T r, int hi) {
+ if (!cpp::is_constant_evaluated()) {
+#ifdef LIBC_TARGET_CPU_HAS_SSE2
+ if constexpr (cpp::is_same_v<T, float>) {
+ __m128i v_exp =
+ _mm_slli_epi32(_mm_cvtsi32_si128(hi), FPBits<T>::FRACTION_LEN);
+ __m128i v_r = _mm_castps_si128(_mm_set_ss(r));
+ return _mm_cvtss_f32(_mm_castsi128_ps(_mm_add_epi32(v_exp, v_r)));
+ }
+ if constexpr (cpp::is_same_v<T, double>) {
+ __m128i v_exp =
+ _mm_slli_epi64(_mm_cvtsi32_si128(hi), FPBits<T>::FRACTION_LEN);
+ __m128i v_r = _mm_castpd_si128(_mm_set_sd(r));
+ return _mm_cvtsd_f64(_mm_castsi128_pd(_mm_add_epi64(v_exp, v_r)));
+ }
+#elif defined(LIBC_TARGET_ARCH_IS_AARCH64) && defined(__ARM_NEON)
+ if constexpr (cpp::is_same_v<T, float>) {
+ uint32x2_t v_exp = vshl_n_u32(vdup_n_u32(static_cast<uint32_t>(hi)),
+ FPBits<T>::FRACTION_LEN);
+ uint32x2_t v_r = vreinterpret_u32_f32(vdup_n_f32(r));
+ return vget_lane_f32(vreinterpret_f32_u32(vadd_u32(v_exp, v_r)), 0);
+ }
+ if constexpr (cpp::is_same_v<T, double>) {
+ uint64x1_t v_exp = vshl_n_u64(vdup_n_u64(static_cast<uint64_t>(hi)),
+ FPBits<T>::FRACTION_LEN);
+ uint64x1_t v_r = vreinterpret_u64_f64(vdup_n_f64(r));
+ return vget_lane_f64(vreinterpret_f64_u64(vadd_u64(v_exp, v_r)), 0);
+ }
+#endif
+ }
+ using StorageType = typename FPBits<T>::StorageType;
+ StorageType exp_hi = static_cast<StorageType>(static_cast<StorageType>(hi)
+ << FPBits<T>::FRACTION_LEN);
+ return FPBits<T>(static_cast<StorageType>(exp_hi + FPBits<T>(r).uintval()))
+ .get_val();
+}
+
} // namespace fputil
} // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/__support/math/CMakeLists.txt b/libc/src/__support/math/CMakeLists.txt
index 58f0730cba5756..03dd7c1970bf8d 100644
--- a/libc/src/__support/math/CMakeLists.txt
+++ b/libc/src/__support/math/CMakeLists.txt
@@ -4257,58 +4257,66 @@ add_header_library(
libc.src.__support.FPUtil.double_double
libc.src.__support.FPUtil.fenv_impl
libc.src.__support.FPUtil.fp_bits
+ libc.src.__support.FPUtil.fp_bitwise
libc.src.__support.FPUtil.multiply_add
libc.src.__support.FPUtil.rounding_mode
libc.src.__support.common
libc.src.__support.macros.attributes
libc.src.__support.macros.config
libc.src.__support.macros.optimization
- libc.src.__support.macros.properties.architectures
libc.src.__support.macros.properties.cpu_features
)
add_header_library(
- exp
+ exp_double_utils
HDRS
- exp.h
+ exp_double_utils.h
DEPENDS
- .exp_constants
.exp_utils
- libc.src.__support.CPP.bit
- libc.src.__support.CPP.optional
- libc.src.__support.FPUtil.dyadic_float
+ libc.hdr.errno_macros
libc.src.__support.FPUtil.fenv_impl
libc.src.__support.FPUtil.fp_bits
+ libc.src.__support.FPUtil.fp_bitwise
libc.src.__support.FPUtil.multiply_add
- libc.src.__support.FPUtil.nearest_integer
- libc.src.__support.FPUtil.polyeval
- libc.src.__support.FPUtil.rounding_mode
- libc.src.__support.FPUtil.triple_double
- libc.src.__support.integer_literals
+ libc.src.__support.common
+ libc.src.__support.macros.attributes
+ libc.src.__support.macros.config
libc.src.__support.macros.optimization
)
add_header_library(
- exp_double_utils
+ exp2_double_eval
HDRS
- exp_double_utils.h
+ exp2_double_eval.h
DEPENDS
+ .exp_double_utils
.exp_utils
- libc.hdr.errno_macros
- libc.src.__support.CPP.bit
- libc.src.__support.FPUtil.fenv_impl
+ libc.src.__support.FPUtil.double_double
libc.src.__support.FPUtil.fp_bits
libc.src.__support.FPUtil.multiply_add
+ libc.src.__support.FPUtil.nearest_integer
libc.src.__support.common
libc.src.__support.macros.attributes
libc.src.__support.macros.config
libc.src.__support.macros.optimization
+ libc.src.__support.macros.properties.cpu_features
)
add_header_library(
- exp2_double_eval
+ exp2
HDRS
- exp2_double_eval.h
+ exp2.h
+ DEPENDS
+ .exp2_double_eval
+ libc.src.__support.common
+ libc.src.__support.macros.config
+ libc.src.__support.macros.optimization
+)
+
+add_header_library(
+ exp_double_eval
+ HDRS
+ exp_double_eval.h
DEPENDS
.exp_double_utils
.exp_utils
@@ -4324,11 +4332,11 @@ add_header_library(
)
add_header_library(
- exp2
+ exp
HDRS
- exp2.h
+ exp.h
DEPENDS
- .exp2_double_eval
+ .exp_double_eval
libc.src.__support.common
libc.src.__support.macros.config
libc.src.__support.macros.optimization
diff --git a/libc/src/__support/math/exp.h b/libc/src/__support/math/exp.h
index dfb2a2efc5e793..b2bcb2fd3dedc7 100644
--- a/libc/src/__support/math/exp.h
+++ b/libc/src/__support/math/exp.h
@@ -1,454 +1,34 @@
-//===-- Implementation header for exp ---------------------------*- C++ -*-===//
+//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Implementation header for exp.
+///
+//===----------------------------------------------------------------------===//
#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_EXP_H
#define LLVM_LIBC_SRC___SUPPORT_MATH_EXP_H
-#include "exp_constants.h"
-#include "exp_utils.h"
-#include "src/__support/CPP/bit.h"
-#include "src/__support/CPP/optional.h"
-#include "src/__support/FPUtil/FEnvImpl.h"
-#include "src/__support/FPUtil/FPBits.h"
-#include "src/__support/FPUtil/PolyEval.h"
-#include "src/__support/FPUtil/double_double.h"
-#include "src/__support/FPUtil/dyadic_float.h"
-#include "src/__support/FPUtil/multiply_add.h"
-#include "src/__support/FPUtil/nearest_integer.h"
-#include "src/__support/FPUtil/rounding_mode.h"
-#include "src/__support/FPUtil/triple_double.h"
#include "src/__support/common.h"
-#include "src/__support/integer_literals.h"
#include "src/__support/macros/config.h"
-#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
+#include "src/__support/macros/optimization.h"
-namespace LIBC_NAMESPACE_DECL {
+#include "src/__support/math/exp_double_eval.h"
+#define LIBC_MATH_EXP_IMPL double_eval
+namespace LIBC_NAMESPACE_DECL {
namespace math {
-namespace exp_internal {
-
-using fputil::DoubleDouble;
-using fputil::TripleDouble;
-using DFloat128 = typename fputil::DyadicFloat<128>;
-
-using LIBC_NAMESPACE::operator""_u128;
-
-// log2(e)
-LIBC_INLINE_VAR constexpr double LOG2_E = 0x1.71547652b82fep+0;
-
-// Error bounds:
-// Errors when using double precision.
-LIBC_INLINE_VAR constexpr double EXP_ERR_D = 0x1.8p-63;
-
-#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-// Errors when using double-double precision.
-LIBC_INLINE_VAR constexpr double EXP_ERR_DD = 0x1.0p-99;
-#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-
-// -2^-12 * log(2)
-// > a = -2^-12 * log(2);
-// > b = round(a, 30, RN);
-// > c = round(a - b, 30, RN);
-// > d = round(a - b - c, D, RN);
-// Errors < 1.5 * 2^-133
-LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_M12_HI = -0x1.62e42ffp-13;
-LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_M12_MID = 0x1.718432a1b0e26p-47;
-
-#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_M12_MID_30 = 0x1.718432ap-47;
-LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_M12_LO = 0x1.b0e2633fe0685p-79;
-#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-
-// Polynomial approximations with double precision:
-// Return expm1(dx) / x ~ 1 + dx / 2 + dx^2 / 6 + dx^3 / 24.
-// For |dx| < 2^-13 + 2^-30:
-// | output - expm1(dx) / dx | < 2^-51.
-LIBC_INLINE double poly_approx_d(double dx) {
- // dx^2
- double dx2 = dx * dx;
- // c0 = 1 + dx / 2
- double c0 = fputil::multiply_add(dx, 0.5, 1.0);
- // c1 = 1/6 + dx / 24
- double c1 =
- fputil::multiply_add(dx, 0x1.5555555555555p-5, 0x1.5555555555555p-3);
- // p = dx^2 * c1 + c0 = 1 + dx / 2 + dx^2 / 6 + dx^3 / 24
- double p = fputil::multiply_add(dx2, c1, c0);
- return p;
-}
-
-#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-// Polynomial approximation with double-double precision:
-// Return exp(dx) ~ 1 + dx + dx^2 / 2 + ... + dx^6 / 720
-// For |dx| < 2^-13 + 2^-30:
-// | output - exp(dx) | < 2^-101
-LIBC_INLINE DoubleDouble poly_approx_dd(const DoubleDouble &dx) {
- // Taylor polynomial.
- constexpr DoubleDouble COEFFS[] = {
- {0, 0x1p0}, // 1
- {0, 0x1p0}, // 1
- {0, 0x1p-1}, // 1/2
- {0x1.5555555555555p-57, 0x1.5555555555555p-3}, // 1/6
- {0x1.5555555555555p-59, 0x1.5555555555555p-5}, // 1/24
- {0x1.1111111111111p-63, 0x1.1111111111111p-7}, // 1/120
- {-0x1.f49f49f49f49fp-65, 0x1.6c16c16c16c17p-10}, // 1/720
- };
-
- DoubleDouble p = fputil::polyeval(dx, COEFFS[0], COEFFS[1], COEFFS[2],
- COEFFS[3], COEFFS[4], COEFFS[5], COEFFS[6]);
- return p;
-}
-
-// Polynomial approximation with 128-bit precision:
-// Return exp(dx) ~ 1 + dx + dx^2 / 2 + ... + dx^7 / 5040
-// For |dx| < 2^-13 + 2^-30:
-// | output - exp(dx) | < 2^-126.
-LIBC_INLINE DFloat128 poly_approx_f128(const DFloat128 &dx) {
- constexpr DFloat128 COEFFS_128[]{
- {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0
- {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0
- {Sign::POS, -128, 0x80000000'00000000'00000000'00000000_u128}, // 0.5
- {Sign::POS, -130, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1/6
- {Sign::POS, -132, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1/24
- {Sign::POS, -134, 0x88888888'88888888'88888888'88888889_u128}, // 1/120
- {Sign::POS, -137, 0xb60b60b6'0b60b60b'60b60b60'b60b60b6_u128}, // 1/720
- {Sign::POS, -140, 0xd00d00d0'0d00d00d'00d00d00'd00d00d0_u128}, // 1/5040
- };
-
- DFloat128 p = fputil::polyeval(dx, COEFFS_128[0], COEFFS_128[1],
- COEFFS_128[2], COEFFS_128[3], COEFFS_128[4],
- COEFFS_128[5], COEFFS_128[6], COEFFS_128[7]);
- return p;
-}
-
-// Compute exp(x) using 128-bit precision.
-// TODO(lntue): investigate triple-double precision implementation for this
-// step.
-LIBC_INLINE DFloat128 exp_f128(double x, double kd, int idx1, int idx2) {
- // Recalculate dx:
-
- double t1 = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact
- double t2 = kd * MLOG_2_EXP2_M12_MID_30; // exact
- double t3 = kd * MLOG_2_EXP2_M12_LO; // Error < 2^-133
-
- DFloat128 dx = fputil::quick_add(
- DFloat128(t1), fputil::quick_add(DFloat128(t2), DFloat128(t3)));
-
- // TODO: Skip recalculating exp_mid1 and exp_mid2.
- DFloat128 exp_mid1 =
- fputil::quick_add(DFloat128(EXP2_MID1[idx1].hi),
- fputil::quick_add(DFloat128(EXP2_MID1[idx1].mid),
- DFloat128(EXP2_MID1[idx1].lo)));
-
- DFloat128 exp_mid2 =
- fputil::quick_add(DFloat128(EXP2_MID2[idx2].hi),
- fputil::quick_add(DFloat128(EXP2_MID2[idx2].mid),
- DFloat128(EXP2_MID2[idx2].lo)));
-
- DFloat128 exp_mid = fputil::quick_mul(exp_mid1, exp_mid2);
-
- DFloat128 p = poly_approx_f128(dx);
-
- DFloat128 r = fputil::quick_mul(exp_mid, p);
-
- r.exponent += static_cast<int>(kd) >> 12;
-
- return r;
-}
-
-// Compute exp(x) with double-double precision.
-LIBC_INLINE DoubleDouble exp_double_double(double x, double kd,
- const DoubleDouble &exp_mid) {
- // Recalculate dx:
- // dx = x - k * 2^-12 * log(2)
- double t1 = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact
- double t2 = kd * MLOG_2_EXP2_M12_MID_30; // exact
- double t3 = kd * MLOG_2_EXP2_M12_LO; // Error < 2^-130
-
- DoubleDouble dx = fputil::exact_add(t1, t2);
- dx.lo += t3;
-
- // Degree-6 Taylor polynomial approximation in double-double precision.
- // | p - exp(x) | < 2^-100.
- DoubleDouble p = poly_approx_dd(dx);
-
- // Error bounds: 2^-99.
- DoubleDouble r = fputil::quick_mult(exp_mid, p);
-
- return r;
-}
-#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-
-// Check for exceptional cases when
-// |x| <= 2^-53 or x < log(2^-1075) or x >= 0x1.6232bdd7abcd3p+9
-LIBC_INLINE double set_exceptional(double x) {
- using FPBits = typename fputil::FPBits<double>;
- FPBits xbits(x);
-
- uint64_t x_u = xbits.uintval();
- uint64_t x_abs = xbits.abs().uintval();
-
- // |x| <= 2^-53
- if (x_abs <= 0x3ca0'0000'0000'0000ULL) {
- // exp(x) ~ 1 + x
- return 1 + x;
- }
-
- // x <= log(2^-1075) || x >= 0x1.6232bdd7abcd3p+9 or inf/nan.
-
- // x <= log(2^-1075) or -inf/nan
- if (x_u >= 0xc087'4910'd52d'3052ULL) {
- // exp(-Inf) = 0
- if (xbits.is_inf())
- return 0.0;
-
- // exp(nan) = nan
- if (xbits.is_nan())
- return x;
-
-#ifndef LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
- if (fputil::quick_get_round() == FE_UPWARD)
- return FPBits::min_subnormal().get_val();
-#endif
- fputil::set_errno_if_required(ERANGE);
- fputil::raise_except_if_required(FE_UNDERFLOW);
- return 0.0;
- }
-
- // x >= round(log(MAX_NORMAL), D, RU) = 0x1.62e42fefa39fp+9 or +inf/nan
- // x is finite
- if (x_u < 0x7ff0'0000'0000'0000ULL) {
-#ifndef LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
- int rounding = fputil::quick_get_round();
- if (rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO)
- return FPBits::max_normal().get_val();
-#endif
-
- fputil::set_errno_if_required(ERANGE);
- fputil::raise_except_if_required(FE_OVERFLOW);
- }
- // x is +inf or nan
- return x + FPBits::inf().get_val();
-}
-
-} // namespace exp_internal
-
-LIBC_INLINE double exp(double x) {
- using namespace exp_internal;
- using FPBits = typename fputil::FPBits<double>;
- FPBits xbits(x);
-
- uint64_t x_u = xbits.uintval();
-
- // Upper bound: max normal number = 2^1023 * (2 - 2^-52)
- // > round(log (2^1023 ( 2 - 2^-52 )), D, RU) = 0x1.62e42fefa39fp+9
- // > round(log (2^1023 ( 2 - 2^-52 )), D, RD) = 0x1.62e42fefa39efp+9
- // > round(log (2^1023 ( 2 - 2^-52 )), D, RN) = 0x1.62e42fefa39efp+9
- // > round(exp(0x1.62e42fefa39fp+9), D, RN) = infty
-
- // Lower bound: min denormal number / 2 = 2^-1075
- // > round(log(2^-1075), D, RN) = -0x1.74910d52d3052p9
-
- // Another lower bound: min normal number = 2^-1022
- // > round(log(2^-1022), D, RN) = -0x1.6232bdd7abcd2p9
-
- // x < log(2^-1075) or x >= 0x1.6232bdd7abcd3p+9 or |x| < 2^-53.
- if (LIBC_UNLIKELY(x_u >= 0xc0874910d52d3052 ||
- (x_u < 0xbca0000000000000 && x_u >= 0x40862e42fefa39f0) ||
- x_u < 0x3ca0000000000000)) {
- return set_exceptional(x);
- }
-
- // Now log(2^-1075) <= x <= -2^-53 or 2^-53 <= x < log(2^1023 * (2 - 2^-52))
-
- // Range reduction:
- // Let x = log(2) * (hi + mid1 + mid2) + lo
- // in which:
- // hi is an integer
- // mid1 * 2^6 is an integer
- // mid2 * 2^12 is an integer
- // then:
- // exp(x) = 2^hi * 2^(mid1) * 2^(mid2) * exp(lo).
- // With this formula:
- // - multiplying by 2^hi is exact and cheap, simply by adding the exponent
- // field.
- // - 2^(mid1) and 2^(mid2) are stored in 2 x 64-element tables.
- // - exp(lo) ~ 1 + lo + a0 * lo^2 + ...
- //
- // They can be defined by:
- // hi + mid1 + mid2 = 2^(-12) * round(2^12 * log_2(e) * x)
- // If we store L2E = round(log2(e), D, RN), then:
- // log2(e) - L2E ~ 1.5 * 2^(-56)
- // So the errors when computing in double precision is:
- // | x * 2^12 * log_2(e) - D(x * 2^12 * L2E) | <=
- // <= | x * 2^12 * log_2(e) - x * 2^12 * L2E | +
- // + | x * 2^12 * L2E - D(x * 2^12 * L2E) |
- // <= 2^12 * ( |x| * 1.5 * 2^-56 + eps(x)) for RN
- // 2^12 * ( |x| * 1.5 * 2^-56 + 2*eps(x)) for other rounding modes.
- // So if:
- // hi + mid1 + mid2 = 2^(-12) * round(x * 2^12 * L2E) is computed entirely
- // in double precision, the reduced argument:
- // lo = x - log(2) * (hi + mid1 + mid2) is bounded by:
- // |lo| <= 2^-13 + (|x| * 1.5 * 2^-56 + 2*eps(x))
- // < 2^-13 + (1.5 * 2^9 * 1.5 * 2^-56 + 2*2^(9 - 52))
- // < 2^-13 + 2^-41
- //
-
- // The following trick computes the round(x * L2E) more efficiently
- // than using the rounding instructions, with the tradeoff for less accuracy,
- // and hence a slightly larger range for the reduced argument `lo`.
- //
- // To be precise, since |x| < |log(2^-1075)| < 1.5 * 2^9,
- // |x * 2^12 * L2E| < 1.5 * 2^9 * 1.5 < 2^23,
- // So we can fit the rounded result round(x * 2^12 * L2E) in int32_t.
- // Thus, the goal is to be able to use an additional addition and fixed width
- // shift to get an int32_t representing round(x * 2^12 * L2E).
- //
- // Assuming int32_t using 2-complement representation, since the mantissa part
- // of a double precision is unsigned with the leading bit hidden, if we add an
- // extra constant C = 2^e1 + 2^e2 with e1 > e2 >= 2^25 to the product, the
- // part that are < 2^e2 in resulted mantissa of (x*2^12*L2E + C) can be
- // considered as a proper 2-complement representations of x*2^12*L2E.
- //
- // One small problem with this approach is that the sum (x*2^12*L2E + C) in
- // double precision is rounded to the least significant bit of the dorminant
- // factor C. In order to minimize the rounding errors from this addition, we
- // want to minimize e1. Another constraint that we want is that after
- // shifting the mantissa so that the least significant bit of int32_t
- // corresponds to the unit bit of (x*2^12*L2E), the sign is correct without
- // any adjustment. So combining these 2 requirements, we can choose
- // C = 2^33 + 2^32, so that the sign bit corresponds to 2^31 bit, and hence
- // after right shifting the mantissa, the resulting int32_t has correct sign.
- // With this choice of C, the number of mantissa bits we need to shift to the
- // right is: 52 - 33 = 19.
- //
- // Moreover, since the integer right shifts are equivalent to rounding down,
- // we can add an extra 0.5 so that it will become round-to-nearest, tie-to-
- // +infinity. So in particular, we can compute:
- // hmm = x * 2^12 * L2E + C,
- // where C = 2^33 + 2^32 + 2^-1, then if
- // k = int32_t(lower 51 bits of double(x * 2^12 * L2E + C) >> 19),
- // the reduced argument:
- // lo = x - log(2) * 2^-12 * k is bounded by:
- // |lo| <= 2^-13 + 2^-41 + 2^-12*2^-19
- // = 2^-13 + 2^-31 + 2^-41.
- //
- // Finally, notice that k only uses the mantissa of x * 2^12 * L2E, so the
- // exponent 2^12 is not needed. So we can simply define
- // C = 2^(33 - 12) + 2^(32 - 12) + 2^(-13 - 12), and
- // k = int32_t(lower 51 bits of double(x * L2E + C) >> 19).
-
- // Rounding errors <= 2^-31 + 2^-41.
- double tmp = fputil::multiply_add(x, LOG2_E, 0x1.8000'0000'4p21);
- int k = static_cast<int>(cpp::bit_cast<uint64_t>(tmp) >> 19);
- double kd = static_cast<double>(k);
-
- uint32_t idx1 = (k >> 6) & 0x3f;
- uint32_t idx2 = k & 0x3f;
- int hi = k >> 12;
-
- bool denorm = (hi <= -1022);
-
- DoubleDouble exp_mid1{EXP2_MID1[idx1].mid, EXP2_MID1[idx1].hi};
- DoubleDouble exp_mid2{EXP2_MID2[idx2].mid, EXP2_MID2[idx2].hi};
-
- DoubleDouble exp_mid = fputil::quick_mult(exp_mid1, exp_mid2);
-
- // |x - (hi + mid1 + mid2) * log(2) - dx| < 2^11 * eps(M_LOG_2_EXP2_M12.lo)
- // = 2^11 * 2^-13 * 2^-52
- // = 2^-54.
- // |dx| < 2^-13 + 2^-30.
- double lo_h = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact
- double dx = fputil::multiply_add(kd, MLOG_2_EXP2_M12_MID, lo_h);
-
- // We use the degree-4 Taylor polynomial to approximate exp(lo):
- // exp(lo) ~ 1 + lo + lo^2 / 2 + lo^3 / 6 + lo^4 / 24 = 1 + lo * P(lo)
- // So that the errors are bounded by:
- // |P(lo) - expm1(lo)/lo| < |lo|^4 / 64 < 2^(-13 * 4) / 64 = 2^-58
- // Let P_ be an evaluation of P where all intermediate computations are in
- // double precision. Using either Horner's or Estrin's schemes, the evaluated
- // errors can be bounded by:
- // |P_(dx) - P(dx)| < 2^-51
- // => |dx * P_(dx) - expm1(lo) | < 1.5 * 2^-64
- // => 2^(mid1 + mid2) * |dx * P_(dx) - expm1(lo)| < 1.5 * 2^-63.
- // Since we approximate
- // 2^(mid1 + mid2) ~ exp_mid.hi + exp_mid.lo,
- // We use the expression:
- // (exp_mid.hi + exp_mid.lo) * (1 + dx * P_(dx)) ~
- // ~ exp_mid.hi + (exp_mid.hi * dx * P_(dx) + exp_mid.lo)
- // with errors bounded by 1.5 * 2^-63.
-
- double mid_lo = dx * exp_mid.hi;
-
- // Approximate expm1(dx)/dx ~ 1 + dx / 2 + dx^2 / 6 + dx^3 / 24.
- double p = poly_approx_d(dx);
-
- double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);
-
-#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
- if (LIBC_UNLIKELY(denorm)) {
- return ziv_test_denorm</*SKIP_ZIV_TEST=*/true>(hi, exp_mid.hi, lo,
- EXP_ERR_D)
- .value();
- } else {
- // to multiply by 2^hi, a fast way is to simply add hi to the exponent
- // field.
- int64_t exp_hi = static_cast<int64_t>(hi) * (1LL << FPBits::FRACTION_LEN);
- double r =
- cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(exp_mid.hi + lo));
- return r;
- }
-#else
- if (LIBC_UNLIKELY(denorm)) {
- if (auto r = ziv_test_denorm(hi, exp_mid.hi, lo, EXP_ERR_D);
- LIBC_LIKELY(r.has_value()))
- return r.value();
- } else {
- double upper = exp_mid.hi + (lo + EXP_ERR_D);
- double lower = exp_mid.hi + (lo - EXP_ERR_D);
-
- if (LIBC_LIKELY(upper == lower)) {
- // to multiply by 2^hi, a fast way is to simply add hi to the exponent
- // field.
- int64_t exp_hi = static_cast<int64_t>(hi) * (1LL << FPBits::FRACTION_LEN);
- double r = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper));
- return r;
- }
- }
-
- // Use double-double
- DoubleDouble r_dd = exp_double_double(x, kd, exp_mid);
-
- if (LIBC_UNLIKELY(denorm)) {
- if (auto r = ziv_test_denorm(hi, r_dd.hi, r_dd.lo, EXP_ERR_DD);
- LIBC_LIKELY(r.has_value()))
- return r.value();
- } else {
- double upper_dd = r_dd.hi + (r_dd.lo + EXP_ERR_DD);
- double lower_dd = r_dd.hi + (r_dd.lo - EXP_ERR_DD);
-
- if (LIBC_LIKELY(upper_dd == lower_dd)) {
- int64_t exp_hi = static_cast<int64_t>(hi) * (1LL << FPBits::FRACTION_LEN);
- double r =
- cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper_dd));
- return r;
- }
- }
-
- // Use 128-bit precision
- DFloat128 r_f128 = exp_f128(x, kd, idx1, idx2);
-
- return static_cast<double>(r_f128);
-#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-}
+using LIBC_MATH_EXP_IMPL::exp;
} // namespace math
-
} // namespace LIBC_NAMESPACE_DECL
+#undef LIBC_MATH_EXP_IMPL
+
#endif // LLVM_LIBC_SRC___SUPPORT_MATH_EXP_H
diff --git a/libc/src/__support/math/exp2_accurate_128.h b/libc/src/__support/math/exp2_accurate_128.h
index 07fc870a5f3e7f..1efbf487a29261 100644
--- a/libc/src/__support/math/exp2_accurate_128.h
+++ b/libc/src/__support/math/exp2_accurate_128.h
@@ -106,6 +106,25 @@ struct ExpBase192 {
UInt<192> log2_b; // lsb = 2^(base_exp - 191)
};
+// log2(e) in 192-bit fixed-point format (lsb = 2^-191), generated by Sollya
+// with:
+// > display = hexadecimal!;
+// > prec = 500;
+// > c = round(log2(exp(1)) * 2^191, 192, RN);
+// > d2 = floor(c * 2^(-128));
+// > c = c - d2 * 2^128;
+// > d1 = floor(c * 2^(-64));
+// > d0 = c - d1 * 2^64;
+// > print("{", d0, ",", d1, ",", d2, "}");
+LIBC_INLINE_VAR constexpr ExpBase192 LOG2_E_192 = {
+ 0,
+ UInt<192>({
+ 0xeb577aa8dd695a59ULL,
+ 0xbe87fed0691d3e88ULL,
+ 0xb8aa3b295c17f0bbULL,
+ }),
+};
+
// Evaluate 2^(idx * 2^-4 + u) in [1, 2) as Frac128 (lsb = 2^-127) for
// idx in [0, 15] and u in [0, 2^-4) (lsb = 2^-128).
LIBC_INLINE Frac128 exp2_eval_frac128(unsigned idx, const Frac128 &u) {
@@ -123,9 +142,9 @@ LIBC_INLINE Frac128 exp2_eval_frac128(unsigned idx, const Frac128 &u) {
return m + m * (u * p); // lsb = 2^-127
}
-// Compute 2^z in 128-bit precision for a DyadicFloat<128> z with
-// 2^-55 < |z| < 2^11 (z.exponent in [-181, -117]) and optional extra low limb
-// lo (lsb = 2^(z.exponent - 64)):
+// Compute 2^z in 128-bit precision for a DyadicFloat<128> z with leading bit at
+// bit 126 or 127 of z.mantissa, 2^-54 < |z| < 2^11 (z.exponent in
+// [-181, -117]), and optional extra low limb lo (lsb = 2^(z.exponent - 64)):
// z = k * 2^-4 + u, 0 <= u < 2^-4
// hi = k >> 4
// idx = k & 0x0f
@@ -135,13 +154,15 @@ LIBC_INLINE DFloat128 exp2_df128(const DFloat128 &z, uint64_t lo = 0) {
// (-4 - z.exponent) of z.mantissa, leaving
// shift = 128 - (-4 - z.exponent) = z.exponent + 132 bits
// at or above 2^-4 in z.mantissa.val[1].
- // After range reduction, 2^-55 < |z| < 2^11, so z.exponent is in
- // [-181, -117] and shift is in [-49, 15].
+ // After range reduction, 2^-54 < |z| < 2^11 and z.exponent is in
+ // [-181, -117], so shift is in [-49, 15].
int shift = z.exponent + 132;
int k = 0;
UInt<128> frac;
if (LIBC_LIKELY(shift > 0)) {
- // |z| >= 2^-4: split |z| = k * 2^-4 + frac * 2^-132.
+ // |z| >= 2^-5 (all |z| >= 2^-4, plus 2^-5 <= |z| < 2^-4 with k = 0 when
+ // bit 127 of z.mantissa is 0): split
+ // |z| = k * 2^-4 + frac * 2^-132.
// Here shift is in [1, 15] and shr = 64 - shift is in [49, 63], so all
// 64-bit shifts below are strictly in [1, 63] (no undefined behavior).
int shr = 64 - shift; // in [49, 63]
@@ -153,8 +174,7 @@ LIBC_INLINE DFloat128 exp2_df128(const DFloat128 &z, uint64_t lo = 0) {
(z.mantissa.val[0] >> shr)}); // lsb = 2^-132
} else {
// |z| < 2^-4: k = 0 and frac = |z| * 2^132, with -shift in [0, 49].
- frac = (-shift < 128) ? (z.mantissa >> (-shift))
- : UInt<128>(0); // lsb = 2^-132
+ frac = z.mantissa >> (-shift); // lsb = 2^-132
}
if (z.sign.is_neg()) {
@@ -162,20 +182,36 @@ LIBC_INLINE DFloat128 exp2_df128(const DFloat128 &z, uint64_t lo = 0) {
k = -k;
} else {
// One's-complement negation on frac (differs from two's-complement by
- // 2^-132, which is 1/16 ULP of u):
+ // 2^-132 = 2^-4 * lsb(u)):
// -|z| ~ (-k - 1) * 2^-4 + (2^-4 - (frac + 1) * 2^-132).
frac = ~frac;
k = ~k;
}
}
- // Decompose k * 2^-4 = hi + idx * 2^-4 and scale frac from lsb = 2^-132 to
- // u in [0, 2^-4) with lsb = 2^-128:
+ // Decompose:
+ // k * 2^-4 = hi + idx * 2^-4
+ // and scale frac from lsb = 2^-132 to u in [0, 2^-4) with lsb = 2^-128:
int hi = k >> 4; // lsb = 1
unsigned idx = static_cast<unsigned>(k & 0x0f); // lsb = 2^-4
Frac128 u((frac >> 4).val); // lsb = 2^-128
Frac128 m_final = exp2_eval_frac128(idx, u); // lsb = 2^-127
+ // For tiny negative inputs x = -a - a^2 / 2 (where 1 - a is an exact double),
+ // exp(x) = (1 - a) + a^3 / 3 + O(a^4)
+ // is strictly greater than 1 - a by a residual that can be smaller than
+ // 2^-128 (down to ~2^-155 for a = 2^-51).
+ //
+ // When z in (-2^-4, 0) (shift <= 0 and z < 0), the downward truncations of
+ // u, u * p, and m * (u * p) bias m_final by:
+ // (-5, 0) * lsb(m_final).
+ // Adding 5 shifts this error to:
+ // (0, 5) * lsb(m_final),
+ // so 2^-1 * m_final is strictly above 1 - a (preserving a non-zero sticky bit
+ // in all rounding modes).
+ if (shift <= 0 && z.sign.is_neg())
+ m_final += Frac128(5);
+
// Since m_final is in [1, 2) with lsb = 2^-127, its leading bit is already
// at bit 127, so r is normalized with exponent = hi - 127:
DFloat128 r;
@@ -186,8 +222,9 @@ LIBC_INLINE DFloat128 exp2_df128(const DFloat128 &z, uint64_t lo = 0) {
}
// Compute b^x (for b = 2, e, or 10) in 128-bit precision using direct base-2
-// 192-bit fixed-point range reduction. Here log2_base->log2_b holds
-// round(log2(b) * 2^(191 - base_exp)), or log2_base is nullptr when b = 2.
+// 192-bit fixed-point range reduction. Here log2_base->log2_b holds:
+// round(log2(b) * 2^(191 - base_exp)),
+// or log2_base is nullptr when b = 2.
LIBC_NOINLINE LIBC_INLINE double
exp_accurate_128(double x, const ExpBase192 *log2_base = nullptr) {
using FPBits = fputil::FPBits<double>;
diff --git a/libc/src/__support/math/exp2_double_eval.h b/libc/src/__support/math/exp2_double_eval.h
index 5263575680cb4d..c3cb23c57a19d3 100644
--- a/libc/src/__support/math/exp2_double_eval.h
+++ b/libc/src/__support/math/exp2_double_eval.h
@@ -96,14 +96,14 @@ LIBC_ALWAYS_INLINE double exp2(double x) {
// r_hi = m_hi + m_hi * u_hi
// r_lo = m * (u_lo + u^2 * P(u)) + m_lo * (1 + u_hi)
//
- // Since r_hi is in [0.997, 2.0), for r_hi to be exact in double precision,
+ // Since r_hi is in [1 - 2^-8, 2), for r_hi to be exact in double precision,
// we need:
// lsb(m_hi * u_hi) >= 2^-52.
// We choose:
- // lsb(m_hi) >= 2^-22 => |m_lo| <= 2^-23
+ // lsb(m_hi) >= 2^-22 => |m_lo| < 2^-22
// lsb(u_hi) >= 2^-30
// so that lsb(m_hi * u_hi) >= 2^-52, and the rounding errors from
- // m_lo * (1 + u_hi) are bounded by 2^(-23 - 52) = 2^-75.
+ // m_lo * (1 + u_hi) are bounded by 2^(-22 - 52) = 2^-74.
//
// To get lsb(u_hi) >= 2^-30 from u = dx * log(2), since |dx| <= 2^-8 and
// log(2) < 1, we split dx at 2^-18 and log(2) at 2^-12:
diff --git a/libc/src/__support/math/exp_double_eval.h b/libc/src/__support/math/exp_double_eval.h
new file mode 100644
index 00000000000000..15cdd4c318a804
--- /dev/null
+++ b/libc/src/__support/math/exp_double_eval.h
@@ -0,0 +1,153 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Double-precision implementation of exp.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_EXP_DOUBLE_EVAL_H
+#define LLVM_LIBC_SRC___SUPPORT_MATH_EXP_DOUBLE_EVAL_H
+
+#include "src/__support/FPUtil/FPBits.h"
+#include "src/__support/FPUtil/double_double.h"
+#include "src/__support/FPUtil/multiply_add.h"
+#include "src/__support/FPUtil/nearest_integer.h"
+#include "src/__support/common.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/optimization.h"
+#include "src/__support/macros/properties/cpu_features.h"
+
+#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
+#include "src/__support/math/exp_double_utils.h"
+#else
+#include "src/__support/math/exp_utils.h"
+#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
+
+namespace LIBC_NAMESPACE_DECL {
+namespace math {
+namespace double_eval {
+
+LIBC_ALWAYS_INLINE double exp(double x) {
+ using FPBits = typename fputil::FPBits<double>;
+ FPBits xbits(x);
+
+ uint64_t x_u = xbits.uintval();
+ uint64_t x_abs = xbits.abs().uintval();
+
+ // Bound constants (with biased exponent and mantissa bits):
+ // - Tiny bound: 2^-53 = 0x1.0p-53 (for |x| < 2^-53, exp(x) rounds to 1.0 + x)
+ constexpr uint64_t TINY_BOUND = 0x3ca0'0000'0000'0000ULL;
+ // - Overflow bound:
+ // > round(log(2^1023 * (2 - 2^-52)), D, RU) = 0x1.62e42fefa39f0p+9
+ // > round(log(2^1023 * (2 - 2^-52)), D, RD) = 0x1.62e42fefa39efp+9
+ // > round(log(2^1023 * (2 - 2^-52)), D, RN) = 0x1.62e42fefa39efp+9
+ // > round(exp(0x1.62e42fefa39f0p+9), D, RN) = +inf
+ constexpr uint64_t OVERFLOW_BOUND = 0x4086'2e42'fefa'39f0ULL;
+ // -0x1.62e42fefa39f0p+9:
+ constexpr uint64_t NEG_OVERFLOW_BOUND = 0xc086'2e42'fefa'39f0ULL;
+ // - Underflow bound: min denormal number / 2 = 2^-1075
+ // > round(log(2^-1075), D, RN) = -0x1.74910d52d3052p+9
+ constexpr uint64_t UNDERFLOW_BOUND = 0xc087'4910'd52d'3052ULL;
+
+ // Normal range: 2^-53 <= |x| < 0x1.62e42fefa39f0p+9.
+ if (LIBC_UNLIKELY(x_abs - TINY_BOUND >= OVERFLOW_BOUND - TINY_BOUND)) {
+ // Exclude non-underflowing negative inputs in
+ // (UNDERFLOW_BOUND, NEG_OVERFLOW_BOUND].
+ if (LIBC_LIKELY(x_u < NEG_OVERFLOW_BOUND || x_u >= UNDERFLOW_BOUND))
+ return set_exceptional(x);
+ }
+
+ // Now -0x1.74910d52d3052p+9 < x <= -0x1.0p-53 or
+ // 0x1.0p-53 <= x < 0x1.62e42fefa39f0p+9.
+
+ // Range reduction:
+ // Let x = k * (log(2) / 2^N) + u
+ // in which:
+ // k = round(x * 2^N * log2(e))
+ // hi = k >> N
+ // idx = k & (2^N - 1)
+ // then:
+ // exp(x) = 2^hi * 2^(idx / 2^N) * exp(u).
+ double x_scaled = x * (EXP_SCALE * LOG2_E.hi);
+ double kd = fputil::nearest_integer(x_scaled);
+ int k = static_cast<int>(kd);
+
+ int hi = k >> EXP_N_BITS;
+ unsigned idx = static_cast<unsigned>(k & EXP_MASK);
+
+#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
+ double t1 = fputil::multiply_add(kd, MLOG_2_EXP2_HI, x); // exact
+ double u = fputil::multiply_add(kd, MLOG_2_EXP2_MID, t1);
+ return exp2_eval(x, u, hi, idx);
+#else // !LIBC_MATH_HAS_SKIP_ACCURATE_PASS
+#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE
+ // With FMA, we use the full 53-bit:
+ // MLOG_2_HI_53 = -2^-7 * log(2) = -LOG_2.hi * EXP_SCALE_INV (lsb = 2^-60)
+ // to compute:
+ // u = x - k * 2^-7 * log(2) ~ t1 + d
+ // where:
+ // t1 = fma(kd, MLOG_2_HI_53, x)
+ // d = kd * MLOG_2_LO_53 (|d| < 2^18 * 2^-62 = 2^-44).
+ //
+ // For k != 0, |x| >= 2^-8 * log(2) > 2^-9 so lsb(x) >= 2^-61, and since kd is
+ // an integer, lsb(kd * MLOG_2_HI_53) >= 2^-60. Because |t1| < 2^-8, every
+ // non-zero bit of x + kd * MLOG_2_HI_53 lies in [2^-61, 2^-9] (at most 53
+ // bits), so:
+ // t1 = fma(kd, MLOG_2_HI_53, x)
+ // is exact.
+ //
+ // In exp2_eval, P(u.hi) is evaluated at u.hi = t1 alone. Writing:
+ // exp(t1 + d) = exp(t1) * exp(d)
+ // ~ (1 + t1 + t1^2 * P(t1)) * (1 + d)
+ // ~ 1 + t1 + d * (1 + t1) + t1^2 * P(t1),
+ // we fold the linear cross-term t1 * d into:
+ // u.lo = fma(t1, d, d),
+ // bounding the omitted term:
+ // |t1^2 * P(t1) * d| < 2^-63.
+ constexpr double MLOG_2_HI_53 = -LOG_2.hi * EXP_SCALE_INV;
+ constexpr double MLOG_2_LO_53 = -LOG_2.lo * EXP_SCALE_INV;
+
+ double t1 = fputil::multiply_add(kd, MLOG_2_HI_53, x); // exact
+ double d = kd * MLOG_2_LO_53;
+ double u_lo = fputil::multiply_add(t1, d, d);
+ DoubleDouble u = {u_lo, t1};
+#else // !LIBC_TARGET_CPU_HAS_FMA_DOUBLE
+ // Without FMA, we use a 35-bit-precision high part MLOG_2_EXP2_HI (with lsb =
+ // 2^-42) so that:
+ // kd * MLOG_2_EXP2_HI
+ // has at most 18 + 35 = 53 significant bits and is exact in double precision
+ // for |kd| < 2^18, and:
+ // t1 = x + kd * MLOG_2_EXP2_HI
+ // is exact by Sterbenz's lemma.
+ //
+ // We then split t1 at 2^-30 before adding t2 = kd * MLOG_2_EXP2_MID:
+ // u_hi = (t1 + SPLIT_30) - SPLIT_30 (exact, lsb = 2^-30)
+ // t1_lo = t1 - u_hi (exact, |t1_lo| <= 2^-31)
+ // u_lo = t1_lo + t2 (|u_lo| < 2^-26).
+ // This gives lsb(u_hi) >= 2^-30 so that m_hi * u_hi is exact in exp2_eval,
+ // while keeping |u_lo| < 2^-26 so the rounding error of:
+ // u_lo = t1_lo + t2
+ // is bounded by 2^(-26 - 53) = 2^-79.
+ double t1 = fputil::multiply_add(kd, MLOG_2_EXP2_HI, x); // exact
+ double t2 = kd * MLOG_2_EXP2_MID;
+ double u_hi = (t1 + SPLIT_30) - SPLIT_30; // exact, lsb = 2^-30
+ double t1_lo = t1 - u_hi; // exact
+ double u_lo = t1_lo + t2;
+ DoubleDouble u = {u_lo, u_hi};
+#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE
+ return exp2_eval(x, u, hi, idx, EXP_ERR_D, &LOG2_E_192);
+#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
+}
+
+} // namespace double_eval
+} // namespace math
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC___SUPPORT_MATH_EXP_DOUBLE_EVAL_H
diff --git a/libc/src/__support/math/exp_double_utils.h b/libc/src/__support/math/exp_double_utils.h
index bc425b5130737a..dcb4128796df94 100644
--- a/libc/src/__support/math/exp_double_utils.h
+++ b/libc/src/__support/math/exp_double_utils.h
@@ -16,9 +16,9 @@
#define LLVM_LIBC_SRC___SUPPORT_MATH_EXP_DOUBLE_UTILS_H
#include "hdr/errno_macros.h"
-#include "src/__support/CPP/bit.h"
#include "src/__support/FPUtil/FEnvImpl.h"
#include "src/__support/FPUtil/FPBits.h"
+#include "src/__support/FPUtil/fp_bitwise.h"
#include "src/__support/FPUtil/multiply_add.h"
#include "src/__support/common.h"
#include "src/__support/macros/attributes.h"
@@ -48,7 +48,7 @@ LIBC_INLINE_VAR constexpr int EXP_MASK = 0x07;
// [-2^(-4) * log(2), 2^(-4) * log(2)]);
// > dirtyinfnorm(exp(x) - (1 + x + x^2 * P),
// [-2^(-4) * log(2), 2^(-4) * log(2)]);
-// 0x1.6828...p-57 < 1.5 * 2^-57.
+// 0x1.6828...p-57 < 2^-56.
LIBC_INLINE_VAR constexpr double EXP_P_COEFFS[6] = {
0x1.000000000002ep-1, // p_0
0x1.555555555549cp-3, // p_1
@@ -78,6 +78,13 @@ LIBC_INLINE_VAR constexpr double EXP2_MID[8] = {
0x1.ae89f995ad3adp0, 0x1.d5818dcfba487p0,
};
+// Splitting -2^-3 * log(2) ~ hi + lo with 38-bit-precision hi part so that
+// kd * MLOG_2_EXP2_HI is exact for |kd| < 2^14:
+// > hi = round(-2^-3 * log(2), 38, RN);
+// > lo = round(-2^-3 * log(2) - hi, D, RN);
+LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_HI = -0x1.62e42fefap-4;
+LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_MID = -0x1.cf79abc9e3b3ap-43;
+
#else // !LIBC_MATH_HAS_SMALL_TABLES
// Lookup table for 2^(k * 2^-7) with k = 0..127.
diff --git a/libc/src/__support/math/exp_utils.h b/libc/src/__support/math/exp_utils.h
index a7c96ba6806616..2958c00355ac54 100644
--- a/libc/src/__support/math/exp_utils.h
+++ b/libc/src/__support/math/exp_utils.h
@@ -21,21 +21,15 @@
#include "src/__support/FPUtil/FEnvImpl.h"
#include "src/__support/FPUtil/FPBits.h"
#include "src/__support/FPUtil/double_double.h"
+#include "src/__support/FPUtil/fp_bitwise.h"
#include "src/__support/FPUtil/multiply_add.h"
#include "src/__support/FPUtil/rounding_mode.h"
#include "src/__support/common.h"
#include "src/__support/macros/attributes.h"
#include "src/__support/macros/config.h"
#include "src/__support/macros/optimization.h"
-#include "src/__support/macros/properties/architectures.h"
#include "src/__support/macros/properties/cpu_features.h"
-#ifdef LIBC_TARGET_CPU_HAS_SSE2
-#include <immintrin.h>
-#elif defined(LIBC_TARGET_ARCH_IS_AARCH64) && defined(__ARM_NEON)
-#include <arm_neon.h>
-#endif // LIBC_TARGET_CPU_HAS_SSE2
-
#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
#include "src/__support/math/exp2_accurate_128.h"
#endif // !LIBC_MATH_HAS_SKIP_ACCURATE_PASS
@@ -51,35 +45,29 @@ namespace LIBC_NAMESPACE_DECL {
template <bool SKIP_ZIV_TEST = false>
LIBC_INLINE constexpr cpp::optional<double>
ziv_test_denorm(int hi, double mid, double lo, double err) {
- using FPBits = typename fputil::FPBits<double>;
-
// Scaling factor = 1/(min normal number) = 2^1022
- int64_t exp_hi =
- static_cast<int64_t>(hi + 1022) * (1LL << FPBits::FRACTION_LEN);
- double mid_hi = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(mid));
- double lo_scaled =
- (lo != 0.0) ? cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(lo))
- : 0.0;
+ int scale_up = hi + 1022;
+ double mid_hi = fputil::scale_exp2(mid, scale_up);
+ double lo_scaled = (lo != 0.0) ? fputil::scale_exp2(lo, scale_up) : 0.0;
double extra_factor = 0.0;
- uint64_t scale_down = 0x3FE0'0000'0000'0000; // 1022 in the exponent field.
+ int scale_down = -1022;
// Result is denormal if (mid_hi + lo_scale < 1.0).
if ((1.0 - mid_hi) > lo_scaled) {
// Extra rounding step is needed, which adds more rounding errors.
err += 0x1.0p-52;
extra_factor = 1.0;
- scale_down = 0x3FF0'0000'0000'0000; // 1023 in the exponent field.
+ scale_down = -1023;
}
// By adding 1.0, the results will have similar rounding points as denormal
// outputs.
if constexpr (SKIP_ZIV_TEST) {
double r = extra_factor + (mid_hi + lo_scaled);
- return cpp::bit_cast<double>(cpp::bit_cast<uint64_t>(r) - scale_down);
+ return fputil::scale_exp2(r, scale_down);
} else {
- double err_scaled =
- cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(err));
+ double err_scaled = fputil::scale_exp2(err, scale_up);
double lo_u = lo_scaled + err_scaled;
double lo_l = lo_scaled - err_scaled;
@@ -87,9 +75,8 @@ ziv_test_denorm(int hi, double mid, double lo, double err) {
double upper = extra_factor + (mid_hi + lo_u);
double lower = extra_factor + (mid_hi + lo_l);
- if (LIBC_LIKELY(upper == lower)) {
- return cpp::bit_cast<double>(cpp::bit_cast<uint64_t>(upper) - scale_down);
- }
+ if (LIBC_LIKELY(upper == lower))
+ return fputil::scale_exp2(upper, scale_down);
return cpp::nullopt;
}
@@ -99,6 +86,7 @@ namespace math {
namespace double_eval {
using fputil::DoubleDouble;
+using fputil::scale_exp2;
// log(2) in double-double precision, generated by Sollya with:
// > display = hexadecimal!;
@@ -109,43 +97,14 @@ using fputil::DoubleDouble;
LIBC_INLINE_VAR constexpr DoubleDouble LOG_2 = {0x1.abc9e3b39803fp-56,
0x1.62e42fefa39efp-1};
-// Directly add an integer `hi` to the exponent field of a double precision `r`.
-// It is equivalent to scaling `r` by 2^hi when both `r` and the resulting bits
-// are normal.
-// The default implementation is simply bit cast `r` to int64`, shift `hi` to
-// the exponent field, then add `r` bits and shifted `hi`, before bit cast the
-// result back to double.
-// The addition is done in integer, and most likely generated as addition in the
-// general purpose registers (GPR), causing a full round trip from
-// floating-point/SIMD register -> GPR -> FP/SIMD.
-// When SSE2 or NEON are available, we can use the compiler intrinsic to keep
-// `r` in the FP/SIMD register, and perform the integer addition in the FP/SIMD
-// registers instead. This in general results in a reduction in latency since
-// `r` is normally on the critical path.
-LIBC_ALWAYS_INLINE double scale_exp2(double r, int hi) {
- using FPBits = typename fputil::FPBits<double>;
-#ifdef LIBC_TARGET_CPU_HAS_SSE2
- // Move `hi` to SIMD register and shift to exponent field position.
- __m128i v_exp = _mm_slli_epi64(_mm_cvtsi32_si128(hi), FPBits::FRACTION_LEN);
- // Load `r` and "bit_cast" it to integer SIMD type.
- __m128i v_r = _mm_castpd_si128(_mm_set_sd(r));
- // Perform integer addition in SIMD registers and bit cast the result back to
- // double.
- return _mm_cvtsd_f64(_mm_castsi128_pd(_mm_add_epi64(v_exp, v_r)));
-#elif defined(LIBC_TARGET_ARCH_IS_AARCH64) && defined(__ARM_NEON)
- // Shift `hi` to exponent field position and move it to SIMD register.
- int64x1_t v_exp =
- vdup_n_s64(static_cast<int64_t>(hi) << FPBits::FRACTION_LEN);
- // Bit cast `r` to integer SIMD type.
- int64x1_t v_r = vreinterpret_s64_f64(vdup_n_f64(r));
- // Perform integer addition in SIMD registers and bit cast the result back to
- // double.
- return vget_lane_f64(vreinterpret_f64_s64(vadd_s64(v_exp, v_r)), 0);
-#else
- int64_t exp_hi = static_cast<int64_t>(hi) * (1LL << FPBits::FRACTION_LEN);
- return cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(r));
-#endif // LIBC_TARGET_CPU_HAS_SSE2
-}
+// log2(e) in double-double precision, generated by Sollya with:
+// > display = hexadecimal!;
+// > prec = 500;
+// > hi = round(log2(exp(1)), D, RN);
+// > lo = round(log2(exp(1)) - hi, D, RN);
+// > print("{", lo, ",", hi, "};");
+LIBC_INLINE_VAR constexpr DoubleDouble LOG2_E = {0x1.777d0ffda0d24p-56,
+ 0x1.71547652b82fep+0};
// Check for exceptional cases (tiny, overflow, underflow, inf, or nan) for
// exp, exp2, and exp10. Callers have already verified that x is in the exact
@@ -221,7 +180,7 @@ LIBC_INLINE_VAR constexpr int EXP_MASK = 0x7f;
// > B = 2^(-8) * log(2);
// > P0 = fpminimax((exp(x) - 1 - x)/x^2, 3, [|D...|], [-B, B]);
// > dirtyinfnorm(exp(x) - (1 + x + x^2 * P0), [-B, B]);
-// 0x1.4362...p-64 < 2^-63.66.
+// 0x1.4362...p-64 < 2^-63.
//
// Some explanation for the errors (from Chebyshev polynomials):
// Because P0 minimizes |(exp(x) - 1 - x) / x^2 - P0(x)|, its error is governed
@@ -232,23 +191,25 @@ LIBC_INLINE_VAR constexpr int EXP_MASK = 0x7f;
// Multiplying by x^2 gives an absolute error of:
// x^2 * B^4 / (720 * 8) * T_4(x / B),
// peaking at x = +-B with:
-// B^6 / (720 * 8) ~ 0x1.4309...p-64 < 2^-63.66.
+// B^6 / (720 * 8) ~ 0x1.4309...p-64 < 2^-63.
//
// 2) If we instead minimize the absolute error of exp(x) - (1 + x + P(x))
// directly on [-B, B] with monomials [|2, 3, 4, 5|]:
// > P = fpminimax(exp(x) - 1 - x, [|2, 3, 4, 5|], [|D...|], [-B, B],
// absolute);
// > dirtyinfnorm(exp(x) - (1 + x + P), [-B, B]);
-// 0x1.8e05...p-66 < 2^-65.36.
+// 0x1.8e05...p-66 < 2^-65.
//
// Some explanation for the better errors from Chebyshev polynomials:
// The free x^2 and x^4 coefficients in P(x) approximate the omitted x^6 / 720
// term on [-B, B] subject to vanishing at x = 0. Setting t = (x / B)^2 in
-// [0, 1], this is equivalent to approximating t^3 on [0, 1] by
-// a_2 * t^2 + a_1 * t vanishing at t = 0.
-// The degree-3 Chebyshev polynomial T_3(z) = 4*z^3 - 3*z has a root at
-// z = -sqrt(3)/2 and three alternating extrema +-1 on [-sqrt(3)/2, 1] at
-// z = -1/2, 1/2, 1.
+// [0, 1], this is equivalent to approximating t^3 on [0, 1] by:
+// a_2 * t^2 + a_1 * t
+// vanishing at t = 0.
+// The degree-3 Chebyshev polynomial:
+// T_3(z) = 4*z^3 - 3*z
+// has a root at z = -sqrt(3)/2 and three alternating extrema +-1 on
+// [-sqrt(3)/2, 1] at z = -1/2, 1/2, 1.
// Mapping t in [0, 1] affinely onto z in [-sqrt(3)/2, 1] via:
// z = ((2 + sqrt(3)) / 2) * t - sqrt(3) / 2
// gives an error curve T_3(z) that vanishes at t = 0 and equioscillates three
@@ -256,8 +217,9 @@ LIBC_INLINE_VAR constexpr int EXP_MASK = 0x7f;
// 4 * ((2 + sqrt(3)) / 2)^3 = (2 + sqrt(3))^3 / 2.
// Dividing by this leading coefficient gives a maximum error on [-B, B] of:
// (2 / (2 + sqrt(3))^3) * B^6 / 720 = 2 * (2 - sqrt(3))^3 * B^6 / 720
-// ~ 0x1.8dba...p-66 < 2^-65.36,
-// reducing the maximum error compared to P0 by (2 + sqrt(3))^3 / 16 ~ 3.25x.
+// ~ 0x1.8dba...p-66 < 2^-65,
+// reducing the maximum error compared to P0 by:
+// (2 + sqrt(3))^3 / 16 > 3x.
LIBC_INLINE_VAR constexpr double EXP_P_COEFFS[4] = {
0x1.ffffffffffdbdp-2, // p_0
0x1.555555555543dp-3, // p_1
@@ -272,15 +234,22 @@ LIBC_ALWAYS_INLINE double exp_poly(double u, double u2) {
return fputil::multiply_add(u2, c1, c0);
}
+// Splitting -2^-7 * log(2) ~ hi + lo with 35-bit-precision hi part so that
+// kd * MLOG_2_EXP2_HI is exact for |kd| < 2^18:
+// > hi = round(-2^-7 * log(2), 35, RN);
+// > lo = round(-2^-7 * log(2) - hi, D, RN);
+LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_HI = -0x1.62e42fefcp-8;
+LIBC_INLINE_VAR constexpr double MLOG_2_EXP2_MID = 0x1.c610ca86c3899p-44;
+
#endif // !LIBC_MATH_HAS_SKIP_ACCURATE_PASS || !LIBC_MATH_HAS_SMALL_TABLES
#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-// Fixed-point splitting constants (ulp = 2^-22, 2^-18) and pre-split
+// Fixed-point splitting constants (ulp = 2^-18, 2^-30) and pre-split
// 12-bit + 53-bit logarithm constants for exact non-FMA multiplication without
// Veltkamp splitting:
-LIBC_INLINE_VAR constexpr double SPLIT_22 = 0x1.8p30; // 1.5 * 2^(-22 + 52)
LIBC_INLINE_VAR constexpr double SPLIT_18 = 0x1.8p34; // 1.5 * 2^(-18 + 52)
+LIBC_INLINE_VAR constexpr double SPLIT_30 = 0x1.8p22; // 1.5 * 2^(-30 + 52)
// Splitting log(2) ~ hi + lo with 12-bit-precision hi part.
// > hi = round(log(2), 12, RN);
@@ -288,8 +257,9 @@ LIBC_INLINE_VAR constexpr double SPLIT_18 = 0x1.8p34; // 1.5 * 2^(-18 + 52)
LIBC_INLINE_VAR constexpr double LOG_2_HI_12 = 0x1.62ep-1;
LIBC_INLINE_VAR constexpr double LOG_2_LO_12 = 0x1.0bfbe8e7bcd5ep-15;
-// Error bound for double precision fast path (N = 7, Ziv failure rate <
+// Error bounds for double precision fast path (N = 7, Ziv failure rate <
// 0.05%):
+LIBC_INLINE_VAR constexpr double EXP_ERR_D = 0x1.4p-62;
LIBC_INLINE_VAR constexpr double EXP2_ERR_D = 0x1.0p-64;
// Lookup table for 2^(i * 2^-7) with i = 0..127.
@@ -431,6 +401,21 @@ LIBC_INLINE_VAR constexpr DoubleDouble EXP2_MID[128] = {
{0x1.2eb74966579e7p-57, 0x1.fd3c22b8f71f1p0},
};
+// Cold path for scaling and rounding:
+// 2^hi * (r_hi + r_lo) ~ b^x
+// when the result may be subnormal (hi <= -1022). Falls back to 128-bit
+// evaluation exp_accurate_128(x, log2_base) if Ziv's denormal rounding test
+// fails.
+//
+// Input expectations:
+// - x: original input in the non-overflowing/non-underflowing range of b^x.
+// - hi: integer exponent k >> 7 in [-1075, -1022].
+// - r_hi, lo_u: high part and upper-bounded low part (r_lo + err_d) of the
+// unscaled mantissa:
+// 2^(idx / 2^7) * exp(u) in [1 - 2^-8, 2),
+// with |lo_u - err_d| << r_hi.
+// - err_d: Ziv error bound on r_hi + r_lo.
+// - log2_base: pointer to 192-bit log2(b) table (or nullptr when b = 2).
LIBC_NOINLINE LIBC_INLINE double
exp_denorm(double x, int hi, double r_hi, double lo_u, double err_d,
const ExpBase192 *log2_base = nullptr) {
@@ -452,6 +437,23 @@ exp_denorm(double x, int hi, double r_hi, double lo_u, double err_d,
return exp_accurate_128(x, log2_base);
}
+// Evaluate:
+// b^x = 2^hi * 2^(idx / 2^7) * exp(u)
+// in double-double precision and apply Ziv's rounding test, falling back to
+// exp_denorm (when hi <= -1022) or exp_accurate_128 (when Ziv's test fails).
+//
+// Input expectations:
+// - x: original input after filtering out tiny, overflow, underflow, and
+// Inf/NaN cases.
+// - u: reduced argument:
+// u.hi + u.lo ~ x * log(b) - k * 2^-7 * log(2)
+// with |u.hi + u.lo| <= 2^-8 * log(2). On targets without FMA,
+// lsb(u.hi) >= 2^-30 and |u.lo| < 2^-18
+// so that m_hi * u.hi is exact in double.
+// - hi: integer exponent k >> 7 in [-1075, 1023].
+// - idx: table index k & 0x7f in [0, 127].
+// - err_d: Ziv error bound on the double-double approximation r_hi + r_lo.
+// - log2_base: pointer to 192-bit log2(b) table (or nullptr when b = 2).
LIBC_ALWAYS_INLINE double exp2_eval(double x, DoubleDouble u, int hi,
unsigned idx, double err_d = EXP2_ERR_D,
const ExpBase192 *log2_base = nullptr) {
@@ -466,8 +468,9 @@ LIBC_ALWAYS_INLINE double exp2_eval(double x, DoubleDouble u, int hi,
// r_hi + r_lo = exp2_mid.hi * (1 + u.hi)
// tail = exp2_mid.hi * (u.lo + u^2 * P(u))
// + exp2_mid.lo * (1 + u.hi)
- // where the omitted cross term exp2_mid.lo * (u.lo + u^2 * P(u)) is bounded
- // by 2^(-54 - 18) = 2^-72 and absorbed into err_d.
+ // where the omitted term:
+ // exp2_mid.lo * (u.lo + u^2 * P(u))
+ // is bounded by 2^(-54 - 18) = 2^-72 and absorbed into err_d.
// p ~ (exp(u) - 1 - u) / u^2
double u2 = u.hi * u.hi;
@@ -502,12 +505,15 @@ LIBC_ALWAYS_INLINE double exp2_eval(double x, DoubleDouble u, int hi,
double u2 = u_sum * u_sum;
double p = exp_poly(u_sum, u2);
- // Split exp2_mid = m_hi + m_lo with lsb(m_hi) >= 2^-22 and |m_lo| <= 2^-23:
- double m_hi = (exp2_mid.hi + SPLIT_22) - SPLIT_22; // lsb = 2^-22
+ // Split exp2_mid = m_hi + m_lo with lsb(m_hi) >= 2^-22 and |m_lo| < 2^-22:
+ LIBC_BIT_CAST_CONSTEXPR_VAR double HI_MASK_22 =
+ cpp::bit_cast<double>(0xffff'ffff'c000'0000ULL);
+ double m_hi = fputil::fp_and(exp2_mid.hi, HI_MASK_22); // lsb = 2^-22
double m_lo = (exp2_mid.hi - m_hi) + exp2_mid.lo;
- // Since lsb(u.hi) >= 2^-30 and r_hi is in [0.997, 2.0), both m_hi * u.hi and
- // r_hi = m_hi * (1 + u.hi) are exact:
+ // Since lsb(u.hi) >= 2^-30 and r_hi is in [1 - 2^-8, 2), both:
+ // m_hi * u.hi and r_hi = m_hi * (1 + u.hi)
+ // are exact:
double prod_hi = m_hi * u.hi; // exact, lsb = 2^-52
double r_hi = m_hi + prod_hi; // exact
diff --git a/libc/test/src/__support/FPUtil/fp_bitwise_test.cpp b/libc/test/src/__support/FPUtil/fp_bitwise_test.cpp
index db46f804725e8b..0a9874020f2796 100644
--- a/libc/test/src/__support/FPUtil/fp_bitwise_test.cpp
+++ b/libc/test/src/__support/FPUtil/fp_bitwise_test.cpp
@@ -25,6 +25,7 @@ using LIBC_NAMESPACE::fputil::fp_not;
using LIBC_NAMESPACE::fputil::fp_or;
using LIBC_NAMESPACE::fputil::fp_xor;
using LIBC_NAMESPACE::fputil::FPBits;
+using LIBC_NAMESPACE::fputil::scale_exp2;
template <typename T>
class LlvmLibcFPBitwiseTest : public LIBC_NAMESPACE::testing::Test {
@@ -92,6 +93,15 @@ class LlvmLibcFPBitwiseTest : public LIBC_NAMESPACE::testing::Test {
EXPECT_EQ(bits_of(fp_andnot(pos_val, other_val)),
bits_of(fp_and(pos_val, fp_not(other_val))));
}
+
+ void test_scale_exp2() {
+ EXPECT_EQ(bits_of(scale_exp2(pos_val, 0)), bits_of(pos_val));
+ EXPECT_EQ(bits_of(scale_exp2(neg_val, 0)), bits_of(neg_val));
+ EXPECT_EQ(bits_of(scale_exp2(pos_val, 2)), bits_of(T(6.0)));
+ EXPECT_EQ(bits_of(scale_exp2(neg_val, 2)), bits_of(T(-6.0)));
+ EXPECT_EQ(bits_of(scale_exp2(pos_val, -2)), bits_of(T(0.375)));
+ EXPECT_EQ(bits_of(scale_exp2(neg_val, -2)), bits_of(T(-0.375)));
+ }
};
using FPBitwiseTypes = LIBC_NAMESPACE::testing::TypeList<float, double,
@@ -110,6 +120,9 @@ TYPED_TEST_F(LlvmLibcFPBitwiseTest, AndNot, FPBitwiseTypes) {
this->test_andnot();
}
TYPED_TEST_F(LlvmLibcFPBitwiseTest, Not, FPBitwiseTypes) { this->test_not(); }
+TYPED_TEST_F(LlvmLibcFPBitwiseTest, ScaleExp2, FPBitwiseTypes) {
+ this->test_scale_exp2();
+}
TEST(LlvmLibcFPBitwiseConstexprTest, ConstexprEval) {
static_assert(FPBits<double>(fp_xor(-1.5, 1.5)).uintval() ==
@@ -122,9 +135,17 @@ TEST(LlvmLibcFPBitwiseConstexprTest, ConstexprEval) {
FPBits<double>::SIGN_MASK);
static_assert(FPBits<double>(fp_not(fp_not(1.5))).uintval() ==
FPBits<double>(1.5).uintval());
+ static_assert(FPBits<double>(scale_exp2(1.5, 2)).uintval() ==
+ FPBits<double>(6.0).uintval());
+ static_assert(FPBits<double>(scale_exp2(1.5, -2)).uintval() ==
+ FPBits<double>(0.375).uintval());
static_assert(FPBits<float>(fp_xor(-1.5f, 1.5f)).uintval() ==
FPBits<float>::SIGN_MASK);
static_assert(FPBits<float>(fp_andnot(-1.5f, -0.0f)).uintval() ==
FPBits<float>(1.5f).uintval());
+ static_assert(FPBits<float>(scale_exp2(1.5f, 2)).uintval() ==
+ FPBits<float>(6.0f).uintval());
+ static_assert(FPBits<float>(scale_exp2(1.5f, -2)).uintval() ==
+ FPBits<float>(0.375f).uintval());
}
diff --git a/libc/test/src/math/CMakeLists.txt b/libc/test/src/math/CMakeLists.txt
index 067ef651b76c28..d88afe6370e27b 100644
--- a/libc/test/src/math/CMakeLists.txt
+++ b/libc/test/src/math/CMakeLists.txt
@@ -1328,8 +1328,12 @@ add_fp_unittest(
SRCS
exp_test.cpp
DEPENDS
+ libc.hdr.fenv_macros
libc.src.math.exp
+ libc.src.__support.math.exp_double_eval
libc.src.__support.FPUtil.fp_bits
+ libc.src.__support.macros.attributes
+ libc.src.__support.macros.optimization
)
add_fp_unittest(
diff --git a/libc/test/src/math/exp_test.cpp b/libc/test/src/math/exp_test.cpp
index fb4646f790e989..dd764aa5b27dc0 100644
--- a/libc/test/src/math/exp_test.cpp
+++ b/libc/test/src/math/exp_test.cpp
@@ -1,127 +1,191 @@
-//===-- Unittests for exp -------------------------------------------------===//
+//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file contains unittests for exp.
+///
+//===----------------------------------------------------------------------===//
+#include "hdr/fenv_macros.h"
#include "hdr/math_macros.h"
#include "hdr/stdint_proxy.h"
#include "src/__support/FPUtil/FPBits.h"
+#include "src/__support/macros/attributes.h"
#include "src/__support/macros/optimization.h"
+#include "src/__support/math/exp_double_eval.h"
#include "src/math/exp.h"
#include "test/UnitTest/FPMatcher.h"
#include "test/UnitTest/Test.h"
#include "utils/MPFRWrapper/MPFRUtils.h"
#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
+#if defined(LIBC_MATH_HAS_SMALL_TABLES) && \
+ !defined(LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY)
+#define TOLERANCE 2
+#else // LIBC_MATH_HAS_SMALL_TABLE && LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
#define TOLERANCE 1
-#else
+#endif // LIBC_MATH_HAS_SMALL_TABLES && !LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
+#else // !LIBC_MATH_HAS_SKIP_ACCURATE_PASS
#define TOLERANCE 0
#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-using LlvmLibcExpTest = LIBC_NAMESPACE::testing::FPTest<double>;
+#ifdef LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
+#define ALL_ROUNDING false
+#else
+#define ALL_ROUNDING true
+#endif // LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
namespace mpfr = LIBC_NAMESPACE::testing::mpfr;
using LIBC_NAMESPACE::testing::tlog;
-TEST_F(LlvmLibcExpTest, SpecialNumbers) {
- EXPECT_FP_EQ(aNaN, LIBC_NAMESPACE::exp(aNaN));
- EXPECT_FP_EQ(inf, LIBC_NAMESPACE::exp(inf));
- EXPECT_FP_EQ_ALL_ROUNDING(zero, LIBC_NAMESPACE::exp(neg_inf));
- EXPECT_FP_EQ_WITH_EXCEPTION(zero, LIBC_NAMESPACE::exp(-0x1.0p20),
- FE_UNDERFLOW);
- EXPECT_FP_EQ_WITH_EXCEPTION(inf, LIBC_NAMESPACE::exp(0x1.0p20), FE_OVERFLOW);
- EXPECT_FP_EQ_ALL_ROUNDING(1.0, LIBC_NAMESPACE::exp(0.0));
- EXPECT_FP_EQ_ALL_ROUNDING(1.0, LIBC_NAMESPACE::exp(-0.0));
+LIBC_NOINLINE double exp_double_eval(double x) {
+ return LIBC_NAMESPACE::math::double_eval::exp(x);
}
-TEST_F(LlvmLibcExpTest, TrickyInputs) {
- constexpr int N = 14;
- constexpr uint64_t INPUTS[N] = {
- 0x3FD79289C6E6A5C0,
- 0x3FD05DE80A173EA0, // 0x1.05de80a173eap-2
- 0xbf1eb7a4cb841fcc, // -0x1.eb7a4cb841fccp-14
- 0xbf19a61fb925970d,
- 0x3fda7b764e2cf47a, // 0x1.a7b764e2cf47ap-2
- 0xc04757852a4b93aa, // -0x1.757852a4b93aap+5
- 0x4044c19e5712e377, // x=0x1.4c19e5712e377p+5
- 0xbf19a61fb925970d, // x=-0x1.9a61fb925970dp-14
- 0xc039a74cdab36c28, // x=-0x1.9a74cdab36c28p+4
- 0xc085b3e4e2e3bba9, // x=-0x1.5b3e4e2e3bba9p+9
- 0xc086960d591aec34, // x=-0x1.6960d591aec34p+9
- 0xc086232c09d58d91, // x=-0x1.6232c09d58d91p+9
- 0xc0874910d52d3051, // x=-0x1.74910d52d3051p9
- 0xc0867a172ceb0990, // x=-0x1.67a172ceb099p+9
- };
- for (int i = 0; i < N; ++i) {
- double x = FPBits(INPUTS[i]).get_val();
- EXPECT_MPFR_MATCH_ALL_ROUNDING(mpfr::Operation::Exp, x,
- LIBC_NAMESPACE::exp(x), TOLERANCE + 0.5);
+class ExpTest : public LIBC_NAMESPACE::testing::FPTest<double> {
+public:
+ void test_special_numbers(double (*func)(double)) {
+ EXPECT_FP_EQ(aNaN, func(aNaN));
+ EXPECT_FP_EQ(inf, func(inf));
+ EXPECT_FP_EQ_ALL_ROUNDING(zero, func(neg_inf));
+ EXPECT_FP_EQ_ALL_ROUNDING(1.0, func(0.0));
+ EXPECT_FP_EQ_ALL_ROUNDING(1.0, func(-0.0));
}
-}
-TEST_F(LlvmLibcExpTest, InDoubleRange) {
- constexpr uint64_t COUNT = 1'231;
- constexpr uint64_t START = FPBits(0.25).uintval();
- constexpr uint64_t STOP = FPBits(4.0).uintval();
- constexpr uint64_t STEP = (STOP - START) / COUNT;
-
- auto test = [&](mpfr::RoundingMode rounding_mode) {
- mpfr::ForceRoundingMode __r(rounding_mode);
- if (!__r.success)
- return;
-
- uint64_t fails = 0;
- uint64_t count = 0;
- uint64_t cc = 0;
- double mx, mr = 0.0;
- double tol = 0.5;
-
- for (uint64_t i = 0, v = START; i <= COUNT; ++i, v += STEP) {
- double x = FPBits(v).get_val();
- if (FPBits(v).is_nan() || FPBits(v).is_inf() || x < 0.0)
- continue;
- double result = LIBC_NAMESPACE::exp(x);
- ++cc;
- if (FPBits(result).is_nan() || FPBits(result).is_inf())
- continue;
-
- ++count;
- // ASSERT_MPFR_MATCH(mpfr::Operation::Log, x, result, 0.5);
- if (!TEST_MPFR_MATCH_ROUNDING_SILENTLY(mpfr::Operation::Exp, x, result,
- TOLERANCE + 0.5, rounding_mode)) {
- ++fails;
- while (!TEST_MPFR_MATCH_ROUNDING_SILENTLY(mpfr::Operation::Exp, x,
- result, tol, rounding_mode)) {
- mx = x;
- mr = result;
-
- if (tol > 1000.0)
- break;
-
- tol *= 2.0;
- }
+ void test_overflow(double (*func)(double)) {
+ EXPECT_FP_EQ_WITH_EXCEPTION(inf, func(0x1.0p20), FE_OVERFLOW);
+ }
+
+ void test_underflow(double (*func)(double)) {
+ EXPECT_FP_EQ_WITH_EXCEPTION(zero, func(-0x1.0p20), FE_UNDERFLOW);
+ }
+
+ void test_tricky_inputs(double (*func)(double), double ulp_tolerance = 0.5,
+ bool all_rounding = true) {
+ constexpr int N = 18;
+ constexpr uint64_t INPUTS[N] = {
+ 0x3ca0000000000000, // x = 0x1.0p-53
+ 0xbca0000000000000, // x = -0x1.0p-53
+ 0xbcc0000000000001, // x = -0x1.0000000000001p-51
+ 0xbd26000000000079, // x = -0x1.6000000000079p-45
+ 0x3fd79289c6e6a5c0, // x = 0x1.79289c6e6a5cp-2
+ 0x3fd05de80a173ea0, // x = 0x1.05de80a173eap-2
+ 0x3fda7b764e2cf47a, // x = 0x1.a7b764e2cf47ap-2
+ 0x4044c19e5712e377, // x = 0x1.4c19e5712e377p+5
+ 0x40862e42fefa39ef, // x = 0x1.62e42fefa39efp+9
+ 0xc039a74cdab36c28, // x = -0x1.9a74cdab36c28p+4
+ 0xc04757852a4b93aa, // x = -0x1.757852a4b93aap+5
+ 0xc085b3e4e2e3bba9, // x = -0x1.5b3e4e2e3bba9p+9
+ 0xc086960d591aec34, // x = -0x1.6960d591aec34p+9
+ 0xc086232c09d58d91, // x = -0x1.6232c09d58d91p+9
+ 0xc0874910d52d3051, // x = -0x1.74910d52d3051p+9
+ 0xc0867a172ceb0990, // x = -0x1.67a172ceb099p+9
+ 0xbf1eb7a4cb841fcc, // x = -0x1.eb7a4cb841fccp-14
+ 0xbf19a61fb925970d, // x = -0x1.9a61fb925970dp-14
+ };
+ for (int i = 0; i < N; ++i) {
+ double x = FPBits(INPUTS[i]).get_val();
+ if (all_rounding) {
+ EXPECT_MPFR_MATCH_ALL_ROUNDING(mpfr::Operation::Exp, x, func(x),
+ ulp_tolerance);
+ } else {
+ EXPECT_MPFR_MATCH(mpfr::Operation::Exp, x, func(x), ulp_tolerance);
}
}
- if (fails) {
- tlog << " Exp failed: " << fails << "/" << count << "/" << cc
- << " tests.\n";
- tlog << " Max ULPs is at most: " << static_cast<uint64_t>(tol) << ".\n";
- EXPECT_MPFR_MATCH(mpfr::Operation::Exp, mx, mr, 0.5, rounding_mode);
- }
- };
+ }
- tlog << " Test Rounding To Nearest...\n";
- test(mpfr::RoundingMode::Nearest);
+ void test_in_range(double (*func)(double), double ulp_tolerance = 0.5,
+ bool all_rounding = true) {
+ constexpr uint64_t COUNT = 1'231;
+ constexpr uint64_t START = FPBits(0.25).uintval();
+ constexpr uint64_t STOP = FPBits(4.0).uintval();
+ constexpr uint64_t STEP = (STOP - START) / COUNT;
+
+ auto test = [&](mpfr::RoundingMode rounding_mode) {
+ mpfr::ForceRoundingMode __r(rounding_mode);
+ if (!__r.success)
+ return;
+
+ uint64_t fails = 0;
+ uint64_t count = 0;
+ uint64_t cc = 0;
+ double mx = 0.0, mr = 0.0;
+ double tol = 0.5;
+
+ for (uint64_t i = 0, v = START; i <= COUNT; ++i, v += STEP) {
+ double x = FPBits(v).get_val();
+ if (FPBits(v).is_nan() || FPBits(v).is_inf() || x < 0.0)
+ continue;
+ double result = func(x);
+ ++cc;
+ if (FPBits(result).is_nan() || FPBits(result).is_inf())
+ continue;
+
+ ++count;
+ if (!TEST_MPFR_MATCH_ROUNDING_SILENTLY(mpfr::Operation::Exp, x, result,
+ ulp_tolerance, rounding_mode)) {
+ ++fails;
+ while (!TEST_MPFR_MATCH_ROUNDING_SILENTLY(
+ mpfr::Operation::Exp, x, result, tol, rounding_mode)) {
+ mx = x;
+ mr = result;
+
+ if (tol > 1000.0)
+ break;
+
+ tol *= 2.0;
+ }
+ }
+ }
+ if (fails) {
+ tlog << " Exp failed: " << fails << "/" << count << "/" << cc
+ << " tests.\n";
+ tlog << " Max ULPs is at most: " << static_cast<uint64_t>(tol)
+ << ".\n";
+ EXPECT_MPFR_MATCH(mpfr::Operation::Exp, mx, mr, ulp_tolerance,
+ rounding_mode);
+ }
+ };
- tlog << " Test Rounding Downward...\n";
- test(mpfr::RoundingMode::Downward);
+ tlog << " Test Rounding To Nearest...\n";
+ test(mpfr::RoundingMode::Nearest);
- tlog << " Test Rounding Upward...\n";
- test(mpfr::RoundingMode::Upward);
+ if (all_rounding) {
+ tlog << " Test Rounding Downward...\n";
+ test(mpfr::RoundingMode::Downward);
- tlog << " Test Rounding Toward Zero...\n";
- test(mpfr::RoundingMode::TowardZero);
-}
+ tlog << " Test Rounding Upward...\n";
+ test(mpfr::RoundingMode::Upward);
+
+ tlog << " Test Rounding Toward Zero...\n";
+ test(mpfr::RoundingMode::TowardZero);
+ }
+ }
+};
+
+#define LIST_EXP_TESTS(suffix, func, ulp_tolerance, all_rounding) \
+ using LlvmLibcExpTest##suffix = ExpTest; \
+ TEST_F(LlvmLibcExpTest##suffix, SpecialNumbers) { \
+ test_special_numbers(&func); \
+ } \
+ TEST_F(LlvmLibcExpTest##suffix, Overflow) { test_overflow(&func); } \
+ TEST_F(LlvmLibcExpTest##suffix, Underflow) { test_underflow(&func); } \
+ TEST_F(LlvmLibcExpTest##suffix, TrickyInputs) { \
+ test_tricky_inputs(&func, ulp_tolerance, all_rounding); \
+ } \
+ TEST_F(LlvmLibcExpTest##suffix, InDoubleRange) { \
+ test_in_range(&func, ulp_tolerance, all_rounding); \
+ } \
+ static_assert(true, "Require semicolon.")
+
+LIST_EXP_TESTS(Default, LIBC_NAMESPACE::exp,
+ /*ulp_tolerance=*/TOLERANCE + 0.5,
+ /*all_rounding=*/ALL_ROUNDING);
+LIST_EXP_TESTS(DoubleEval, exp_double_eval,
+ /*ulp_tolerance=*/TOLERANCE + 0.5,
+ /*all_rounding=*/ALL_ROUNDING);
diff --git a/libc/test/src/math/smoke/CMakeLists.txt b/libc/test/src/math/smoke/CMakeLists.txt
index a9293a3942fcad..76caeef863e342 100644
--- a/libc/test/src/math/smoke/CMakeLists.txt
+++ b/libc/test/src/math/smoke/CMakeLists.txt
@@ -1423,8 +1423,11 @@ add_fp_unittest(
exp_test.cpp
DEPENDS
libc.hdr.errno_macros
+ libc.hdr.fenv_macros
libc.src.math.exp
+ libc.src.__support.math.exp_double_eval
libc.src.__support.FPUtil.fp_bits
+ libc.src.__support.macros.attributes
)
add_fp_unittest(
diff --git a/libc/test/src/math/smoke/exp_test.cpp b/libc/test/src/math/smoke/exp_test.cpp
index 939727748ca083..608d1084ab692b 100644
--- a/libc/test/src/math/smoke/exp_test.cpp
+++ b/libc/test/src/math/smoke/exp_test.cpp
@@ -1,65 +1,104 @@
-//===-- Unittests for exp -------------------------------------------------===//
+//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file contains smoke tests for exp.
+///
+//===----------------------------------------------------------------------===//
#include "hdr/errno_macros.h"
+#include "hdr/fenv_macros.h"
#include "hdr/math_macros.h"
#include "hdr/stdint_proxy.h"
#include "src/__support/FPUtil/FPBits.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/math/exp_double_eval.h"
#include "src/math/exp.h"
#include "test/UnitTest/FPMatcher.h"
#include "test/UnitTest/Test.h"
-using LlvmLibcExpTest = LIBC_NAMESPACE::testing::FPTest<double>;
+LIBC_NOINLINE double exp_double_eval(double x) {
+ return LIBC_NAMESPACE::math::double_eval::exp(x);
+}
-TEST_F(LlvmLibcExpTest, SpecialNumbers) {
- EXPECT_FP_EQ_WITH_EXCEPTION(aNaN, LIBC_NAMESPACE::exp(sNaN), FE_INVALID);
- EXPECT_MATH_ERRNO(0);
+class ExpTest : public LIBC_NAMESPACE::testing::FPTest<double> {
+public:
+ void test_special_numbers(double (*func)(double),
+ bool check_snan_invalid = false) {
+ if (check_snan_invalid) {
+ EXPECT_FP_EQ_WITH_EXCEPTION(aNaN, func(sNaN), FE_INVALID);
+ } else {
+ EXPECT_FP_EQ(aNaN, func(sNaN));
+ }
+ EXPECT_MATH_ERRNO(0);
- EXPECT_FP_EQ(aNaN, LIBC_NAMESPACE::exp(aNaN));
- EXPECT_MATH_ERRNO(0);
- EXPECT_FP_EQ(inf, LIBC_NAMESPACE::exp(inf));
- EXPECT_MATH_ERRNO(0);
- EXPECT_FP_EQ_ALL_ROUNDING(zero, LIBC_NAMESPACE::exp(neg_inf));
- EXPECT_MATH_ERRNO(0);
+ EXPECT_FP_EQ_ALL_ROUNDING(aNaN, func(aNaN));
+ EXPECT_MATH_ERRNO(0);
- EXPECT_FP_EQ_WITH_EXCEPTION(zero, LIBC_NAMESPACE::exp(-0x1.0p20),
- FE_UNDERFLOW);
- EXPECT_MATH_ERRNO(ERANGE);
- EXPECT_FP_EQ_WITH_EXCEPTION(inf, LIBC_NAMESPACE::exp(0x1.0p20), FE_OVERFLOW);
- EXPECT_MATH_ERRNO(ERANGE);
+ EXPECT_FP_EQ_ALL_ROUNDING(inf, func(inf));
+ EXPECT_MATH_ERRNO(0);
- EXPECT_FP_EQ_ALL_ROUNDING(1.0, LIBC_NAMESPACE::exp(0.0));
- EXPECT_FP_EQ_ALL_ROUNDING(1.0, LIBC_NAMESPACE::exp(-0.0));
-}
+ EXPECT_FP_EQ_ALL_ROUNDING(zero, func(neg_inf));
+ EXPECT_MATH_ERRNO(0);
-#ifdef LIBC_TEST_FTZ_DAZ
+ EXPECT_FP_EQ_ALL_ROUNDING(1.0, func(0.0));
+ EXPECT_MATH_ERRNO(0);
-using namespace LIBC_NAMESPACE::testing;
+ EXPECT_FP_EQ_ALL_ROUNDING(1.0, func(-0.0));
+ EXPECT_MATH_ERRNO(0);
+ }
-TEST_F(LlvmLibcExpTest, FTZMode) {
- ModifyMXCSR mxcsr(FTZ);
+ void test_overflow(double (*func)(double)) {
+ EXPECT_FP_EQ_WITH_EXCEPTION(inf, func(0x1.0p20), FE_OVERFLOW);
+ EXPECT_MATH_ERRNO(ERANGE);
+ }
- EXPECT_FP_EQ(1.0, LIBC_NAMESPACE::exp(min_denormal));
- EXPECT_FP_EQ(1.0, LIBC_NAMESPACE::exp(max_denormal));
-}
+ void test_underflow(double (*func)(double)) {
+ EXPECT_FP_EQ_WITH_EXCEPTION(zero, func(-0x1.0p20), FE_UNDERFLOW);
+ EXPECT_MATH_ERRNO(ERANGE);
+ }
-TEST_F(LlvmLibcExpTest, DAZMode) {
- ModifyMXCSR mxcsr(DAZ);
-
- EXPECT_FP_EQ(1.0, LIBC_NAMESPACE::exp(min_denormal));
- EXPECT_FP_EQ(1.0, LIBC_NAMESPACE::exp(max_denormal));
-}
+#ifdef LIBC_TEST_FTZ_DAZ
+ void test_denormals(double (*func)(double)) {
+ EXPECT_FP_EQ(1.0, func(min_denormal));
+ EXPECT_FP_EQ(1.0, func(max_denormal));
+ }
+#endif // LIBC_TEST_FTZ_DAZ
+};
-TEST_F(LlvmLibcExpTest, FTZDAZMode) {
- ModifyMXCSR mxcsr(FTZ | DAZ);
+#ifdef LIBC_TEST_FTZ_DAZ
+#define LIST_EXP_FTZ_DAZ_TESTS(suffix, func) \
+ TEST_F(LlvmLibcExpTest##suffix, FTZMode) { \
+ LIBC_NAMESPACE::testing::ModifyMXCSR mxcsr(LIBC_NAMESPACE::testing::FTZ); \
+ test_denormals(&func); \
+ } \
+ TEST_F(LlvmLibcExpTest##suffix, DAZMode) { \
+ LIBC_NAMESPACE::testing::ModifyMXCSR mxcsr(LIBC_NAMESPACE::testing::DAZ); \
+ test_denormals(&func); \
+ } \
+ TEST_F(LlvmLibcExpTest##suffix, FTZDAZMode) { \
+ LIBC_NAMESPACE::testing::ModifyMXCSR mxcsr(LIBC_NAMESPACE::testing::FTZ | \
+ LIBC_NAMESPACE::testing::DAZ); \
+ test_denormals(&func); \
+ }
+#else // !LIBC_TEST_FTZ_DAZ
+#define LIST_EXP_FTZ_DAZ_TESTS(suffix, func)
+#endif // LIBC_TEST_FTZ_DAZ
- EXPECT_FP_EQ(1.0, LIBC_NAMESPACE::exp(min_denormal));
- EXPECT_FP_EQ(1.0, LIBC_NAMESPACE::exp(max_denormal));
-}
+#define LIST_EXP_TESTS(suffix, func, check_snan_invalid) \
+ using LlvmLibcExpTest##suffix = ExpTest; \
+ TEST_F(LlvmLibcExpTest##suffix, SpecialNumbers) { \
+ test_special_numbers(&func, check_snan_invalid); \
+ } \
+ TEST_F(LlvmLibcExpTest##suffix, Overflow) { test_overflow(&func); } \
+ TEST_F(LlvmLibcExpTest##suffix, Underflow) { test_underflow(&func); } \
+ LIST_EXP_FTZ_DAZ_TESTS(suffix, func) \
+ static_assert(true, "Require semicolon.")
-#endif
+LIST_EXP_TESTS(Default, LIBC_NAMESPACE::exp, /*check_snan_invalid=*/true);
+LIST_EXP_TESTS(DoubleEval, exp_double_eval, /*check_snan_invalid=*/false);
diff --git a/utils/bazel/llvm-project-overlay/libc/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/BUILD.bazel
index cbb357d07e88ae..52b18885d90982 100644
--- a/utils/bazel/llvm-project-overlay/libc/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/BUILD.bazel
@@ -5093,6 +5093,7 @@ cc_library(
":__support_fputil_float128",
":__support_fputil_fma",
":__support_fputil_fp_bits",
+ ":__support_fputil_fp_bitwise",
":__support_fputil_generic_fmod",
":__support_fputil_hypot",
":__support_fputil_manipulation_functions",
@@ -10623,12 +10624,12 @@ libc_support_library(
":__support_fputil_double_double",
":__support_fputil_fenv_impl",
":__support_fputil_fp_bits",
+ ":__support_fputil_fp_bitwise",
":__support_fputil_multiply_add",
":__support_fputil_rounding_mode",
":__support_macros_attributes",
":__support_macros_config",
":__support_macros_optimization",
- ":__support_macros_properties_architectures",
":__support_macros_properties_cpu_features",
":__support_math_exp2_accurate_128",
":hdr_errno_macros",
@@ -10716,49 +10717,54 @@ libc_support_library(
)
libc_support_library(
- name = "__support_math_exp",
- hdrs = ["src/__support/math/exp.h"],
+ name = "__support_math_exp_double_utils",
+ hdrs = ["src/__support/math/exp_double_utils.h"],
deps = [
":__support_common",
- ":__support_cpp_bit",
- ":__support_cpp_optional",
- ":__support_fputil_double_double",
- ":__support_fputil_dyadic_float",
":__support_fputil_fenv_impl",
":__support_fputil_fp_bits",
+ ":__support_fputil_fp_bitwise",
":__support_fputil_multiply_add",
- ":__support_fputil_nearest_integer",
- ":__support_fputil_polyeval",
- ":__support_fputil_rounding_mode",
- ":__support_fputil_triple_double",
- ":__support_integer_literals",
+ ":__support_macros_attributes",
":__support_macros_config",
":__support_macros_optimization",
- ":__support_math_exp_constants",
":__support_math_exp_utils",
+ ":hdr_errno_macros",
],
)
libc_support_library(
- name = "__support_math_exp_double_utils",
- hdrs = ["src/__support/math/exp_double_utils.h"],
+ name = "__support_math_exp2_double_eval",
+ hdrs = ["src/__support/math/exp2_double_eval.h"],
deps = [
":__support_common",
- ":__support_cpp_bit",
- ":__support_fputil_fenv_impl",
+ ":__support_fputil_double_double",
":__support_fputil_fp_bits",
":__support_fputil_multiply_add",
+ ":__support_fputil_nearest_integer",
":__support_macros_attributes",
":__support_macros_config",
":__support_macros_optimization",
+ ":__support_macros_properties_cpu_features",
+ ":__support_math_exp_double_utils",
":__support_math_exp_utils",
- ":hdr_errno_macros",
],
)
libc_support_library(
- name = "__support_math_exp2_double_eval",
- hdrs = ["src/__support/math/exp2_double_eval.h"],
+ name = "__support_math_exp2",
+ hdrs = ["src/__support/math/exp2.h"],
+ deps = [
+ ":__support_common",
+ ":__support_macros_config",
+ ":__support_macros_optimization",
+ ":__support_math_exp2_double_eval",
+ ],
+)
+
+libc_support_library(
+ name = "__support_math_exp_double_eval",
+ hdrs = ["src/__support/math/exp_double_eval.h"],
deps = [
":__support_common",
":__support_fputil_double_double",
@@ -10775,13 +10781,13 @@ libc_support_library(
)
libc_support_library(
- name = "__support_math_exp2",
- hdrs = ["src/__support/math/exp2.h"],
+ name = "__support_math_exp",
+ hdrs = ["src/__support/math/exp.h"],
deps = [
":__support_common",
":__support_macros_config",
":__support_macros_optimization",
- ":__support_math_exp2_double_eval",
+ ":__support_math_exp_double_eval",
],
)
diff --git a/utils/bazel/llvm-project-overlay/libc/test/src/math/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/test/src/math/BUILD.bazel
index cdb8d203c06e11..c39dc612851536 100644
--- a/utils/bazel/llvm-project-overlay/libc/test/src/math/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/test/src/math/BUILD.bazel
@@ -188,7 +188,13 @@ math_mpfr_test(name = "erff16")
math_mpfr_test(name = "erfcf16")
-math_mpfr_test(name = "exp")
+math_mpfr_test(
+ name = "exp",
+ deps = [
+ "//libc:__support_macros_attributes",
+ "//libc:__support_math_exp_double_eval",
+ ],
+)
math_mpfr_test(
name = "expf",
diff --git a/utils/bazel/llvm-project-overlay/libc/test/src/math/smoke/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/test/src/math/smoke/BUILD.bazel
index 40e8163f8a86e9..238b2852e4cc6c 100644
--- a/utils/bazel/llvm-project-overlay/libc/test/src/math/smoke/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/test/src/math/smoke/BUILD.bazel
@@ -499,7 +499,13 @@ math_test(name = "erfcf16")
math_test(name = "erff16")
-math_test(name = "exp")
+math_test(
+ name = "exp",
+ deps = [
+ "//libc:__support_macros_attributes",
+ "//libc:__support_math_exp_double_eval",
+ ],
+)
math_test(
name = "expf",
>From 96439c6156649435adb9ee287aa6862257ddbace Mon Sep 17 00:00:00 2001
From: Tue Ly <lntue.h at gmail.com>
Date: Wed, 21 Oct 2026 22:17:03 +0000
Subject: [PATCH 2/3] Update hi range comment on exp2_eval.
---
libc/src/__support/math/exp_utils.h | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/libc/src/__support/math/exp_utils.h b/libc/src/__support/math/exp_utils.h
index 2958c00355ac54..46a1cc8f186375 100644
--- a/libc/src/__support/math/exp_utils.h
+++ b/libc/src/__support/math/exp_utils.h
@@ -450,7 +450,13 @@ exp_denorm(double x, int hi, double r_hi, double lo_u, double err_d,
// with |u.hi + u.lo| <= 2^-8 * log(2). On targets without FMA,
// lsb(u.hi) >= 2^-30 and |u.lo| < 2^-18
// so that m_hi * u.hi is exact in double.
-// - hi: integer exponent k >> 7 in [-1075, 1023].
+// - hi: integer exponent k >> 7 in [-1075, 1024].
+// When hi == 1024, k = 1024 * 2^7 so
+// idx = 0 (exp2_mid = 1.0) and u < -2^-46 < 0,
+// since x is strictly below the overflow threshold, which keeps upper in
+// [1 - 2^-8, 1) with unbiased exponent -1 (biased exponent 1022). Adding
+// hi = 1024 in scale_exp2(upper, hi) then produces biased exponent 2046
+// (unbiased exponent 1023) without overflowing.
// - idx: table index k & 0x7f in [0, 127].
// - err_d: Ziv error bound on the double-double approximation r_hi + r_lo.
// - log2_base: pointer to 192-bit log2(b) table (or nullptr when b = 2).
>From 1541760e337ef8c6399e1968359a1ea4599d80dd Mon Sep 17 00:00:00 2001
From: Tue Ly <lntue.h at gmail.com>
Date: Thu, 22 Oct 2026 15:40:59 +0000
Subject: [PATCH 3/3] Remove redundant typename from non-dependent type
aliases.
---
libc/src/__support/math/exp2_accurate_128.h | 2 +-
libc/src/__support/math/exp2_double_eval.h | 2 +-
libc/src/__support/math/exp_double_eval.h | 2 +-
libc/src/__support/math/exp_double_utils.h | 2 +-
libc/src/__support/math/exp_utils.h | 4 ++--
5 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/libc/src/__support/math/exp2_accurate_128.h b/libc/src/__support/math/exp2_accurate_128.h
index 1efbf487a29261..31c8bde4259756 100644
--- a/libc/src/__support/math/exp2_accurate_128.h
+++ b/libc/src/__support/math/exp2_accurate_128.h
@@ -27,7 +27,7 @@ namespace LIBC_NAMESPACE_DECL {
namespace math {
namespace double_eval {
-using DFloat128 = typename fputil::DyadicFloat<128>;
+using DFloat128 = fputil::DyadicFloat<128>;
// Table of 2^(i / 16) with i = 0..15 in 128-bit fixed-point format:
// Generated by Sollya with:
diff --git a/libc/src/__support/math/exp2_double_eval.h b/libc/src/__support/math/exp2_double_eval.h
index c3cb23c57a19d3..8e2e372b58fbac 100644
--- a/libc/src/__support/math/exp2_double_eval.h
+++ b/libc/src/__support/math/exp2_double_eval.h
@@ -34,7 +34,7 @@ namespace math {
namespace double_eval {
LIBC_ALWAYS_INLINE double exp2(double x) {
- using FPBits = typename fputil::FPBits<double>;
+ using FPBits = fputil::FPBits<double>;
FPBits xbits(x);
uint64_t x_u = xbits.uintval();
diff --git a/libc/src/__support/math/exp_double_eval.h b/libc/src/__support/math/exp_double_eval.h
index 15cdd4c318a804..ef75ee37c5be62 100644
--- a/libc/src/__support/math/exp_double_eval.h
+++ b/libc/src/__support/math/exp_double_eval.h
@@ -35,7 +35,7 @@ namespace math {
namespace double_eval {
LIBC_ALWAYS_INLINE double exp(double x) {
- using FPBits = typename fputil::FPBits<double>;
+ using FPBits = fputil::FPBits<double>;
FPBits xbits(x);
uint64_t x_u = xbits.uintval();
diff --git a/libc/src/__support/math/exp_double_utils.h b/libc/src/__support/math/exp_double_utils.h
index dcb4128796df94..00c43235f63ed2 100644
--- a/libc/src/__support/math/exp_double_utils.h
+++ b/libc/src/__support/math/exp_double_utils.h
@@ -141,7 +141,7 @@ LIBC_INLINE_VAR constexpr double EXP2_MID[128] = {
LIBC_NOINLINE LIBC_INLINE double exp_denorm(double x, int hi, double r,
bool is_exp2) {
- using FPBits = typename fputil::FPBits<double>;
+ using FPBits = fputil::FPBits<double>;
if (is_exp2 && LIBC_UNLIKELY(static_cast<double>(hi) == x))
return FPBits(uint64_t(1) << (hi + 1074)).get_val();
diff --git a/libc/src/__support/math/exp_utils.h b/libc/src/__support/math/exp_utils.h
index 46a1cc8f186375..fa909c824efc5f 100644
--- a/libc/src/__support/math/exp_utils.h
+++ b/libc/src/__support/math/exp_utils.h
@@ -111,7 +111,7 @@ LIBC_INLINE_VAR constexpr DoubleDouble LOG2_E = {0x1.777d0ffda0d24p-56,
// tiny, underflow, or overflow/inf/nan range for the specific function before
// calling this helper.
LIBC_NOINLINE LIBC_INLINE double set_exceptional(double x) {
- using FPBits = typename fputil::FPBits<double>;
+ using FPBits = fputil::FPBits<double>;
FPBits xbits(x);
// |x| <= 0x1.0p-53 (caller has already checked the exact tiny bound):
@@ -419,7 +419,7 @@ LIBC_INLINE_VAR constexpr DoubleDouble EXP2_MID[128] = {
LIBC_NOINLINE LIBC_INLINE double
exp_denorm(double x, int hi, double r_hi, double lo_u, double err_d,
const ExpBase192 *log2_base = nullptr) {
- using FPBits = typename fputil::FPBits<double>;
+ using FPBits = fputil::FPBits<double>;
// Exact subnormal power of 2 when x is an integer in [-1074, -1022].
if (log2_base == nullptr && LIBC_UNLIKELY(static_cast<double>(hi) == x))
return FPBits(uint64_t(1) << (hi + 1074)).get_val();
More information about the libc-commits
mailing list