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