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 using FPBits = fputil::FPBits<double>;
194
195 if (auto r = ziv_test_denorm(hi, mid: exp_mid.hi, lo, err: ERR_D);
196 LIBC_LIKELY(r.has_value())) {
197 double res = r.value();
198 if (LIBC_UNLIKELY(FPBits(res).is_normal()))
199 return res;
200 if (x != fputil::nearest_integer(x)) {
201 fputil::set_errno_if_required(ERANGE);
202 fputil::raise_underflow_except_if_required<double>();
203 }
204 return res;
205 }
206
207 // Use double-double
208 DoubleDouble r_dd = exp2_double_double(x: dx, exp_mid);
209
210 if (auto r = ziv_test_denorm(hi, mid: r_dd.hi, lo: r_dd.lo, err: ERR_DD);
211 LIBC_LIKELY(r.has_value())) {
212 double res = r.value();
213 if (LIBC_UNLIKELY(FPBits(res).is_normal()))
214 return res;
215 if (x != fputil::nearest_integer(x)) {
216 fputil::set_errno_if_required(ERANGE);
217 fputil::raise_underflow_except_if_required<double>();
218 }
219 return res;
220 }
221
222 // Use 128-bit precision
223 DFloat128 r_f128 = exp2_f128(x: dx, hi, idx1, idx2);
224
225 return static_cast<double>(r_f128);
226#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
227}
228
229// Check for exceptional cases when:
230// * log2(1 - 2^-54) < x < log2(1 + 2^-53)
231// * x >= 1024
232// * x <= -1022
233// * x is inf or nan
234LIBC_INLINE double set_exceptional(double x) {
235 using FPBits = typename fputil::FPBits<double>;
236 FPBits xbits(x);
237
238 uint64_t x_u = xbits.uintval();
239 uint64_t x_abs = xbits.abs().uintval();
240
241 // |x| < log2(1 + 2^-53)
242 if (x_abs <= 0x3ca71547652b82fd) {
243 // 2^(x) ~ 1 + x/2
244 return fputil::multiply_add(x, y: 0.5, z: 1.0);
245 }
246
247 // x <= -1022 || x >= 1024 or inf/nan.
248 if (x_u > 0xc08ff00000000000) {
249 // x <= -1075 or -inf/nan
250 if (x_u >= 0xc090cc0000000000) {
251 // exp(-Inf) = 0
252 if (xbits.is_inf())
253 return 0.0;
254
255 // exp(nan) = nan
256 if (xbits.is_nan())
257 return x + FPBits::inf().get_val();
258
259 fputil::set_errno_if_required(ERANGE);
260 fputil::raise_underflow_except_if_required<double>();
261#ifndef LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
262 if (fputil::quick_get_round() == FE_UPWARD)
263 return FPBits::min_subnormal().get_val();
264#endif
265 return 0.0;
266 }
267
268 return exp2_denorm(x);
269 }
270
271 // x >= 1024 or +inf/nan
272 // x is finite
273 if (x_u < 0x7ff0'0000'0000'0000ULL) {
274 fputil::set_errno_if_required(ERANGE);
275 fputil::raise_overflow_except_if_required<double>();
276#ifndef LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY
277 int rounding = fputil::quick_get_round();
278 if (rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO)
279 return FPBits::max_normal().get_val();
280#endif
281 return FPBits::inf().get_val();
282 }
283 // x is +inf or nan
284 return x + FPBits::inf().get_val();
285}
286
287} // namespace exp2_internal
288
289LIBC_INLINE double exp2(double x) {
290 using namespace exp2_internal;
291 using FPBits = typename fputil::FPBits<double>;
292 FPBits xbits(x);
293
294 uint64_t x_u = xbits.uintval();
295
296 // x < -1022 or x >= 1024 or log2(1 - 2^-54) < x < log2(1 + 2^-53).
297 if (LIBC_UNLIKELY(x_u > 0xc08ff00000000000 ||
298 (x_u <= 0xbc971547652b82fe && x_u >= 0x4090000000000000) ||
299 x_u <= 0x3ca71547652b82fd)) {
300 return set_exceptional(x);
301 }
302
303 // Now -1075 < x <= log2(1 - 2^-54) or log2(1 + 2^-53) < x < 1024
304
305 // Range reduction:
306 // Let x = (hi + mid1 + mid2) + lo
307 // in which:
308 // hi is an integer
309 // mid1 * 2^6 is an integer
310 // mid2 * 2^12 is an integer
311 // then:
312 // 2^(x) = 2^hi * 2^(mid1) * 2^(mid2) * 2^(lo).
313 // With this formula:
314 // - multiplying by 2^hi is exact and cheap, simply by adding the exponent
315 // field.
316 // - 2^(mid1) and 2^(mid2) are stored in 2 x 64-element tables.
317 // - 2^(lo) ~ 1 + a0*lo + a1 * lo^2 + ...
318 //
319 // We compute (hi + mid1 + mid2) together by perform the rounding on x * 2^12.
320 // Since |x| < |-1075)| < 2^11,
321 // |x * 2^12| < 2^11 * 2^12 < 2^23,
322 // So we can fit the rounded result round(x * 2^12) in int32_t.
323 // Thus, the goal is to be able to use an additional addition and fixed width
324 // shift to get an int32_t representing round(x * 2^12).
325 //
326 // Assuming int32_t using 2-complement representation, since the mantissa part
327 // of a double precision is unsigned with the leading bit hidden, if we add an
328 // extra constant C = 2^e1 + 2^e2 with e1 > e2 >= 2^25 to the product, the
329 // part that are < 2^e2 in resulted mantissa of (x*2^12*L2E + C) can be
330 // considered as a proper 2-complement representations of x*2^12.
331 //
332 // One small problem with this approach is that the sum (x*2^12 + C) in
333 // double precision is rounded to the least significant bit of the dorminant
334 // factor C. In order to minimize the rounding errors from this addition, we
335 // want to minimize e1. Another constraint that we want is that after
336 // shifting the mantissa so that the least significant bit of int32_t
337 // corresponds to the unit bit of (x*2^12*L2E), the sign is correct without
338 // any adjustment. So combining these 2 requirements, we can choose
339 // C = 2^33 + 2^32, so that the sign bit corresponds to 2^31 bit, and hence
340 // after right shifting the mantissa, the resulting int32_t has correct sign.
341 // With this choice of C, the number of mantissa bits we need to shift to the
342 // right is: 52 - 33 = 19.
343 //
344 // Moreover, since the integer right shifts are equivalent to rounding down,
345 // we can add an extra 0.5 so that it will become round-to-nearest, tie-to-
346 // +infinity. So in particular, we can compute:
347 // hmm = x * 2^12 + C,
348 // where C = 2^33 + 2^32 + 2^-1, then if
349 // k = int32_t(lower 51 bits of double(x * 2^12 + C) >> 19),
350 // the reduced argument:
351 // lo = x - 2^-12 * k is bounded by:
352 // |lo| <= 2^-13 + 2^-12*2^-19
353 // = 2^-13 + 2^-31.
354 //
355 // Finally, notice that k only uses the mantissa of x * 2^12, so the
356 // exponent 2^12 is not needed. So we can simply define
357 // C = 2^(33 - 12) + 2^(32 - 12) + 2^(-13 - 12), and
358 // k = int32_t(lower 51 bits of double(x + C) >> 19).
359
360 // Rounding errors <= 2^-31.
361 int k =
362 static_cast<int>(cpp::bit_cast<uint64_t>(from: x + 0x1.8000'0000'4p21) >> 19);
363 double kd = static_cast<double>(k);
364
365 uint32_t idx1 = (k >> 6) & 0x3f;
366 uint32_t idx2 = k & 0x3f;
367
368 int hi = k >> 12;
369
370 DoubleDouble exp_mid1{.lo: EXP2_MID1[idx1].mid, .hi: EXP2_MID1[idx1].hi};
371 DoubleDouble exp_mid2{.lo: EXP2_MID2[idx2].mid, .hi: EXP2_MID2[idx2].hi};
372 DoubleDouble exp_mid = fputil::quick_mult(a: exp_mid1, b: exp_mid2);
373
374 // |dx| < 2^-13 + 2^-30.
375 double dx = fputil::multiply_add(x: kd, y: -0x1.0p-12, z: x); // exact
376
377 // We use the degree-4 polynomial to approximate 2^(lo):
378 // 2^(lo) ~ 1 + a0 * lo + a1 * lo^2 + a2 * lo^3 + a3 * lo^4 = 1 + lo * P(lo)
379 // So that the errors are bounded by:
380 // |P(lo) - (2^lo - 1)/lo| < |lo|^4 / 64 < 2^(-13 * 4) / 64 = 2^-58
381 // Let P_ be an evaluation of P where all intermediate computations are in
382 // double precision. Using either Horner's or Estrin's schemes, the evaluated
383 // errors can be bounded by:
384 // |P_(lo) - P(lo)| < 2^-51
385 // => |lo * P_(lo) - (2^lo - 1) | < 2^-64
386 // => 2^(mid1 + mid2) * |lo * P_(lo) - expm1(lo)| < 2^-63.
387 // Since we approximate
388 // 2^(mid1 + mid2) ~ exp_mid.hi + exp_mid.lo,
389 // We use the expression:
390 // (exp_mid.hi + exp_mid.lo) * (1 + dx * P_(dx)) ~
391 // ~ exp_mid.hi + (exp_mid.hi * dx * P_(dx) + exp_mid.lo)
392 // with errors bounded by 2^-63.
393
394 double mid_lo = dx * exp_mid.hi;
395
396 // Approximate (2^dx - 1)/dx ~ 1 + a0*dx + a1*dx^2 + a2*dx^3 + a3*dx^4.
397 double p = poly_approx_d(dx);
398
399 double lo = fputil::multiply_add(x: p, y: mid_lo, z: exp_mid.lo);
400
401#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
402 // To multiply by 2^hi, a fast way is to simply add hi to the exponent
403 // field.
404 int64_t exp_hi = static_cast<int64_t>(hi) * (1LL << FPBits::FRACTION_LEN);
405 double r =
406 cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(exp_mid.hi + lo));
407 return r;
408#else
409 double upper = exp_mid.hi + (lo + ERR_D);
410 double lower = exp_mid.hi + (lo - ERR_D);
411
412 if (LIBC_LIKELY(upper == lower)) {
413 // To multiply by 2^hi, a fast way is to simply add hi to the exponent
414 // field.
415 int64_t exp_hi = static_cast<int64_t>(hi) * (1LL << FPBits::FRACTION_LEN);
416 double r = cpp::bit_cast<double>(from: exp_hi + cpp::bit_cast<int64_t>(from: upper));
417 return r;
418 }
419
420 // Use double-double
421 DoubleDouble r_dd = exp2_double_double(x: dx, exp_mid);
422
423 double upper_dd = r_dd.hi + (r_dd.lo + ERR_DD);
424 double lower_dd = r_dd.hi + (r_dd.lo - ERR_DD);
425
426 if (LIBC_LIKELY(upper_dd == lower_dd)) {
427 // To multiply by 2^hi, a fast way is to simply add hi to the exponent
428 // field.
429 int64_t exp_hi = static_cast<int64_t>(hi) * (1LL << FPBits::FRACTION_LEN);
430 double r = cpp::bit_cast<double>(from: exp_hi + cpp::bit_cast<int64_t>(from: upper_dd));
431 return r;
432 }
433
434 // Use 128-bit precision
435 DFloat128 r_f128 = exp2_f128(x: dx, hi, idx1, idx2);
436
437 return static_cast<double>(r_f128);
438#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS
439}
440
441} // namespace math
442
443} // namespace LIBC_NAMESPACE_DECL
444
445#endif // LLVM_LIBC_SRC___SUPPORT_MATH_EXP2_H
446