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