1//===-- Double-precision 2^x function -------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "src/math/exp2.h"
10#include "common_constants.h" // Lookup tables EXP2_MID1 and EXP_M2.
11#include "explogxf.h" // ziv_test_denorm.
12#include "src/__support/CPP/bit.h"
13#include "src/__support/CPP/optional.h"
14#include "src/__support/FPUtil/FEnvImpl.h"
15#include "src/__support/FPUtil/FPBits.h"
16#include "src/__support/FPUtil/PolyEval.h"
17#include "src/__support/FPUtil/double_double.h"
18#include "src/__support/FPUtil/dyadic_float.h"
19#include "src/__support/FPUtil/multiply_add.h"
20#include "src/__support/FPUtil/nearest_integer.h"
21#include "src/__support/FPUtil/rounding_mode.h"
22#include "src/__support/FPUtil/triple_double.h"
23#include "src/__support/common.h"
24#include "src/__support/integer_literals.h"
25#include "src/__support/macros/config.h"
26#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
27
28namespace LIBC_NAMESPACE_DECL {
29
30using fputil::DoubleDouble;
31using fputil::TripleDouble;
32using Float128 = typename fputil::DyadicFloat<128>;
33
34using LIBC_NAMESPACE::operator""_u128;
35
36// Error bounds:
37// Errors when using double precision.
38#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE
39constexpr double ERR_D = 0x1.0p-63;
40#else
41constexpr double ERR_D = 0x1.8p-63;
42#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE
43
44#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
45// Errors when using double-double precision.
46constexpr double ERR_DD = 0x1.0p-100;
47#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
48
49namespace {
50
51// Polynomial approximations with double precision. Generated by Sollya with:
52// > P = fpminimax((2^x - 1)/x, 3, [|D...|], [-2^-13 - 2^-30, 2^-13 + 2^-30]);
53// > P;
54// Error bounds:
55// | output - (2^dx - 1) / dx | < 1.5 * 2^-52.
56LIBC_INLINE double poly_approx_d(double dx) {
57 // dx^2
58 double dx2 = dx * dx;
59 double c0 =
60 fputil::multiply_add(dx, 0x1.ebfbdff82c58ep-3, 0x1.62e42fefa39efp-1);
61 double c1 =
62 fputil::multiply_add(dx, 0x1.3b2aba7a95a89p-7, 0x1.c6b08e8fc0c0ep-5);
63 double p = fputil::multiply_add(dx2, c1, c0);
64 return p;
65}
66
67#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
68// Polynomial approximation with double-double precision. Generated by Solya
69// with:
70// > P = fpminimax((2^x - 1)/x, 5, [|DD...|], [-2^-13 - 2^-30, 2^-13 + 2^-30]);
71// Error bounds:
72// | output - 2^(dx) | < 2^-101
73DoubleDouble poly_approx_dd(const DoubleDouble &dx) {
74 // Taylor polynomial.
75 constexpr DoubleDouble COEFFS[] = {
76 {0, 0x1p0},
77 {0x1.abc9e3b39824p-56, 0x1.62e42fefa39efp-1},
78 {-0x1.5e43a53e4527bp-57, 0x1.ebfbdff82c58fp-3},
79 {-0x1.d37963a9444eep-59, 0x1.c6b08d704a0cp-5},
80 {0x1.4eda1a81133dap-62, 0x1.3b2ab6fba4e77p-7},
81 {-0x1.c53fd1ba85d14p-64, 0x1.5d87fe7a265a5p-10},
82 {0x1.d89250b013eb8p-70, 0x1.430912f86cb8ep-13},
83 };
84
85 DoubleDouble p = fputil::polyeval(dx, COEFFS[0], COEFFS[1], COEFFS[2],
86 COEFFS[3], COEFFS[4], COEFFS[5], COEFFS[6]);
87 return p;
88}
89
90// Polynomial approximation with 128-bit precision:
91// Return exp(dx) ~ 1 + a0 * dx + a1 * dx^2 + ... + a6 * dx^7
92// For |dx| < 2^-13 + 2^-30:
93// | output - exp(dx) | < 2^-126.
94Float128 poly_approx_f128(const Float128 &dx) {
95 constexpr Float128 COEFFS_128[]{
96 {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0
97 {Sign::POS, -128, 0xb17217f7'd1cf79ab'c9e3b398'03f2f6af_u128},
98 {Sign::POS, -128, 0x3d7f7bff'058b1d50'de2d60dd'9c9a1d9f_u128},
99 {Sign::POS, -132, 0xe35846b8'2505fc59'9d3b15d9'e7fb6897_u128},
100 {Sign::POS, -134, 0x9d955b7d'd273b94e'184462f6'bcd2b9e7_u128},
101 {Sign::POS, -137, 0xaec3ff3c'53398883'39ea1bb9'64c51a89_u128},
102 {Sign::POS, -138, 0x2861225f'345c396a'842c5341'8fa8ae61_u128},
103 {Sign::POS, -144, 0xffe5fe2d'109a319d'7abeb5ab'd5ad2079_u128},
104 };
105
106 Float128 p = fputil::polyeval(dx, COEFFS_128[0], COEFFS_128[1], COEFFS_128[2],
107 COEFFS_128[3], COEFFS_128[4], COEFFS_128[5],
108 COEFFS_128[6], COEFFS_128[7]);
109 return p;
110}
111
112// Compute 2^(x) using 128-bit precision.
113// TODO(lntue): investigate triple-double precision implementation for this
114// step.
115Float128 exp2_f128(double x, int hi, int idx1, int idx2) {
116 Float128 dx = Float128(x);
117
118 // TODO: Skip recalculating exp_mid1 and exp_mid2.
119 Float128 exp_mid1 =
120 fputil::quick_add(Float128(EXP2_MID1[idx1].hi),
121 fputil::quick_add(Float128(EXP2_MID1[idx1].mid),
122 Float128(EXP2_MID1[idx1].lo)));
123
124 Float128 exp_mid2 =
125 fputil::quick_add(Float128(EXP2_MID2[idx2].hi),
126 fputil::quick_add(Float128(EXP2_MID2[idx2].mid),
127 Float128(EXP2_MID2[idx2].lo)));
128
129 Float128 exp_mid = fputil::quick_mul(exp_mid1, exp_mid2);
130
131 Float128 p = poly_approx_f128(dx);
132
133 Float128 r = fputil::quick_mul(exp_mid, p);
134
135 r.exponent += hi;
136
137 return r;
138}
139
140// Compute 2^x with double-double precision.
141DoubleDouble exp2_double_double(double x, const DoubleDouble &exp_mid) {
142 DoubleDouble dx({0, x});
143
144 // Degree-6 polynomial approximation in double-double precision.
145 // | p - 2^x | < 2^-103.
146 DoubleDouble p = poly_approx_dd(dx);
147
148 // Error bounds: 2^-102.
149 DoubleDouble r = fputil::quick_mult(exp_mid, p);
150
151 return r;
152}
153#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
154
155// When output is denormal.
156double exp2_denorm(double x) {
157 // Range reduction.
158 int k =
159 static_cast<int>(cpp::bit_cast<uint64_t>(x + 0x1.8000'0000'4p21) >> 19);
160 double kd = static_cast<double>(k);
161
162 uint32_t idx1 = (k >> 6) & 0x3f;
163 uint32_t idx2 = k & 0x3f;
164
165 int hi = k >> 12;
166
167 DoubleDouble exp_mid1{EXP2_MID1[idx1].mid, EXP2_MID1[idx1].hi};
168 DoubleDouble exp_mid2{EXP2_MID2[idx2].mid, EXP2_MID2[idx2].hi};
169 DoubleDouble exp_mid = fputil::quick_mult(exp_mid1, exp_mid2);
170
171 // |dx| < 2^-13 + 2^-30.
172 double dx = fputil::multiply_add(kd, -0x1.0p-12, x); // exact
173
174 double mid_lo = dx * exp_mid.hi;
175
176 // Approximate (2^dx - 1)/dx ~ 1 + a0*dx + a1*dx^2 + a2*dx^3 + a3*dx^4.
177 double p = poly_approx_d(dx);
178
179 double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);
180
181#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
182 return ziv_test_denorm</*SKIP_ZIV_TEST=*/true>(hi, exp_mid.hi, lo, ERR_D)
183 .value();
184#else
185 if (auto r = ziv_test_denorm(hi, exp_mid.hi, lo, ERR_D);
186 LIBC_LIKELY(r.has_value()))
187 return r.value();
188
189 // Use double-double
190 DoubleDouble r_dd = exp2_double_double(dx, exp_mid);
191
192 if (auto r = ziv_test_denorm(hi, r_dd.hi, r_dd.lo, ERR_DD);
193 LIBC_LIKELY(r.has_value()))
194 return r.value();
195
196 // Use 128-bit precision
197 Float128 r_f128 = exp2_f128(dx, hi, idx1, idx2);
198
199 return static_cast<double>(r_f128);
200#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
201}
202
203// Check for exceptional cases when:
204// * log2(1 - 2^-54) < x < log2(1 + 2^-53)
205// * x >= 1024
206// * x <= -1022
207// * x is inf or nan
208double set_exceptional(double x) {
209 using FPBits = typename fputil::FPBits<double>;
210 FPBits xbits(x);
211
212 uint64_t x_u = xbits.uintval();
213 uint64_t x_abs = xbits.abs().uintval();
214
215 // |x| < log2(1 + 2^-53)
216 if (x_abs <= 0x3ca71547652b82fd) {
217 // 2^(x) ~ 1 + x/2
218 return fputil::multiply_add(x, 0.5, 1.0);
219 }
220
221 // x <= -1022 || x >= 1024 or inf/nan.
222 if (x_u > 0xc08ff00000000000) {
223 // x <= -1075 or -inf/nan
224 if (x_u >= 0xc090cc0000000000) {
225 // exp(-Inf) = 0
226 if (xbits.is_inf())
227 return 0.0;
228
229 // exp(nan) = nan
230 if (xbits.is_nan())
231 return x;
232
233 if (fputil::quick_get_round() == FE_UPWARD)
234 return FPBits::min_subnormal().get_val();
235 fputil::set_errno_if_required(ERANGE);
236 fputil::raise_except_if_required(FE_UNDERFLOW);
237 return 0.0;
238 }
239
240 return exp2_denorm(x);
241 }
242
243 // x >= 1024 or +inf/nan
244 // x is finite
245 if (x_u < 0x7ff0'0000'0000'0000ULL) {
246 int rounding = fputil::quick_get_round();
247 if (rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO)
248 return FPBits::max_normal().get_val();
249
250 fputil::set_errno_if_required(ERANGE);
251 fputil::raise_except_if_required(FE_OVERFLOW);
252 }
253 // x is +inf or nan
254 return x + FPBits::inf().get_val();
255}
256
257} // namespace
258
259LLVM_LIBC_FUNCTION(double, exp2, (double x)) {
260 using FPBits = typename fputil::FPBits<double>;
261 FPBits xbits(x);
262
263 uint64_t x_u = xbits.uintval();
264
265 // x < -1022 or x >= 1024 or log2(1 - 2^-54) < x < log2(1 + 2^-53).
266 if (LIBC_UNLIKELY(x_u > 0xc08ff00000000000 ||
267 (x_u <= 0xbc971547652b82fe && x_u >= 0x4090000000000000) ||
268 x_u <= 0x3ca71547652b82fd)) {
269 return set_exceptional(x);
270 }
271
272 // Now -1075 < x <= log2(1 - 2^-54) or log2(1 + 2^-53) < x < 1024
273
274 // Range reduction:
275 // Let x = (hi + mid1 + mid2) + lo
276 // in which:
277 // hi is an integer
278 // mid1 * 2^6 is an integer
279 // mid2 * 2^12 is an integer
280 // then:
281 // 2^(x) = 2^hi * 2^(mid1) * 2^(mid2) * 2^(lo).
282 // With this formula:
283 // - multiplying by 2^hi is exact and cheap, simply by adding the exponent
284 // field.
285 // - 2^(mid1) and 2^(mid2) are stored in 2 x 64-element tables.
286 // - 2^(lo) ~ 1 + a0*lo + a1 * lo^2 + ...
287 //
288 // We compute (hi + mid1 + mid2) together by perform the rounding on x * 2^12.
289 // Since |x| < |-1075)| < 2^11,
290 // |x * 2^12| < 2^11 * 2^12 < 2^23,
291 // So we can fit the rounded result round(x * 2^12) in int32_t.
292 // Thus, the goal is to be able to use an additional addition and fixed width
293 // shift to get an int32_t representing round(x * 2^12).
294 //
295 // Assuming int32_t using 2-complement representation, since the mantissa part
296 // of a double precision is unsigned with the leading bit hidden, if we add an
297 // extra constant C = 2^e1 + 2^e2 with e1 > e2 >= 2^25 to the product, the
298 // part that are < 2^e2 in resulted mantissa of (x*2^12*L2E + C) can be
299 // considered as a proper 2-complement representations of x*2^12.
300 //
301 // One small problem with this approach is that the sum (x*2^12 + C) in
302 // double precision is rounded to the least significant bit of the dorminant
303 // factor C. In order to minimize the rounding errors from this addition, we
304 // want to minimize e1. Another constraint that we want is that after
305 // shifting the mantissa so that the least significant bit of int32_t
306 // corresponds to the unit bit of (x*2^12*L2E), the sign is correct without
307 // any adjustment. So combining these 2 requirements, we can choose
308 // C = 2^33 + 2^32, so that the sign bit corresponds to 2^31 bit, and hence
309 // after right shifting the mantissa, the resulting int32_t has correct sign.
310 // With this choice of C, the number of mantissa bits we need to shift to the
311 // right is: 52 - 33 = 19.
312 //
313 // Moreover, since the integer right shifts are equivalent to rounding down,
314 // we can add an extra 0.5 so that it will become round-to-nearest, tie-to-
315 // +infinity. So in particular, we can compute:
316 // hmm = x * 2^12 + C,
317 // where C = 2^33 + 2^32 + 2^-1, then if
318 // k = int32_t(lower 51 bits of double(x * 2^12 + C) >> 19),
319 // the reduced argument:
320 // lo = x - 2^-12 * k is bounded by:
321 // |lo| <= 2^-13 + 2^-12*2^-19
322 // = 2^-13 + 2^-31.
323 //
324 // Finally, notice that k only uses the mantissa of x * 2^12, so the
325 // exponent 2^12 is not needed. So we can simply define
326 // C = 2^(33 - 12) + 2^(32 - 12) + 2^(-13 - 12), and
327 // k = int32_t(lower 51 bits of double(x + C) >> 19).
328
329 // Rounding errors <= 2^-31.
330 int k =
331 static_cast<int>(cpp::bit_cast<uint64_t>(x + 0x1.8000'0000'4p21) >> 19);
332 double kd = static_cast<double>(k);
333
334 uint32_t idx1 = (k >> 6) & 0x3f;
335 uint32_t idx2 = k & 0x3f;
336
337 int hi = k >> 12;
338
339 DoubleDouble exp_mid1{EXP2_MID1[idx1].mid, EXP2_MID1[idx1].hi};
340 DoubleDouble exp_mid2{EXP2_MID2[idx2].mid, EXP2_MID2[idx2].hi};
341 DoubleDouble exp_mid = fputil::quick_mult(exp_mid1, exp_mid2);
342
343 // |dx| < 2^-13 + 2^-30.
344 double dx = fputil::multiply_add(kd, -0x1.0p-12, x); // exact
345
346 // We use the degree-4 polynomial to approximate 2^(lo):
347 // 2^(lo) ~ 1 + a0 * lo + a1 * lo^2 + a2 * lo^3 + a3 * lo^4 = 1 + lo * P(lo)
348 // So that the errors are bounded by:
349 // |P(lo) - (2^lo - 1)/lo| < |lo|^4 / 64 < 2^(-13 * 4) / 64 = 2^-58
350 // Let P_ be an evaluation of P where all intermediate computations are in
351 // double precision. Using either Horner's or Estrin's schemes, the evaluated
352 // errors can be bounded by:
353 // |P_(lo) - P(lo)| < 2^-51
354 // => |lo * P_(lo) - (2^lo - 1) | < 2^-64
355 // => 2^(mid1 + mid2) * |lo * P_(lo) - expm1(lo)| < 2^-63.
356 // Since we approximate
357 // 2^(mid1 + mid2) ~ exp_mid.hi + exp_mid.lo,
358 // We use the expression:
359 // (exp_mid.hi + exp_mid.lo) * (1 + dx * P_(dx)) ~
360 // ~ exp_mid.hi + (exp_mid.hi * dx * P_(dx) + exp_mid.lo)
361 // with errors bounded by 2^-63.
362
363 double mid_lo = dx * exp_mid.hi;
364
365 // Approximate (2^dx - 1)/dx ~ 1 + a0*dx + a1*dx^2 + a2*dx^3 + a3*dx^4.
366 double p = poly_approx_d(dx);
367
368 double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);
369
370#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
371 // To multiply by 2^hi, a fast way is to simply add hi to the exponent
372 // field.
373 int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;
374 double r =
375 cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(exp_mid.hi + lo));
376 return r;
377#else
378 double upper = exp_mid.hi + (lo + ERR_D);
379 double lower = exp_mid.hi + (lo - ERR_D);
380
381 if (LIBC_LIKELY(upper == lower)) {
382 // To multiply by 2^hi, a fast way is to simply add hi to the exponent
383 // field.
384 int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;
385 double r = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper));
386 return r;
387 }
388
389 // Use double-double
390 DoubleDouble r_dd = exp2_double_double(dx, exp_mid);
391
392 double upper_dd = r_dd.hi + (r_dd.lo + ERR_DD);
393 double lower_dd = r_dd.hi + (r_dd.lo - ERR_DD);
394
395 if (LIBC_LIKELY(upper_dd == lower_dd)) {
396 // To multiply by 2^hi, a fast way is to simply add hi to the exponent
397 // field.
398 int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;
399 double r = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper_dd));
400 return r;
401 }
402
403 // Use 128-bit precision
404 Float128 r_f128 = exp2_f128(dx, hi, idx1, idx2);
405
406 return static_cast<double>(r_f128);
407#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
408}
409
410} // namespace LIBC_NAMESPACE_DECL
411

source code of libc/src/math/generic/exp2.cpp