[libc-commits] [libc] [llvm] [libc][math] Optimize exp2 and refactor shared double-precision exp utilities. (PR #231041)

via libc-commits libc-commits at lists.llvm.org
Sun Oct 11 15:15:16 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libc

Author: lntue

<details>
<summary>Changes</summary>

Refactor double-precision `exp2` to improve latency, throughput, and code                                               
sharing across `exp`, `exp2`, `exp10`, and `pow`, while adding support for                                              
`LIBC_MATH_HAS_SMALL_TABLES` and `LIBC_MATH_HAS_SKIP_ACCURATE_PASS`.

Algorithm & implementation overview:
- Fast path (`exp2_double_eval.h`, `exp_utils.h`):
  - Single-step range reduction `x = k * 2^-N + dx` (`N = 7` by default, or
    `N = 4` when `LIBC_MATH_HAS_SMALL_TABLES` is enabled) with
    `hi = k >> N`, `idx = k & (2^N - 1)`, and `u = dx * log(2)`.
  - Without FMA, use fixed-point splitting (`SPLIT_18` on `dx`, `LOG_2_HI_12`
    on `log(2)`, and `SPLIT_22` on `EXP2_MID[idx]`) so `m_hi * (1 + u_hi)` is
    exact in `double` without needing Veltkamp splitting or `DoubleDouble`
    multiplications.
  - Approximate `(exp(u) - 1 - u) / u^2` with a degree-3 minimax polynomial
    evaluated with Estrin's scheme (`exp_poly`), and reconstruct
    `2^(idx / 2^N) * exp(u)` followed by Ziv's rounding test.
  - Scale `2^hi * r` directly in vector registers (`scale_exp2`) using SSE2
    and NEON integer additions on the exponent field to avoid
    float-to-GPR-to-float round-trips.

- Single-precision / skip-accurate-pass variant (`exp_double_utils.h`):
  - When `LIBC_MATH_HAS_SKIP_ACCURATE_PASS` is enabled, evaluate `exp2_eval`
    purely in `double` precision (~0.51 ULP error, <= 1 ULP in RN and <= 2 ULPs
    in directed rounding modes).

- 128-bit accurate path (`exp2_accurate_128.h`):
  - Replace the previous 2-step `DyadicFloat<128>` lookup tables (`2^-6` and
    `2^-12`) and degree-6 `DyadicFloat<128>` Taylor polynomial with a single
    16-entry `Frac128` lookup table (`EXP2_MID_FRAC128`, `2^(i/16)`) and a
    degree-14 minimax polynomial (`EXP2_POLY_128`) in 128-bit fixed-point
    arithmetic.
  - Provide `exp_accurate_128` and `exp2_df128` to be shared across `exp2`,
    `exp`, `exp10`, and `pow`.

- File organization & tests:
  - Split `double_eval::exp2` into `libc/src/__support/math/exp2_double_eval.h`
    so `double_eval::exp2` can be tested directly alongside `libc::exp2`.
  - Add a `LIBC_NOINLINE` wrapper around `double_eval::exp2` in unit and smoke
    tests to prevent excessive inlining into test functions.

Assisted-by: Gemini was used for performance analysis, error bound verification, and refactoring.

---

Patch is 89.50 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/231041.diff


15 Files Affected:

- (modified) libc/src/__support/FPUtil/PolyEval.h (+10-3) 
- (modified) libc/src/__support/FPUtil/multiply_add.h (+10-3) 
- (modified) libc/src/__support/math/CMakeLists.txt (+64-11) 
- (modified) libc/src/__support/math/exp2.h (+13-424) 
- (added) libc/src/__support/math/exp2_accurate_128.h (+228) 
- (added) libc/src/__support/math/exp2_double_eval.h (+133) 
- (added) libc/src/__support/math/exp_double_utils.h (+175) 
- (modified) libc/src/__support/math/exp_utils.h (+474-1) 
- (modified) libc/test/src/math/CMakeLists.txt (+2) 
- (modified) libc/test/src/math/exp2_test.cpp (+160-95) 
- (modified) libc/test/src/math/smoke/CMakeLists.txt (+2) 
- (modified) libc/test/src/math/smoke/exp2_test.cpp (+81-41) 
- (modified) utils/bazel/llvm-project-overlay/libc/BUILD.bazel (+61-11) 
- (modified) utils/bazel/llvm-project-overlay/libc/test/src/math/BUILD.bazel (+6-1) 
- (modified) utils/bazel/llvm-project-overlay/libc/test/src/math/smoke/BUILD.bazel (+6-1) 


``````````diff
diff --git a/libc/src/__support/FPUtil/PolyEval.h b/libc/src/__support/FPUtil/PolyEval.h
index 58a3f4e24fdeb..55583cca70c3b 100644
--- a/libc/src/__support/FPUtil/PolyEval.h
+++ b/libc/src/__support/FPUtil/PolyEval.h
@@ -1,10 +1,15 @@
-//===-- Common header for PolyEval implementations --------------*- 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
+/// Common header for PolyEval implementations.
+///
+//===----------------------------------------------------------------------===//
 
 #ifndef LLVM_LIBC_SRC___SUPPORT_FPUTIL_POLYEVAL_H
 #define LLVM_LIBC_SRC___SUPPORT_FPUTIL_POLYEVAL_H
@@ -67,13 +72,15 @@ altpolyeval(T, T a0) {
 template <typename T, typename... Ts>
 LIBC_INLINE constexpr cpp::enable_if_t<(sizeof(T) > sizeof(void *)), T>
 altpolyeval(const T &x, const T &a0, const Ts &...a) {
-  return a0 - x * altpolyeval(x, a...);
+  T prod = x * altpolyeval(x, a...);
+  return a0 - prod;
 }
 
 template <typename T, typename... Ts>
 LIBC_INLINE constexpr cpp::enable_if_t<(sizeof(T) <= sizeof(void *)), T>
 altpolyeval(T x, T a0, Ts... a) {
-  return a0 - x * altpolyeval(x, a...);
+  T prod = x * altpolyeval(x, a...);
+  return a0 - prod;
 }
 
 } // namespace fputil
diff --git a/libc/src/__support/FPUtil/multiply_add.h b/libc/src/__support/FPUtil/multiply_add.h
index dce09622cd668..fe87877d2443d 100644
--- a/libc/src/__support/FPUtil/multiply_add.h
+++ b/libc/src/__support/FPUtil/multiply_add.h
@@ -1,10 +1,15 @@
-//===-- Common header for multiply-add implementations ----------*- 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
+/// Common header for multiply-add implementations.
+///
+//===----------------------------------------------------------------------===//
 
 #ifndef LLVM_LIBC_SRC___SUPPORT_FPUTIL_MULTIPLY_ADD_H
 #define LLVM_LIBC_SRC___SUPPORT_FPUTIL_MULTIPLY_ADD_H
@@ -25,13 +30,15 @@ namespace fputil {
 template <typename T>
 LIBC_INLINE constexpr cpp::enable_if_t<(sizeof(T) > sizeof(void *)), T>
 multiply_add(const T &x, const T &y, const T &z) {
-  return x * y + z;
+  T prod = x * y;
+  return prod + z;
 }
 
 template <typename T>
 LIBC_INLINE constexpr cpp::enable_if_t<(sizeof(T) <= sizeof(void *)), T>
 multiply_add(T x, T y, T z) {
-  return x * y + z;
+  T prod = x * y;
+  return prod + z;
 }
 
 } // namespace fputil
diff --git a/libc/src/__support/math/CMakeLists.txt b/libc/src/__support/math/CMakeLists.txt
index ef33e3f8ada7b..3a19ee880fe06 100644
--- a/libc/src/__support/math/CMakeLists.txt
+++ b/libc/src/__support/math/CMakeLists.txt
@@ -4195,14 +4195,43 @@ add_header_library(
     libc.src.__support.FPUtil.triple_double
 )
 
+add_header_library(
+  exp2_accurate_128
+  HDRS
+    exp2_accurate_128.h
+  DEPENDS
+    libc.src.__support.FPUtil.dyadic_float
+    libc.src.__support.FPUtil.fp_bits
+    libc.src.__support.common
+    libc.src.__support.frac128
+    libc.src.__support.frac64
+    libc.src.__support.macros.attributes
+    libc.src.__support.macros.config
+    libc.src.__support.macros.optimization
+    libc.src.__support.uint128
+)
+
 add_header_library(
   exp_utils
   HDRS
     exp_utils.h
   DEPENDS
-    libc.src.__support.CPP.optional
+    .exp2_accurate_128
+    libc.hdr.errno_macros
+    libc.hdr.fenv_macros
     libc.src.__support.CPP.bit
+    libc.src.__support.CPP.optional
+    libc.src.__support.FPUtil.double_double
+    libc.src.__support.FPUtil.fenv_impl
     libc.src.__support.FPUtil.fp_bits
+    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(
@@ -4227,25 +4256,49 @@ add_header_library(
 )
 
 add_header_library(
-  exp2
+  exp_double_utils
   HDRS
-    exp2.h
+    exp_double_utils.h
   DEPENDS
-    .common_constants
     .exp_utils
+    libc.hdr.errno_macros
     libc.src.__support.CPP.bit
-    libc.src.__support.CPP.optional
-    libc.src.__support.FPUtil.dyadic_float
     libc.src.__support.FPUtil.fenv_impl
     libc.src.__support.FPUtil.fp_bits
     libc.src.__support.FPUtil.multiply_add
+    libc.src.__support.common
+    libc.src.__support.macros.attributes
+    libc.src.__support.macros.config
+    libc.src.__support.macros.optimization
+)
+
+add_header_library(
+  exp2_double_eval
+  HDRS
+    exp2_double_eval.h
+  DEPENDS
+    .exp_double_utils
+    .exp_utils
+    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.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
+    libc.src.__support.macros.properties.cpu_features
+)
+
+add_header_library(
+  exp2
+  HDRS
+    exp2.h
+  DEPENDS
+    .exp2_double_eval
+    libc.src.__support.common
+    libc.src.__support.macros.config
     libc.src.__support.macros.optimization
-    libc.src.errno.errno
 )
 
 add_header_library(
diff --git a/libc/src/__support/math/exp2.h b/libc/src/__support/math/exp2.h
index 084578796e422..12bad5db2a9b2 100644
--- a/libc/src/__support/math/exp2.h
+++ b/libc/src/__support/math/exp2.h
@@ -1,445 +1,34 @@
-//===-- Implementation header for exp2 --------------------------*- 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 exp2.
+///
+//===----------------------------------------------------------------------===//
 
 #ifndef LLVM_LIBC_SRC___SUPPORT_MATH_EXP2_H
 #define LLVM_LIBC_SRC___SUPPORT_MATH_EXP2_H
 
-#include "common_constants.h" // Lookup tables EXP2_MID1 and EXP_M2.
-#include "exp_constants.h"
-#include "exp_utils.h" // ziv_test_denorm.
-#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/exp2_double_eval.h"
+#define LIBC_MATH_EXP2_IMPL double_eval
 
+namespace LIBC_NAMESPACE_DECL {
 namespace math {
 
-namespace exp2_internal {
-
-using namespace common_constants_internal;
-
-using fputil::DoubleDouble;
-using fputil::TripleDouble;
-using DFloat128 = typename fputil::DyadicFloat<128>;
-
-using LIBC_NAMESPACE::operator""_u128;
-
-// Error bounds:
-// Errors when using double precision.
-#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE
-LIBC_INLINE_VAR constexpr double ERR_D = 0x1.0p-63;
-#else
-LIBC_INLINE_VAR constexpr double ERR_D = 0x1.8p-63;
-#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE
-
-#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-// Errors when using double-double precision.
-LIBC_INLINE_VAR constexpr double ERR_DD = 0x1.0p-100;
-#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-
-// Polynomial approximations with double precision.  Generated by Sollya with:
-// > P = fpminimax((2^x - 1)/x, 3, [|D...|], [-2^-13 - 2^-30, 2^-13 + 2^-30]);
-// > P;
-// Error bounds:
-//   | output - (2^dx - 1) / dx | < 1.5 * 2^-52.
-LIBC_INLINE double poly_approx_d(double dx) {
-  // dx^2
-  double dx2 = dx * dx;
-  double c0 =
-      fputil::multiply_add(dx, 0x1.ebfbdff82c58ep-3, 0x1.62e42fefa39efp-1);
-  double c1 =
-      fputil::multiply_add(dx, 0x1.3b2aba7a95a89p-7, 0x1.c6b08e8fc0c0ep-5);
-  double p = fputil::multiply_add(dx2, c1, c0);
-  return p;
-}
-
-#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-// Polynomial approximation with double-double precision.  Generated by Solya
-// with:
-// > P = fpminimax((2^x - 1)/x, 5, [|DD...|], [-2^-13 - 2^-30, 2^-13 + 2^-30]);
-// Error bounds:
-//   | output - 2^(dx) | < 2^-101
-LIBC_INLINE DoubleDouble poly_approx_dd(const DoubleDouble &dx) {
-  // Taylor polynomial.
-  constexpr DoubleDouble COEFFS[] = {
-      {0, 0x1p0},
-      {0x1.abc9e3b39824p-56, 0x1.62e42fefa39efp-1},
-      {-0x1.5e43a53e4527bp-57, 0x1.ebfbdff82c58fp-3},
-      {-0x1.d37963a9444eep-59, 0x1.c6b08d704a0cp-5},
-      {0x1.4eda1a81133dap-62, 0x1.3b2ab6fba4e77p-7},
-      {-0x1.c53fd1ba85d14p-64, 0x1.5d87fe7a265a5p-10},
-      {0x1.d89250b013eb8p-70, 0x1.430912f86cb8ep-13},
-  };
-
-  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 + a0 * dx + a1 * dx^2 + ... + a6 * dx^7
-// 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, -128, 0xb17217f7'd1cf79ab'c9e3b398'03f2f6af_u128},
-      {Sign::POS, -128, 0x3d7f7bff'058b1d50'de2d60dd'9c9a1d9f_u128},
-      {Sign::POS, -132, 0xe35846b8'2505fc59'9d3b15d9'e7fb6897_u128},
-      {Sign::POS, -134, 0x9d955b7d'd273b94e'184462f6'bcd2b9e7_u128},
-      {Sign::POS, -137, 0xaec3ff3c'53398883'39ea1bb9'64c51a89_u128},
-      {Sign::POS, -138, 0x2861225f'345c396a'842c5341'8fa8ae61_u128},
-      {Sign::POS, -144, 0xffe5fe2d'109a319d'7abeb5ab'd5ad2079_u128},
-  };
-
-  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 2^(x) using 128-bit precision.
-// TODO(lntue): investigate triple-double precision implementation for this
-// step.
-LIBC_INLINE DFloat128 exp2_f128(double x, int hi, int idx1, int idx2) {
-  DFloat128 dx = DFloat128(x);
-
-  // 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 += hi;
-
-  return r;
-}
-
-// Compute 2^x with double-double precision.
-LIBC_INLINE DoubleDouble exp2_double_double(double x,
-                                            const DoubleDouble &exp_mid) {
-  DoubleDouble dx({0, x});
-
-  // Degree-6 polynomial approximation in double-double precision.
-  // | p - 2^x | < 2^-103.
-  DoubleDouble p = poly_approx_dd(dx);
-
-  // Error bounds: 2^-102.
-  DoubleDouble r = fputil::quick_mult(exp_mid, p);
-
-  return r;
-}
-#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-
-// When output is denormal.
-LIBC_INLINE double exp2_denorm(double x) {
-  // Range reduction.
-  int k =
-      static_cast<int>(cpp::bit_cast<uint64_t>(x + 0x1.8000'0000'4p21) >> 19);
-  double kd = static_cast<double>(k);
-
-  uint32_t idx1 = (k >> 6) & 0x3f;
-  uint32_t idx2 = k & 0x3f;
-
-  int hi = k >> 12;
-
-  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);
-
-  // |dx| < 2^-13 + 2^-30.
-  double dx = fputil::multiply_add(kd, -0x1.0p-12, x); // exact
-
-  double mid_lo = dx * exp_mid.hi;
-
-  // Approximate (2^dx - 1)/dx ~ 1 + a0*dx + a1*dx^2 + a2*dx^3 + a3*dx^4.
-  double p = poly_approx_d(dx);
-
-  double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);
-
-#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-  return ziv_test_denorm</*SKIP_ZIV_TEST=*/true>(hi, exp_mid.hi, lo, ERR_D)
-      .value();
-#else
-  using FPBits = fputil::FPBits<double>;
-
-  if (auto r = ziv_test_denorm(hi, exp_mid.hi, lo, ERR_D);
-      LIBC_LIKELY(r.has_value())) {
-    double res = r.value();
-    if (LIBC_UNLIKELY(FPBits(res).is_normal()))
-      return res;
-    if (x != fputil::nearest_integer(x)) {
-      fputil::set_errno_if_required(ERANGE);
-      fputil::raise_underflow_except_if_required<double>();
-    }
-    return res;
-  }
-
-  // Use double-double
-  DoubleDouble r_dd = exp2_double_double(dx, exp_mid);
-
-  if (auto r = ziv_test_denorm(hi, r_dd.hi, r_dd.lo, ERR_DD);
-      LIBC_LIKELY(r.has_value())) {
-    double res = r.value();
-    if (LIBC_UNLIKELY(FPBits(res).is_normal()))
-      return res;
-    if (x != fputil::nearest_integer(x)) {
-      fputil::set_errno_if_required(ERANGE);
-      fputil::raise_underflow_except_if_required<double>();
-    }
-    return res;
-  }
-
-  // Use 128-bit precision
-  DFloat128 r_f128 = exp2_f128(dx, hi, idx1, idx2);
-
-  return static_cast<double>(r_f128);
-#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
-}
-
-// Check for exceptional cases when:
-//  * log2(1 - 2^-54) < x < log2(1 + 2^-53)
-//  * x >= 1024
-//  * x <= -1022
-//  * x is inf or nan
-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| < log2(1 + 2^-53)
-  if (x_abs <= 0x3ca71547652b82fd) {
-    // 2^(x) ~ 1 + x/2
-    return fputil::multiply_add(x, 0.5, 1.0);
-  }
-
-  // x <= -1022 || x >= 1024 or inf/nan.
-  if (x_u > 0xc08ff00000000000) {
-    // x <= -1075 or -inf/nan
-    if (x_u >= 0xc090cc0000000000) {
-      // exp(-Inf) = 0
-      if (xbits.is_inf())
-        return 0.0;
-
-      // exp(nan) = nan
-      if (xbits.is_nan())
-        return x + FPBits::inf().get_val();
-
-      fputil::set_errno_if_required(ERANGE);
-      fputil::raise_underflow_except_if_required<double>();
-#ifndef LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
-      if (fputil::quick_get_round() == FE_UPWARD)
-        return FPBits::min_subnormal().get_val();
-#endif
-      return 0.0;
-    }
-
-    return exp2_denorm(x);
-  }
-
-  // x >= 1024 or +inf/nan
-  // x is finite
-  if (x_u < 0x7ff0'0000'0000'0000ULL) {
-    fputil::set_errno_if_required(ERANGE);
-    fputil::raise_overflow_except_if_required<double>();
-#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
-    return FPBits::inf().get_val();
-  }
-  // x is +inf or nan
-  return x + FPBits::inf().get_val();
-}
-
-} // namespace exp2_internal
-
-LIBC_INLINE double exp2(double x) {
-  using namespace exp2_internal;
-  using FPBits = typename fputil::FPBits<double>;
-  FPBits xbits(x);
-
-  uint64_t x_u = xbits.uintval();
-
-  // x < -1022 or x >= 1024 or log2(1 - 2^-54) < x < log2(1 + 2^-53).
-  if (LIBC_UNLIKELY(x_u > 0xc08ff00000000000 ||
-                    (x_u <= 0xbc971547652b82fe && x_u >= 0x4090000000000000) ||
-                    x_u <= 0x3ca71547652b82fd)) {
-    return set_exceptional(x);
-  }
-
-  // Now -1075 < x <= log2(1 - 2^-54) or log2(1 + 2^-53) < x < 1024
-
-  // Range reduction:
-  // Let x = (hi + mid1 + mid2) + lo
-  // in which:
-  //   hi is an integer
-  //   mid1 * 2^6 is an integer
-  //   mid2 * 2^12 is an integer
-  // then:
-  //   2^(x) = 2^hi * 2^(mid1) * 2^(mid2) * 2^(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.
-  //   - 2^(lo) ~ 1 + a0*lo + a1 * lo^2 + ...
-  //
-  // We compute (hi + mid1 + mid2) together by perform the rounding on x * 2^12.
-  // Since |x| < |-1075)| < 2^11,
-  //   |x * 2^12| < 2^11 * 2^12 < 2^23,
-  // So we can fit the rounded result round(x * 2^12) 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).
-  //
-  // 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.
-  //
-  // One small problem with this approach is that the sum (x*2^12 + 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 + C,
-  // where C = 2^33 + 2^32 + 2^-1, then if
-  //   k = int32_t(lower 51 bits of double(x * 2^12 + C) >> 19),
-  // the reduced argument:
-  //   lo = x - 2^-12 * k is bounded by:
-  //   |lo| <= 2^-13 + 2^-12*2^-19
-  //         = 2^-13 + 2^-31.
-  //
-  // Finally, notice that k only uses the mantissa of x * 2^12, 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 + C) >> 19).
-
-  // Rounding errors <= 2^-31.
-  int k =
-      static_cast<int>(cpp::bit_cast<uint64_t>(x + 0x1.8000'0000'4p21) >> 19);
-  double kd = static_cast<double>(k);
-
-  uint32_t idx1 = (k >> 6) & 0x3f;
-  uint32_t idx2 = k & 0x3f;
-
-  int hi = k >> 12;
-
-  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);
-
-  // |dx| < 2^-13 + 2^-30.
-  double dx = fputil::multiply_add(kd, -0x1.0p-12, x); // exact
-
-  // We use the degree-4 polynomial to approximate 2^(lo):
-  //   2^(lo) ~ 1 + a0 * lo + a1 * lo^2 + a2 * lo^3 + a3 * lo^4 = 1 + lo * P(lo)
-  // So that the errors are bounded...
[truncated]

``````````

</details>


https://github.com/llvm/llvm-project/pull/231041


More information about the libc-commits mailing list