brintos

brintos / llvm-project-archived public Read only

0
0
Text · 14.7 KiB · 7eaa465 Raw
426 lines · c
1//===-- Implementation header for exp2 --------------------------*- C++ -*-===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_EXP2_H10#define LLVM_LIBC_SRC___SUPPORT_MATH_EXP2_H11 12#include "common_constants.h" // Lookup tables EXP2_MID1 and EXP_M2.13#include "exp_constants.h"14#include "exp_utils.h" // ziv_test_denorm.15#include "src/__support/CPP/bit.h"16#include "src/__support/CPP/optional.h"17#include "src/__support/FPUtil/FEnvImpl.h"18#include "src/__support/FPUtil/FPBits.h"19#include "src/__support/FPUtil/PolyEval.h"20#include "src/__support/FPUtil/double_double.h"21#include "src/__support/FPUtil/dyadic_float.h"22#include "src/__support/FPUtil/multiply_add.h"23#include "src/__support/FPUtil/nearest_integer.h"24#include "src/__support/FPUtil/rounding_mode.h"25#include "src/__support/FPUtil/triple_double.h"26#include "src/__support/common.h"27#include "src/__support/integer_literals.h"28#include "src/__support/macros/config.h"29#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY30 31namespace LIBC_NAMESPACE_DECL {32 33namespace math {34 35namespace exp2_internal {36 37using namespace common_constants_internal;38 39using fputil::DoubleDouble;40using fputil::TripleDouble;41using Float128 = typename fputil::DyadicFloat<128>;42 43using LIBC_NAMESPACE::operator""_u128;44 45// Error bounds:46// Errors when using double precision.47#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE48constexpr double ERR_D = 0x1.0p-63;49#else50constexpr double ERR_D = 0x1.8p-63;51#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE52 53#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS54// Errors when using double-double precision.55constexpr double ERR_DD = 0x1.0p-100;56#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS57 58// Polynomial approximations with double precision.  Generated by Sollya with:59// > P = fpminimax((2^x - 1)/x, 3, [|D...|], [-2^-13 - 2^-30, 2^-13 + 2^-30]);60// > P;61// Error bounds:62//   | output - (2^dx - 1) / dx | < 1.5 * 2^-52.63LIBC_INLINE static double poly_approx_d(double dx) {64  // dx^265  double dx2 = dx * dx;66  double c0 =67      fputil::multiply_add(dx, 0x1.ebfbdff82c58ep-3, 0x1.62e42fefa39efp-1);68  double c1 =69      fputil::multiply_add(dx, 0x1.3b2aba7a95a89p-7, 0x1.c6b08e8fc0c0ep-5);70  double p = fputil::multiply_add(dx2, c1, c0);71  return p;72}73 74#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS75// Polynomial approximation with double-double precision.  Generated by Solya76// with:77// > P = fpminimax((2^x - 1)/x, 5, [|DD...|], [-2^-13 - 2^-30, 2^-13 + 2^-30]);78// Error bounds:79//   | output - 2^(dx) | < 2^-10180LIBC_INLINE static constexpr DoubleDouble81poly_approx_dd(const DoubleDouble &dx) {82  // Taylor polynomial.83  constexpr DoubleDouble COEFFS[] = {84      {0, 0x1p0},85      {0x1.abc9e3b39824p-56, 0x1.62e42fefa39efp-1},86      {-0x1.5e43a53e4527bp-57, 0x1.ebfbdff82c58fp-3},87      {-0x1.d37963a9444eep-59, 0x1.c6b08d704a0cp-5},88      {0x1.4eda1a81133dap-62, 0x1.3b2ab6fba4e77p-7},89      {-0x1.c53fd1ba85d14p-64, 0x1.5d87fe7a265a5p-10},90      {0x1.d89250b013eb8p-70, 0x1.430912f86cb8ep-13},91  };92 93  DoubleDouble p = fputil::polyeval(dx, COEFFS[0], COEFFS[1], COEFFS[2],94                                    COEFFS[3], COEFFS[4], COEFFS[5], COEFFS[6]);95  return p;96}97 98// Polynomial approximation with 128-bit precision:99// Return exp(dx) ~ 1 + a0 * dx + a1 * dx^2 + ... + a6 * dx^7100// For |dx| < 2^-13 + 2^-30:101//   | output - exp(dx) | < 2^-126.102LIBC_INLINE static constexpr Float128 poly_approx_f128(const Float128 &dx) {103  constexpr Float128 COEFFS_128[]{104      {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0105      {Sign::POS, -128, 0xb17217f7'd1cf79ab'c9e3b398'03f2f6af_u128},106      {Sign::POS, -128, 0x3d7f7bff'058b1d50'de2d60dd'9c9a1d9f_u128},107      {Sign::POS, -132, 0xe35846b8'2505fc59'9d3b15d9'e7fb6897_u128},108      {Sign::POS, -134, 0x9d955b7d'd273b94e'184462f6'bcd2b9e7_u128},109      {Sign::POS, -137, 0xaec3ff3c'53398883'39ea1bb9'64c51a89_u128},110      {Sign::POS, -138, 0x2861225f'345c396a'842c5341'8fa8ae61_u128},111      {Sign::POS, -144, 0xffe5fe2d'109a319d'7abeb5ab'd5ad2079_u128},112  };113 114  Float128 p = fputil::polyeval(dx, COEFFS_128[0], COEFFS_128[1], COEFFS_128[2],115                                COEFFS_128[3], COEFFS_128[4], COEFFS_128[5],116                                COEFFS_128[6], COEFFS_128[7]);117  return p;118}119 120// Compute 2^(x) using 128-bit precision.121// TODO(lntue): investigate triple-double precision implementation for this122// step.123LIBC_INLINE static constexpr Float128 exp2_f128(double x, int hi, int idx1,124                                                int idx2) {125  Float128 dx = Float128(x);126 127  // TODO: Skip recalculating exp_mid1 and exp_mid2.128  Float128 exp_mid1 =129      fputil::quick_add(Float128(EXP2_MID1[idx1].hi),130                        fputil::quick_add(Float128(EXP2_MID1[idx1].mid),131                                          Float128(EXP2_MID1[idx1].lo)));132 133  Float128 exp_mid2 =134      fputil::quick_add(Float128(EXP2_MID2[idx2].hi),135                        fputil::quick_add(Float128(EXP2_MID2[idx2].mid),136                                          Float128(EXP2_MID2[idx2].lo)));137 138  Float128 exp_mid = fputil::quick_mul(exp_mid1, exp_mid2);139 140  Float128 p = poly_approx_f128(dx);141 142  Float128 r = fputil::quick_mul(exp_mid, p);143 144  r.exponent += hi;145 146  return r;147}148 149// Compute 2^x with double-double precision.150LIBC_INLINE static DoubleDouble151exp2_double_double(double x, const DoubleDouble &exp_mid) {152  DoubleDouble dx({0, x});153 154  // Degree-6 polynomial approximation in double-double precision.155  // | p - 2^x | < 2^-103.156  DoubleDouble p = poly_approx_dd(dx);157 158  // Error bounds: 2^-102.159  DoubleDouble r = fputil::quick_mult(exp_mid, p);160 161  return r;162}163#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS164 165// When output is denormal.166LIBC_INLINE static double exp2_denorm(double x) {167  // Range reduction.168  int k =169      static_cast<int>(cpp::bit_cast<uint64_t>(x + 0x1.8000'0000'4p21) >> 19);170  double kd = static_cast<double>(k);171 172  uint32_t idx1 = (k >> 6) & 0x3f;173  uint32_t idx2 = k & 0x3f;174 175  int hi = k >> 12;176 177  DoubleDouble exp_mid1{EXP2_MID1[idx1].mid, EXP2_MID1[idx1].hi};178  DoubleDouble exp_mid2{EXP2_MID2[idx2].mid, EXP2_MID2[idx2].hi};179  DoubleDouble exp_mid = fputil::quick_mult(exp_mid1, exp_mid2);180 181  // |dx| < 2^-13 + 2^-30.182  double dx = fputil::multiply_add(kd, -0x1.0p-12, x); // exact183 184  double mid_lo = dx * exp_mid.hi;185 186  // Approximate (2^dx - 1)/dx ~ 1 + a0*dx + a1*dx^2 + a2*dx^3 + a3*dx^4.187  double p = poly_approx_d(dx);188 189  double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);190 191#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS192  return ziv_test_denorm</*SKIP_ZIV_TEST=*/true>(hi, exp_mid.hi, lo, ERR_D)193      .value();194#else195  if (auto r = ziv_test_denorm(hi, exp_mid.hi, lo, ERR_D);196      LIBC_LIKELY(r.has_value()))197    return r.value();198 199  // Use double-double200  DoubleDouble r_dd = exp2_double_double(dx, exp_mid);201 202  if (auto r = ziv_test_denorm(hi, r_dd.hi, r_dd.lo, ERR_DD);203      LIBC_LIKELY(r.has_value()))204    return r.value();205 206  // Use 128-bit precision207  Float128 r_f128 = exp2_f128(dx, hi, idx1, idx2);208 209  return static_cast<double>(r_f128);210#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS211}212 213// Check for exceptional cases when:214//  * log2(1 - 2^-54) < x < log2(1 + 2^-53)215//  * x >= 1024216//  * x <= -1022217//  * x is inf or nan218LIBC_INLINE static constexpr double set_exceptional(double x) {219  using FPBits = typename fputil::FPBits<double>;220  FPBits xbits(x);221 222  uint64_t x_u = xbits.uintval();223  uint64_t x_abs = xbits.abs().uintval();224 225  // |x| < log2(1 + 2^-53)226  if (x_abs <= 0x3ca71547652b82fd) {227    // 2^(x) ~ 1 + x/2228    return fputil::multiply_add(x, 0.5, 1.0);229  }230 231  // x <= -1022 || x >= 1024 or inf/nan.232  if (x_u > 0xc08ff00000000000) {233    // x <= -1075 or -inf/nan234    if (x_u >= 0xc090cc0000000000) {235      // exp(-Inf) = 0236      if (xbits.is_inf())237        return 0.0;238 239      // exp(nan) = nan240      if (xbits.is_nan())241        return x;242 243      if (fputil::quick_get_round() == FE_UPWARD)244        return FPBits::min_subnormal().get_val();245      fputil::set_errno_if_required(ERANGE);246      fputil::raise_except_if_required(FE_UNDERFLOW);247      return 0.0;248    }249 250    return exp2_denorm(x);251  }252 253  // x >= 1024 or +inf/nan254  // x is finite255  if (x_u < 0x7ff0'0000'0000'0000ULL) {256    int rounding = fputil::quick_get_round();257    if (rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO)258      return FPBits::max_normal().get_val();259 260    fputil::set_errno_if_required(ERANGE);261    fputil::raise_except_if_required(FE_OVERFLOW);262  }263  // x is +inf or nan264  return x + FPBits::inf().get_val();265}266 267} // namespace exp2_internal268 269LIBC_INLINE static constexpr double exp2(double x) {270  using namespace exp2_internal;271  using FPBits = typename fputil::FPBits<double>;272  FPBits xbits(x);273 274  uint64_t x_u = xbits.uintval();275 276  // x < -1022 or x >= 1024 or log2(1 - 2^-54) < x < log2(1 + 2^-53).277  if (LIBC_UNLIKELY(x_u > 0xc08ff00000000000 ||278                    (x_u <= 0xbc971547652b82fe && x_u >= 0x4090000000000000) ||279                    x_u <= 0x3ca71547652b82fd)) {280    return set_exceptional(x);281  }282 283  // Now -1075 < x <= log2(1 - 2^-54) or log2(1 + 2^-53) < x < 1024284 285  // Range reduction:286  // Let x = (hi + mid1 + mid2) + lo287  // in which:288  //   hi is an integer289  //   mid1 * 2^6 is an integer290  //   mid2 * 2^12 is an integer291  // then:292  //   2^(x) = 2^hi * 2^(mid1) * 2^(mid2) * 2^(lo).293  // With this formula:294  //   - multiplying by 2^hi is exact and cheap, simply by adding the exponent295  //     field.296  //   - 2^(mid1) and 2^(mid2) are stored in 2 x 64-element tables.297  //   - 2^(lo) ~ 1 + a0*lo + a1 * lo^2 + ...298  //299  // We compute (hi + mid1 + mid2) together by perform the rounding on x * 2^12.300  // Since |x| < |-1075)| < 2^11,301  //   |x * 2^12| < 2^11 * 2^12 < 2^23,302  // So we can fit the rounded result round(x * 2^12) in int32_t.303  // Thus, the goal is to be able to use an additional addition and fixed width304  // shift to get an int32_t representing round(x * 2^12).305  //306  // Assuming int32_t using 2-complement representation, since the mantissa part307  // of a double precision is unsigned with the leading bit hidden, if we add an308  // extra constant C = 2^e1 + 2^e2 with e1 > e2 >= 2^25 to the product, the309  // part that are < 2^e2 in resulted mantissa of (x*2^12*L2E + C) can be310  // considered as a proper 2-complement representations of x*2^12.311  //312  // One small problem with this approach is that the sum (x*2^12 + C) in313  // double precision is rounded to the least significant bit of the dorminant314  // factor C.  In order to minimize the rounding errors from this addition, we315  // want to minimize e1.  Another constraint that we want is that after316  // shifting the mantissa so that the least significant bit of int32_t317  // corresponds to the unit bit of (x*2^12*L2E), the sign is correct without318  // any adjustment.  So combining these 2 requirements, we can choose319  //   C = 2^33 + 2^32, so that the sign bit corresponds to 2^31 bit, and hence320  // after right shifting the mantissa, the resulting int32_t has correct sign.321  // With this choice of C, the number of mantissa bits we need to shift to the322  // right is: 52 - 33 = 19.323  //324  // Moreover, since the integer right shifts are equivalent to rounding down,325  // we can add an extra 0.5 so that it will become round-to-nearest, tie-to-326  // +infinity.  So in particular, we can compute:327  //   hmm = x * 2^12 + C,328  // where C = 2^33 + 2^32 + 2^-1, then if329  //   k = int32_t(lower 51 bits of double(x * 2^12 + C) >> 19),330  // the reduced argument:331  //   lo = x - 2^-12 * k is bounded by:332  //   |lo| <= 2^-13 + 2^-12*2^-19333  //         = 2^-13 + 2^-31.334  //335  // Finally, notice that k only uses the mantissa of x * 2^12, so the336  // exponent 2^12 is not needed.  So we can simply define337  //   C = 2^(33 - 12) + 2^(32 - 12) + 2^(-13 - 12), and338  //   k = int32_t(lower 51 bits of double(x + C) >> 19).339 340  // Rounding errors <= 2^-31.341  int k =342      static_cast<int>(cpp::bit_cast<uint64_t>(x + 0x1.8000'0000'4p21) >> 19);343  double kd = static_cast<double>(k);344 345  uint32_t idx1 = (k >> 6) & 0x3f;346  uint32_t idx2 = k & 0x3f;347 348  int hi = k >> 12;349 350  DoubleDouble exp_mid1{EXP2_MID1[idx1].mid, EXP2_MID1[idx1].hi};351  DoubleDouble exp_mid2{EXP2_MID2[idx2].mid, EXP2_MID2[idx2].hi};352  DoubleDouble exp_mid = fputil::quick_mult(exp_mid1, exp_mid2);353 354  // |dx| < 2^-13 + 2^-30.355  double dx = fputil::multiply_add(kd, -0x1.0p-12, x); // exact356 357  // We use the degree-4 polynomial to approximate 2^(lo):358  //   2^(lo) ~ 1 + a0 * lo + a1 * lo^2 + a2 * lo^3 + a3 * lo^4 = 1 + lo * P(lo)359  // So that the errors are bounded by:360  //   |P(lo) - (2^lo - 1)/lo| < |lo|^4 / 64 < 2^(-13 * 4) / 64 = 2^-58361  // Let P_ be an evaluation of P where all intermediate computations are in362  // double precision.  Using either Horner's or Estrin's schemes, the evaluated363  // errors can be bounded by:364  //      |P_(lo) - P(lo)| < 2^-51365  //   => |lo * P_(lo) - (2^lo - 1) | < 2^-64366  //   => 2^(mid1 + mid2) * |lo * P_(lo) - expm1(lo)| < 2^-63.367  // Since we approximate368  //   2^(mid1 + mid2) ~ exp_mid.hi + exp_mid.lo,369  // We use the expression:370  //    (exp_mid.hi + exp_mid.lo) * (1 + dx * P_(dx)) ~371  //  ~ exp_mid.hi + (exp_mid.hi * dx * P_(dx) + exp_mid.lo)372  // with errors bounded by 2^-63.373 374  double mid_lo = dx * exp_mid.hi;375 376  // Approximate (2^dx - 1)/dx ~ 1 + a0*dx + a1*dx^2 + a2*dx^3 + a3*dx^4.377  double p = poly_approx_d(dx);378 379  double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);380 381#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS382  // To multiply by 2^hi, a fast way is to simply add hi to the exponent383  // field.384  int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;385  double r =386      cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(exp_mid.hi + lo));387  return r;388#else389  double upper = exp_mid.hi + (lo + ERR_D);390  double lower = exp_mid.hi + (lo - ERR_D);391 392  if (LIBC_LIKELY(upper == lower)) {393    // To multiply by 2^hi, a fast way is to simply add hi to the exponent394    // field.395    int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;396    double r = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper));397    return r;398  }399 400  // Use double-double401  DoubleDouble r_dd = exp2_double_double(dx, exp_mid);402 403  double upper_dd = r_dd.hi + (r_dd.lo + ERR_DD);404  double lower_dd = r_dd.hi + (r_dd.lo - ERR_DD);405 406  if (LIBC_LIKELY(upper_dd == lower_dd)) {407    // To multiply by 2^hi, a fast way is to simply add hi to the exponent408    // field.409    int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;410    double r = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper_dd));411    return r;412  }413 414  // Use 128-bit precision415  Float128 r_f128 = exp2_f128(dx, hi, idx1, idx2);416 417  return static_cast<double>(r_f128);418#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS419}420 421} // namespace math422 423} // namespace LIBC_NAMESPACE_DECL424 425#endif // LLVM_LIBC_SRC___SUPPORT_MATH_EXP2_H426