• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Double-precision e^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/exp.h"
10 #include "common_constants.h" // Lookup tables EXP_M1 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 // log2(e)
38 constexpr double LOG2_E = 0x1.71547652b82fep+0;
39 
40 // Error bounds:
41 // Errors when using double precision.
42 constexpr double ERR_D = 0x1.8p-63;
43 // Errors when using double-double precision.
44 constexpr double ERR_DD = 0x1.0p-99;
45 
46 // -2^-12 * log(2)
47 // > a = -2^-12 * log(2);
48 // > b = round(a, 30, RN);
49 // > c = round(a - b, 30, RN);
50 // > d = round(a - b - c, D, RN);
51 // Errors < 1.5 * 2^-133
52 constexpr double MLOG_2_EXP2_M12_HI = -0x1.62e42ffp-13;
53 constexpr double MLOG_2_EXP2_M12_MID = 0x1.718432a1b0e26p-47;
54 constexpr double MLOG_2_EXP2_M12_MID_30 = 0x1.718432ap-47;
55 constexpr double MLOG_2_EXP2_M12_LO = 0x1.b0e2633fe0685p-79;
56 
57 namespace {
58 
59 // Polynomial approximations with double precision:
60 // Return expm1(dx) / x ~ 1 + dx / 2 + dx^2 / 6 + dx^3 / 24.
61 // For |dx| < 2^-13 + 2^-30:
62 //   | output - expm1(dx) / dx | < 2^-51.
poly_approx_d(double dx)63 LIBC_INLINE double poly_approx_d(double dx) {
64   // dx^2
65   double dx2 = dx * dx;
66   // c0 = 1 + dx / 2
67   double c0 = fputil::multiply_add(dx, 0.5, 1.0);
68   // c1 = 1/6 + dx / 24
69   double c1 =
70       fputil::multiply_add(dx, 0x1.5555555555555p-5, 0x1.5555555555555p-3);
71   // p = dx^2 * c1 + c0 = 1 + dx / 2 + dx^2 / 6 + dx^3 / 24
72   double p = fputil::multiply_add(dx2, c1, c0);
73   return p;
74 }
75 
76 // Polynomial approximation with double-double precision:
77 // Return exp(dx) ~ 1 + dx + dx^2 / 2 + ... + dx^6 / 720
78 // For |dx| < 2^-13 + 2^-30:
79 //   | output - exp(dx) | < 2^-101
poly_approx_dd(const DoubleDouble & dx)80 DoubleDouble poly_approx_dd(const DoubleDouble &dx) {
81   // Taylor polynomial.
82   constexpr DoubleDouble COEFFS[] = {
83       {0, 0x1p0},                                      // 1
84       {0, 0x1p0},                                      // 1
85       {0, 0x1p-1},                                     // 1/2
86       {0x1.5555555555555p-57, 0x1.5555555555555p-3},   // 1/6
87       {0x1.5555555555555p-59, 0x1.5555555555555p-5},   // 1/24
88       {0x1.1111111111111p-63, 0x1.1111111111111p-7},   // 1/120
89       {-0x1.f49f49f49f49fp-65, 0x1.6c16c16c16c17p-10}, // 1/720
90   };
91 
92   DoubleDouble p = fputil::polyeval(dx, COEFFS[0], COEFFS[1], COEFFS[2],
93                                     COEFFS[3], COEFFS[4], COEFFS[5], COEFFS[6]);
94   return p;
95 }
96 
97 // Polynomial approximation with 128-bit precision:
98 // Return exp(dx) ~ 1 + dx + dx^2 / 2 + ... + dx^7 / 5040
99 // For |dx| < 2^-13 + 2^-30:
100 //   | output - exp(dx) | < 2^-126.
poly_approx_f128(const Float128 & dx)101 Float128 poly_approx_f128(const Float128 &dx) {
102   constexpr Float128 COEFFS_128[]{
103       {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0
104       {Sign::POS, -127, 0x80000000'00000000'00000000'00000000_u128}, // 1.0
105       {Sign::POS, -128, 0x80000000'00000000'00000000'00000000_u128}, // 0.5
106       {Sign::POS, -130, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1/6
107       {Sign::POS, -132, 0xaaaaaaaa'aaaaaaaa'aaaaaaaa'aaaaaaab_u128}, // 1/24
108       {Sign::POS, -134, 0x88888888'88888888'88888888'88888889_u128}, // 1/120
109       {Sign::POS, -137, 0xb60b60b6'0b60b60b'60b60b60'b60b60b6_u128}, // 1/720
110       {Sign::POS, -140, 0xd00d00d0'0d00d00d'00d00d00'd00d00d0_u128}, // 1/5040
111   };
112 
113   Float128 p = fputil::polyeval(dx, COEFFS_128[0], COEFFS_128[1], COEFFS_128[2],
114                                 COEFFS_128[3], COEFFS_128[4], COEFFS_128[5],
115                                 COEFFS_128[6], COEFFS_128[7]);
116   return p;
117 }
118 
119 // Compute exp(x) using 128-bit precision.
120 // TODO(lntue): investigate triple-double precision implementation for this
121 // step.
exp_f128(double x,double kd,int idx1,int idx2)122 Float128 exp_f128(double x, double kd, int idx1, int idx2) {
123   // Recalculate dx:
124 
125   double t1 = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact
126   double t2 = kd * MLOG_2_EXP2_M12_MID_30;                     // exact
127   double t3 = kd * MLOG_2_EXP2_M12_LO;                         // Error < 2^-133
128 
129   Float128 dx = fputil::quick_add(
130       Float128(t1), fputil::quick_add(Float128(t2), Float128(t3)));
131 
132   // TODO: Skip recalculating exp_mid1 and exp_mid2.
133   Float128 exp_mid1 =
134       fputil::quick_add(Float128(EXP2_MID1[idx1].hi),
135                         fputil::quick_add(Float128(EXP2_MID1[idx1].mid),
136                                           Float128(EXP2_MID1[idx1].lo)));
137 
138   Float128 exp_mid2 =
139       fputil::quick_add(Float128(EXP2_MID2[idx2].hi),
140                         fputil::quick_add(Float128(EXP2_MID2[idx2].mid),
141                                           Float128(EXP2_MID2[idx2].lo)));
142 
143   Float128 exp_mid = fputil::quick_mul(exp_mid1, exp_mid2);
144 
145   Float128 p = poly_approx_f128(dx);
146 
147   Float128 r = fputil::quick_mul(exp_mid, p);
148 
149   r.exponent += static_cast<int>(kd) >> 12;
150 
151   return r;
152 }
153 
154 // Compute exp(x) with double-double precision.
exp_double_double(double x,double kd,const DoubleDouble & exp_mid)155 DoubleDouble exp_double_double(double x, double kd,
156                                const DoubleDouble &exp_mid) {
157   // Recalculate dx:
158   //   dx = x - k * 2^-12 * log(2)
159   double t1 = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact
160   double t2 = kd * MLOG_2_EXP2_M12_MID_30;                     // exact
161   double t3 = kd * MLOG_2_EXP2_M12_LO;                         // Error < 2^-130
162 
163   DoubleDouble dx = fputil::exact_add(t1, t2);
164   dx.lo += t3;
165 
166   // Degree-6 Taylor polynomial approximation in double-double precision.
167   // | p - exp(x) | < 2^-100.
168   DoubleDouble p = poly_approx_dd(dx);
169 
170   // Error bounds: 2^-99.
171   DoubleDouble r = fputil::quick_mult(exp_mid, p);
172 
173   return r;
174 }
175 
176 // Check for exceptional cases when
177 // |x| <= 2^-53 or x < log(2^-1075) or x >= 0x1.6232bdd7abcd3p+9
set_exceptional(double x)178 double set_exceptional(double x) {
179   using FPBits = typename fputil::FPBits<double>;
180   FPBits xbits(x);
181 
182   uint64_t x_u = xbits.uintval();
183   uint64_t x_abs = xbits.abs().uintval();
184 
185   // |x| <= 2^-53
186   if (x_abs <= 0x3ca0'0000'0000'0000ULL) {
187     // exp(x) ~ 1 + x
188     return 1 + x;
189   }
190 
191   // x <= log(2^-1075) || x >= 0x1.6232bdd7abcd3p+9 or inf/nan.
192 
193   // x <= log(2^-1075) or -inf/nan
194   if (x_u >= 0xc087'4910'd52d'3052ULL) {
195     // exp(-Inf) = 0
196     if (xbits.is_inf())
197       return 0.0;
198 
199     // exp(nan) = nan
200     if (xbits.is_nan())
201       return x;
202 
203     if (fputil::quick_get_round() == FE_UPWARD)
204       return FPBits::min_subnormal().get_val();
205     fputil::set_errno_if_required(ERANGE);
206     fputil::raise_except_if_required(FE_UNDERFLOW);
207     return 0.0;
208   }
209 
210   // x >= round(log(MAX_NORMAL), D, RU) = 0x1.62e42fefa39fp+9 or +inf/nan
211   // x is finite
212   if (x_u < 0x7ff0'0000'0000'0000ULL) {
213     int rounding = fputil::quick_get_round();
214     if (rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO)
215       return FPBits::max_normal().get_val();
216 
217     fputil::set_errno_if_required(ERANGE);
218     fputil::raise_except_if_required(FE_OVERFLOW);
219   }
220   // x is +inf or nan
221   return x + FPBits::inf().get_val();
222 }
223 
224 } // namespace
225 
226 LLVM_LIBC_FUNCTION(double, exp, (double x)) {
227   using FPBits = typename fputil::FPBits<double>;
228   FPBits xbits(x);
229 
230   uint64_t x_u = xbits.uintval();
231 
232   // Upper bound: max normal number = 2^1023 * (2 - 2^-52)
233   // > round(log (2^1023 ( 2 - 2^-52 )), D, RU) = 0x1.62e42fefa39fp+9
234   // > round(log (2^1023 ( 2 - 2^-52 )), D, RD) = 0x1.62e42fefa39efp+9
235   // > round(log (2^1023 ( 2 - 2^-52 )), D, RN) = 0x1.62e42fefa39efp+9
236   // > round(exp(0x1.62e42fefa39fp+9), D, RN) = infty
237 
238   // Lower bound: min denormal number / 2 = 2^-1075
239   // > round(log(2^-1075), D, RN) = -0x1.74910d52d3052p9
240 
241   // Another lower bound: min normal number = 2^-1022
242   // > round(log(2^-1022), D, RN) = -0x1.6232bdd7abcd2p9
243 
244   // x < log(2^-1075) or x >= 0x1.6232bdd7abcd3p+9 or |x| < 2^-53.
245   if (LIBC_UNLIKELY(x_u >= 0xc0874910d52d3052 ||
246                     (x_u < 0xbca0000000000000 && x_u >= 0x40862e42fefa39f0) ||
247                     x_u < 0x3ca0000000000000)) {
248     return set_exceptional(x);
249   }
250 
251   // Now log(2^-1075) <= x <= -2^-53 or 2^-53 <= x < log(2^1023 * (2 - 2^-52))
252 
253   // Range reduction:
254   // Let x = log(2) * (hi + mid1 + mid2) + lo
255   // in which:
256   //   hi is an integer
257   //   mid1 * 2^6 is an integer
258   //   mid2 * 2^12 is an integer
259   // then:
260   //   exp(x) = 2^hi * 2^(mid1) * 2^(mid2) * exp(lo).
261   // With this formula:
262   //   - multiplying by 2^hi is exact and cheap, simply by adding the exponent
263   //     field.
264   //   - 2^(mid1) and 2^(mid2) are stored in 2 x 64-element tables.
265   //   - exp(lo) ~ 1 + lo + a0 * lo^2 + ...
266   //
267   // They can be defined by:
268   //   hi + mid1 + mid2 = 2^(-12) * round(2^12 * log_2(e) * x)
269   // If we store L2E = round(log2(e), D, RN), then:
270   //   log2(e) - L2E ~ 1.5 * 2^(-56)
271   // So the errors when computing in double precision is:
272   //   | x * 2^12 * log_2(e) - D(x * 2^12 * L2E) | <=
273   //  <= | x * 2^12 * log_2(e) - x * 2^12 * L2E | +
274   //     + | x * 2^12 * L2E - D(x * 2^12 * L2E) |
275   //  <= 2^12 * ( |x| * 1.5 * 2^-56 + eps(x))  for RN
276   //     2^12 * ( |x| * 1.5 * 2^-56 + 2*eps(x)) for other rounding modes.
277   // So if:
278   //   hi + mid1 + mid2 = 2^(-12) * round(x * 2^12 * L2E) is computed entirely
279   // in double precision, the reduced argument:
280   //   lo = x - log(2) * (hi + mid1 + mid2) is bounded by:
281   //   |lo| <= 2^-13 + (|x| * 1.5 * 2^-56 + 2*eps(x))
282   //         < 2^-13 + (1.5 * 2^9 * 1.5 * 2^-56 + 2*2^(9 - 52))
283   //         < 2^-13 + 2^-41
284   //
285 
286   // The following trick computes the round(x * L2E) more efficiently
287   // than using the rounding instructions, with the tradeoff for less accuracy,
288   // and hence a slightly larger range for the reduced argument `lo`.
289   //
290   // To be precise, since |x| < |log(2^-1075)| < 1.5 * 2^9,
291   //   |x * 2^12 * L2E| < 1.5 * 2^9 * 1.5 < 2^23,
292   // So we can fit the rounded result round(x * 2^12 * L2E) in int32_t.
293   // Thus, the goal is to be able to use an additional addition and fixed width
294   // shift to get an int32_t representing round(x * 2^12 * L2E).
295   //
296   // Assuming int32_t using 2-complement representation, since the mantissa part
297   // of a double precision is unsigned with the leading bit hidden, if we add an
298   // extra constant C = 2^e1 + 2^e2 with e1 > e2 >= 2^25 to the product, the
299   // part that are < 2^e2 in resulted mantissa of (x*2^12*L2E + C) can be
300   // considered as a proper 2-complement representations of x*2^12*L2E.
301   //
302   // One small problem with this approach is that the sum (x*2^12*L2E + C) in
303   // double precision is rounded to the least significant bit of the dorminant
304   // factor C.  In order to minimize the rounding errors from this addition, we
305   // want to minimize e1.  Another constraint that we want is that after
306   // shifting the mantissa so that the least significant bit of int32_t
307   // corresponds to the unit bit of (x*2^12*L2E), the sign is correct without
308   // any adjustment.  So combining these 2 requirements, we can choose
309   //   C = 2^33 + 2^32, so that the sign bit corresponds to 2^31 bit, and hence
310   // after right shifting the mantissa, the resulting int32_t has correct sign.
311   // With this choice of C, the number of mantissa bits we need to shift to the
312   // right is: 52 - 33 = 19.
313   //
314   // Moreover, since the integer right shifts are equivalent to rounding down,
315   // we can add an extra 0.5 so that it will become round-to-nearest, tie-to-
316   // +infinity.  So in particular, we can compute:
317   //   hmm = x * 2^12 * L2E + C,
318   // where C = 2^33 + 2^32 + 2^-1, then if
319   //   k = int32_t(lower 51 bits of double(x * 2^12 * L2E + C) >> 19),
320   // the reduced argument:
321   //   lo = x - log(2) * 2^-12 * k is bounded by:
322   //   |lo| <= 2^-13 + 2^-41 + 2^-12*2^-19
323   //         = 2^-13 + 2^-31 + 2^-41.
324   //
325   // Finally, notice that k only uses the mantissa of x * 2^12 * L2E, so the
326   // exponent 2^12 is not needed.  So we can simply define
327   //   C = 2^(33 - 12) + 2^(32 - 12) + 2^(-13 - 12), and
328   //   k = int32_t(lower 51 bits of double(x * L2E + C) >> 19).
329 
330   // Rounding errors <= 2^-31 + 2^-41.
331   double tmp = fputil::multiply_add(x, LOG2_E, 0x1.8000'0000'4p21);
332   int k = static_cast<int>(cpp::bit_cast<uint64_t>(tmp) >> 19);
333   double kd = static_cast<double>(k);
334 
335   uint32_t idx1 = (k >> 6) & 0x3f;
336   uint32_t idx2 = k & 0x3f;
337   int hi = k >> 12;
338 
339   bool denorm = (hi <= -1022);
340 
341   DoubleDouble exp_mid1{EXP2_MID1[idx1].mid, EXP2_MID1[idx1].hi};
342   DoubleDouble exp_mid2{EXP2_MID2[idx2].mid, EXP2_MID2[idx2].hi};
343 
344   DoubleDouble exp_mid = fputil::quick_mult(exp_mid1, exp_mid2);
345 
346   // |x - (hi + mid1 + mid2) * log(2) - dx| < 2^11 * eps(M_LOG_2_EXP2_M12.lo)
347   //                                        = 2^11 * 2^-13 * 2^-52
348   //                                        = 2^-54.
349   // |dx| < 2^-13 + 2^-30.
350   double lo_h = fputil::multiply_add(kd, MLOG_2_EXP2_M12_HI, x); // exact
351   double dx = fputil::multiply_add(kd, MLOG_2_EXP2_M12_MID, lo_h);
352 
353   // We use the degree-4 Taylor polynomial to approximate exp(lo):
354   //   exp(lo) ~ 1 + lo + lo^2 / 2 + lo^3 / 6 + lo^4 / 24 = 1 + lo * P(lo)
355   // So that the errors are bounded by:
356   //   |P(lo) - expm1(lo)/lo| < |lo|^4 / 64 < 2^(-13 * 4) / 64 = 2^-58
357   // Let P_ be an evaluation of P where all intermediate computations are in
358   // double precision.  Using either Horner's or Estrin's schemes, the evaluated
359   // errors can be bounded by:
360   //      |P_(dx) - P(dx)| < 2^-51
361   //   => |dx * P_(dx) - expm1(lo) | < 1.5 * 2^-64
362   //   => 2^(mid1 + mid2) * |dx * P_(dx) - expm1(lo)| < 1.5 * 2^-63.
363   // Since we approximate
364   //   2^(mid1 + mid2) ~ exp_mid.hi + exp_mid.lo,
365   // We use the expression:
366   //    (exp_mid.hi + exp_mid.lo) * (1 + dx * P_(dx)) ~
367   //  ~ exp_mid.hi + (exp_mid.hi * dx * P_(dx) + exp_mid.lo)
368   // with errors bounded by 1.5 * 2^-63.
369 
370   double mid_lo = dx * exp_mid.hi;
371 
372   // Approximate expm1(dx)/dx ~ 1 + dx / 2 + dx^2 / 6 + dx^3 / 24.
373   double p = poly_approx_d(dx);
374 
375   double lo = fputil::multiply_add(p, mid_lo, exp_mid.lo);
376 
377   if (LIBC_UNLIKELY(denorm)) {
378     if (auto r = ziv_test_denorm(hi, exp_mid.hi, lo, ERR_D);
379         LIBC_LIKELY(r.has_value()))
380       return r.value();
381   } else {
382     double upper = exp_mid.hi + (lo + ERR_D);
383     double lower = exp_mid.hi + (lo - ERR_D);
384 
385     if (LIBC_LIKELY(upper == lower)) {
386       // to multiply by 2^hi, a fast way is to simply add hi to the exponent
387       // field.
388       int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;
389       double r = cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper));
390       return r;
391     }
392   }
393 
394   // Use double-double
395   DoubleDouble r_dd = exp_double_double(x, kd, exp_mid);
396 
397   if (LIBC_UNLIKELY(denorm)) {
398     if (auto r = ziv_test_denorm(hi, r_dd.hi, r_dd.lo, ERR_DD);
399         LIBC_LIKELY(r.has_value()))
400       return r.value();
401   } else {
402     double upper_dd = r_dd.hi + (r_dd.lo + ERR_DD);
403     double lower_dd = r_dd.hi + (r_dd.lo - ERR_DD);
404 
405     if (LIBC_LIKELY(upper_dd == lower_dd)) {
406       int64_t exp_hi = static_cast<int64_t>(hi) << FPBits::FRACTION_LEN;
407       double r =
408           cpp::bit_cast<double>(exp_hi + cpp::bit_cast<int64_t>(upper_dd));
409       return r;
410     }
411   }
412 
413   // Use 128-bit precision
414   Float128 r_f128 = exp_f128(x, kd, idx1, idx2);
415 
416   return static_cast<double>(r_f128);
417 }
418 
419 } // namespace LIBC_NAMESPACE
420