1 //===-- Utils which wrap MPFR ---------------------------------------------===//
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 "MPFRUtils.h"
10 
11 #include "src/__support/CPP/StringView.h"
12 #include "src/__support/FPUtil/FPBits.h"
13 #include "src/__support/FPUtil/PlatformDefs.h"
14 #include "utils/UnitTest/FPMatcher.h"
15 
16 #include <cmath>
17 #include <fenv.h>
18 #include <memory>
19 #include <sstream>
20 #include <stdint.h>
21 #include <string>
22 
23 #ifdef CUSTOM_MPFR_INCLUDER
24 // Some downstream repos are monoliths carrying MPFR sources in their third
25 // party directory. In such repos, including the MPFR header as
26 // `#include <mpfr.h>` is either disallowed or not possible. If that is the
27 // case, a file named `CustomMPFRIncluder.h` should be added through which the
28 // MPFR header can be included in manner allowed in that repo.
29 #include "CustomMPFRIncluder.h"
30 #else
31 #include <mpfr.h>
32 #endif
33 
34 template <typename T> using FPBits = __llvm_libc::fputil::FPBits<T>;
35 
36 namespace __llvm_libc {
37 namespace testing {
38 namespace mpfr {
39 
40 template <typename T> struct Precision;
41 
42 template <> struct Precision<float> {
43   static constexpr unsigned int VALUE = 24;
44 };
45 
46 template <> struct Precision<double> {
47   static constexpr unsigned int VALUE = 53;
48 };
49 
50 #if defined(LONG_DOUBLE_IS_DOUBLE)
51 template <> struct Precision<long double> {
52   static constexpr unsigned int VALUE = 53;
53 };
54 #elif defined(SPECIAL_X86_LONG_DOUBLE)
55 template <> struct Precision<long double> {
56   static constexpr unsigned int VALUE = 64;
57 };
58 #else
59 template <> struct Precision<long double> {
60   static constexpr unsigned int VALUE = 113;
61 };
62 #endif
63 
64 // A precision value which allows sufficiently large additional
65 // precision compared to the floating point precision.
66 template <typename T> struct ExtraPrecision;
67 
68 template <> struct ExtraPrecision<float> {
69   static constexpr unsigned int VALUE = 128;
70 };
71 
72 template <> struct ExtraPrecision<double> {
73   static constexpr unsigned int VALUE = 256;
74 };
75 
76 template <> struct ExtraPrecision<long double> {
77   static constexpr unsigned int VALUE = 256;
78 };
79 
80 // If the ulp tolerance is less than or equal to 0.5, we would check that the
81 // result is rounded correctly with respect to the rounding mode by using the
82 // same precision as the inputs.
83 template <typename T>
84 static inline unsigned int get_precision(double ulp_tolerance) {
85   if (ulp_tolerance <= 0.5) {
86     return Precision<T>::VALUE;
87   } else {
88     return ExtraPrecision<T>::VALUE;
89   }
90 }
91 
92 static inline mpfr_rnd_t get_mpfr_rounding_mode(RoundingMode mode) {
93   switch (mode) {
94   case RoundingMode::Upward:
95     return MPFR_RNDU;
96     break;
97   case RoundingMode::Downward:
98     return MPFR_RNDD;
99     break;
100   case RoundingMode::TowardZero:
101     return MPFR_RNDZ;
102     break;
103   case RoundingMode::Nearest:
104     return MPFR_RNDN;
105     break;
106   }
107 }
108 
109 int get_fe_rounding(RoundingMode mode) {
110   switch (mode) {
111   case RoundingMode::Upward:
112     return FE_UPWARD;
113     break;
114   case RoundingMode::Downward:
115     return FE_DOWNWARD;
116     break;
117   case RoundingMode::TowardZero:
118     return FE_TOWARDZERO;
119     break;
120   case RoundingMode::Nearest:
121     return FE_TONEAREST;
122     break;
123   }
124 }
125 
126 ForceRoundingMode::ForceRoundingMode(RoundingMode mode) {
127   old_rounding_mode = fegetround();
128   rounding_mode = get_fe_rounding(mode);
129   if (old_rounding_mode != rounding_mode)
130     fesetround(rounding_mode);
131 }
132 
133 ForceRoundingMode::~ForceRoundingMode() {
134   if (old_rounding_mode != rounding_mode)
135     fesetround(old_rounding_mode);
136 }
137 
138 class MPFRNumber {
139   unsigned int mpfr_precision;
140   mpfr_rnd_t mpfr_rounding;
141 
142   mpfr_t value;
143 
144 public:
145   MPFRNumber() : mpfr_precision(256), mpfr_rounding(MPFR_RNDN) {
146     mpfr_init2(value, mpfr_precision);
147   }
148 
149   // We use explicit EnableIf specializations to disallow implicit
150   // conversions. Implicit conversions can potentially lead to loss of
151   // precision.
152   template <typename XType,
153             cpp::EnableIfType<cpp::IsSame<float, XType>::Value, int> = 0>
154   explicit MPFRNumber(XType x, int precision = ExtraPrecision<XType>::VALUE,
155                       RoundingMode rounding = RoundingMode::Nearest)
156       : mpfr_precision(precision),
157         mpfr_rounding(get_mpfr_rounding_mode(rounding)) {
158     mpfr_init2(value, mpfr_precision);
159     mpfr_set_flt(value, x, mpfr_rounding);
160   }
161 
162   template <typename XType,
163             cpp::EnableIfType<cpp::IsSame<double, XType>::Value, int> = 0>
164   explicit MPFRNumber(XType x, int precision = ExtraPrecision<XType>::VALUE,
165                       RoundingMode rounding = RoundingMode::Nearest)
166       : mpfr_precision(precision),
167         mpfr_rounding(get_mpfr_rounding_mode(rounding)) {
168     mpfr_init2(value, mpfr_precision);
169     mpfr_set_d(value, x, mpfr_rounding);
170   }
171 
172   template <typename XType,
173             cpp::EnableIfType<cpp::IsSame<long double, XType>::Value, int> = 0>
174   explicit MPFRNumber(XType x, int precision = ExtraPrecision<XType>::VALUE,
175                       RoundingMode rounding = RoundingMode::Nearest)
176       : mpfr_precision(precision),
177         mpfr_rounding(get_mpfr_rounding_mode(rounding)) {
178     mpfr_init2(value, mpfr_precision);
179     mpfr_set_ld(value, x, mpfr_rounding);
180   }
181 
182   template <typename XType,
183             cpp::EnableIfType<cpp::IsIntegral<XType>::Value, int> = 0>
184   explicit MPFRNumber(XType x, int precision = ExtraPrecision<float>::VALUE,
185                       RoundingMode rounding = RoundingMode::Nearest)
186       : mpfr_precision(precision),
187         mpfr_rounding(get_mpfr_rounding_mode(rounding)) {
188     mpfr_init2(value, mpfr_precision);
189     mpfr_set_sj(value, x, mpfr_rounding);
190   }
191 
192   MPFRNumber(const MPFRNumber &other)
193       : mpfr_precision(other.mpfr_precision),
194         mpfr_rounding(other.mpfr_rounding) {
195     mpfr_init2(value, mpfr_precision);
196     mpfr_set(value, other.value, mpfr_rounding);
197   }
198 
199   ~MPFRNumber() { mpfr_clear(value); }
200 
201   MPFRNumber &operator=(const MPFRNumber &rhs) {
202     mpfr_precision = rhs.mpfr_precision;
203     mpfr_rounding = rhs.mpfr_rounding;
204     mpfr_set(value, rhs.value, mpfr_rounding);
205     return *this;
206   }
207 
208   MPFRNumber abs() const {
209     MPFRNumber result(*this);
210     mpfr_abs(result.value, value, mpfr_rounding);
211     return result;
212   }
213 
214   MPFRNumber ceil() const {
215     MPFRNumber result(*this);
216     mpfr_ceil(result.value, value);
217     return result;
218   }
219 
220   MPFRNumber cos() const {
221     MPFRNumber result(*this);
222     mpfr_cos(result.value, value, mpfr_rounding);
223     return result;
224   }
225 
226   MPFRNumber exp() const {
227     MPFRNumber result(*this);
228     mpfr_exp(result.value, value, mpfr_rounding);
229     return result;
230   }
231 
232   MPFRNumber exp2() const {
233     MPFRNumber result(*this);
234     mpfr_exp2(result.value, value, mpfr_rounding);
235     return result;
236   }
237 
238   MPFRNumber expm1() const {
239     MPFRNumber result(*this);
240     mpfr_expm1(result.value, value, mpfr_rounding);
241     return result;
242   }
243 
244   MPFRNumber floor() const {
245     MPFRNumber result(*this);
246     mpfr_floor(result.value, value);
247     return result;
248   }
249 
250   MPFRNumber frexp(int &exp) {
251     MPFRNumber result(*this);
252     mpfr_exp_t resultExp;
253     mpfr_frexp(&resultExp, result.value, value, mpfr_rounding);
254     exp = resultExp;
255     return result;
256   }
257 
258   MPFRNumber hypot(const MPFRNumber &b) {
259     MPFRNumber result(*this);
260     mpfr_hypot(result.value, value, b.value, mpfr_rounding);
261     return result;
262   }
263 
264   MPFRNumber log() const {
265     MPFRNumber result(*this);
266     mpfr_log(result.value, value, mpfr_rounding);
267     return result;
268   }
269 
270   MPFRNumber log2() const {
271     MPFRNumber result(*this);
272     mpfr_log2(result.value, value, mpfr_rounding);
273     return result;
274   }
275 
276   MPFRNumber log10() const {
277     MPFRNumber result(*this);
278     mpfr_log10(result.value, value, mpfr_rounding);
279     return result;
280   }
281 
282   MPFRNumber log1p() const {
283     MPFRNumber result(*this);
284     mpfr_log1p(result.value, value, mpfr_rounding);
285     return result;
286   }
287 
288   MPFRNumber remquo(const MPFRNumber &divisor, int &quotient) {
289     MPFRNumber remainder(*this);
290     long q;
291     mpfr_remquo(remainder.value, &q, value, divisor.value, mpfr_rounding);
292     quotient = q;
293     return remainder;
294   }
295 
296   MPFRNumber round() const {
297     MPFRNumber result(*this);
298     mpfr_round(result.value, value);
299     return result;
300   }
301 
302   bool round_to_long(long &result) const {
303     // We first calculate the rounded value. This way, when converting
304     // to long using mpfr_get_si, the rounding direction of MPFR_RNDN
305     // (or any other rounding mode), does not have an influence.
306     MPFRNumber roundedValue = round();
307     mpfr_clear_erangeflag();
308     result = mpfr_get_si(roundedValue.value, MPFR_RNDN);
309     return mpfr_erangeflag_p();
310   }
311 
312   bool round_to_long(mpfr_rnd_t rnd, long &result) const {
313     MPFRNumber rint_result(*this);
314     mpfr_rint(rint_result.value, value, rnd);
315     return rint_result.round_to_long(result);
316   }
317 
318   MPFRNumber rint(mpfr_rnd_t rnd) const {
319     MPFRNumber result(*this);
320     mpfr_rint(result.value, value, rnd);
321     return result;
322   }
323 
324   MPFRNumber mod_2pi() const {
325     MPFRNumber result(0.0, 1280);
326     MPFRNumber _2pi(0.0, 1280);
327     mpfr_const_pi(_2pi.value, MPFR_RNDN);
328     mpfr_mul_si(_2pi.value, _2pi.value, 2, MPFR_RNDN);
329     mpfr_fmod(result.value, value, _2pi.value, MPFR_RNDN);
330     return result;
331   }
332 
333   MPFRNumber mod_pi_over_2() const {
334     MPFRNumber result(0.0, 1280);
335     MPFRNumber pi_over_2(0.0, 1280);
336     mpfr_const_pi(pi_over_2.value, MPFR_RNDN);
337     mpfr_mul_d(pi_over_2.value, pi_over_2.value, 0.5, MPFR_RNDN);
338     mpfr_fmod(result.value, value, pi_over_2.value, MPFR_RNDN);
339     return result;
340   }
341 
342   MPFRNumber mod_pi_over_4() const {
343     MPFRNumber result(0.0, 1280);
344     MPFRNumber pi_over_4(0.0, 1280);
345     mpfr_const_pi(pi_over_4.value, MPFR_RNDN);
346     mpfr_mul_d(pi_over_4.value, pi_over_4.value, 0.25, MPFR_RNDN);
347     mpfr_fmod(result.value, value, pi_over_4.value, MPFR_RNDN);
348     return result;
349   }
350 
351   MPFRNumber sin() const {
352     MPFRNumber result(*this);
353     mpfr_sin(result.value, value, mpfr_rounding);
354     return result;
355   }
356 
357   MPFRNumber sqrt() const {
358     MPFRNumber result(*this);
359     mpfr_sqrt(result.value, value, mpfr_rounding);
360     return result;
361   }
362 
363   MPFRNumber tan() const {
364     MPFRNumber result(*this);
365     mpfr_tan(result.value, value, mpfr_rounding);
366     return result;
367   }
368 
369   MPFRNumber trunc() const {
370     MPFRNumber result(*this);
371     mpfr_trunc(result.value, value);
372     return result;
373   }
374 
375   MPFRNumber fma(const MPFRNumber &b, const MPFRNumber &c) {
376     MPFRNumber result(*this);
377     mpfr_fma(result.value, value, b.value, c.value, mpfr_rounding);
378     return result;
379   }
380 
381   std::string str() const {
382     // 200 bytes should be more than sufficient to hold a 100-digit number
383     // plus additional bytes for the decimal point, '-' sign etc.
384     constexpr size_t printBufSize = 200;
385     char buffer[printBufSize];
386     mpfr_snprintf(buffer, printBufSize, "%100.50Rf", value);
387     cpp::StringView view(buffer);
388     view = view.trim(' ');
389     return std::string(view.data());
390   }
391 
392   // These functions are useful for debugging.
393   template <typename T> T as() const;
394 
395   template <> float as<float>() const {
396     return mpfr_get_flt(value, mpfr_rounding);
397   }
398   template <> double as<double>() const {
399     return mpfr_get_d(value, mpfr_rounding);
400   }
401   template <> long double as<long double>() const {
402     return mpfr_get_ld(value, mpfr_rounding);
403   }
404 
405   void dump(const char *msg) const { mpfr_printf("%s%.128Rf\n", msg, value); }
406 
407   // Return the ULP (units-in-the-last-place) difference between the
408   // stored MPFR and a floating point number.
409   //
410   // We define ULP difference as follows:
411   //   If exponents of this value and the |input| are same, then:
412   //     ULP(this_value, input) = abs(this_value - input) / eps(input)
413   //   else:
414   //     max = max(abs(this_value), abs(input))
415   //     min = min(abs(this_value), abs(input))
416   //     maxExponent = exponent(max)
417   //     ULP(this_value, input) = (max - 2^maxExponent) / eps(max) +
418   //                              (2^maxExponent - min) / eps(min)
419   //
420   // Remarks:
421   // 1. A ULP of 0.0 will imply that the value is correctly rounded.
422   // 2. We expect that this value and the value to be compared (the [input]
423   //    argument) are reasonable close, and we will provide an upper bound
424   //    of ULP value for testing.  Morever, most of the fractional parts of
425   //    ULP value do not matter much, so using double as the return type
426   //    should be good enough.
427   // 3. For close enough values (values which don't diff in their exponent by
428   //    not more than 1), a ULP difference of N indicates a bit distance
429   //    of N between this number and [input].
430   // 4. A values of +0.0 and -0.0 are treated as equal.
431   template <typename T>
432   cpp::EnableIfType<cpp::IsFloatingPointType<T>::Value, double> ulp(T input) {
433     T thisAsT = as<T>();
434     if (thisAsT == input)
435       return T(0.0);
436 
437     int thisExponent = fputil::FPBits<T>(thisAsT).get_exponent();
438     int inputExponent = fputil::FPBits<T>(input).get_exponent();
439     // Adjust the exponents for denormal numbers.
440     if (fputil::FPBits<T>(thisAsT).get_unbiased_exponent() == 0)
441       ++thisExponent;
442     if (fputil::FPBits<T>(input).get_unbiased_exponent() == 0)
443       ++inputExponent;
444 
445     if (thisAsT * input < 0 || thisExponent == inputExponent) {
446       MPFRNumber inputMPFR(input);
447       mpfr_sub(inputMPFR.value, value, inputMPFR.value, MPFR_RNDN);
448       mpfr_abs(inputMPFR.value, inputMPFR.value, MPFR_RNDN);
449       mpfr_mul_2si(inputMPFR.value, inputMPFR.value,
450                    -thisExponent + int(fputil::MantissaWidth<T>::VALUE),
451                    MPFR_RNDN);
452       return inputMPFR.as<double>();
453     }
454 
455     // If the control reaches here, it means that this number and input are
456     // of the same sign but different exponent. In such a case, ULP error is
457     // calculated as sum of two parts.
458     thisAsT = std::abs(thisAsT);
459     input = std::abs(input);
460     T min = thisAsT > input ? input : thisAsT;
461     T max = thisAsT > input ? thisAsT : input;
462     int minExponent = fputil::FPBits<T>(min).get_exponent();
463     int maxExponent = fputil::FPBits<T>(max).get_exponent();
464     // Adjust the exponents for denormal numbers.
465     if (fputil::FPBits<T>(min).get_unbiased_exponent() == 0)
466       ++minExponent;
467     if (fputil::FPBits<T>(max).get_unbiased_exponent() == 0)
468       ++maxExponent;
469 
470     MPFRNumber minMPFR(min);
471     MPFRNumber maxMPFR(max);
472 
473     MPFRNumber pivot(uint32_t(1));
474     mpfr_mul_2si(pivot.value, pivot.value, maxExponent, MPFR_RNDN);
475 
476     mpfr_sub(minMPFR.value, pivot.value, minMPFR.value, MPFR_RNDN);
477     mpfr_mul_2si(minMPFR.value, minMPFR.value,
478                  -minExponent + int(fputil::MantissaWidth<T>::VALUE),
479                  MPFR_RNDN);
480 
481     mpfr_sub(maxMPFR.value, maxMPFR.value, pivot.value, MPFR_RNDN);
482     mpfr_mul_2si(maxMPFR.value, maxMPFR.value,
483                  -maxExponent + int(fputil::MantissaWidth<T>::VALUE),
484                  MPFR_RNDN);
485 
486     mpfr_add(minMPFR.value, minMPFR.value, maxMPFR.value, MPFR_RNDN);
487     return minMPFR.as<double>();
488   }
489 };
490 
491 namespace internal {
492 
493 template <typename InputType>
494 cpp::EnableIfType<cpp::IsFloatingPointType<InputType>::Value, MPFRNumber>
495 unary_operation(Operation op, InputType input, unsigned int precision,
496                 RoundingMode rounding) {
497   MPFRNumber mpfrInput(input, precision, rounding);
498   switch (op) {
499   case Operation::Abs:
500     return mpfrInput.abs();
501   case Operation::Ceil:
502     return mpfrInput.ceil();
503   case Operation::Cos:
504     return mpfrInput.cos();
505   case Operation::Exp:
506     return mpfrInput.exp();
507   case Operation::Exp2:
508     return mpfrInput.exp2();
509   case Operation::Expm1:
510     return mpfrInput.expm1();
511   case Operation::Floor:
512     return mpfrInput.floor();
513   case Operation::Log:
514     return mpfrInput.log();
515   case Operation::Log2:
516     return mpfrInput.log2();
517   case Operation::Log10:
518     return mpfrInput.log10();
519   case Operation::Log1p:
520     return mpfrInput.log1p();
521   case Operation::Mod2PI:
522     return mpfrInput.mod_2pi();
523   case Operation::ModPIOver2:
524     return mpfrInput.mod_pi_over_2();
525   case Operation::ModPIOver4:
526     return mpfrInput.mod_pi_over_4();
527   case Operation::Round:
528     return mpfrInput.round();
529   case Operation::Sin:
530     return mpfrInput.sin();
531   case Operation::Sqrt:
532     return mpfrInput.sqrt();
533   case Operation::Tan:
534     return mpfrInput.tan();
535   case Operation::Trunc:
536     return mpfrInput.trunc();
537   default:
538     __builtin_unreachable();
539   }
540 }
541 
542 template <typename InputType>
543 cpp::EnableIfType<cpp::IsFloatingPointType<InputType>::Value, MPFRNumber>
544 unary_operation_two_outputs(Operation op, InputType input, int &output,
545                             unsigned int precision, RoundingMode rounding) {
546   MPFRNumber mpfrInput(input, precision, rounding);
547   switch (op) {
548   case Operation::Frexp:
549     return mpfrInput.frexp(output);
550   default:
551     __builtin_unreachable();
552   }
553 }
554 
555 template <typename InputType>
556 cpp::EnableIfType<cpp::IsFloatingPointType<InputType>::Value, MPFRNumber>
557 binary_operation_one_output(Operation op, InputType x, InputType y,
558                             unsigned int precision, RoundingMode rounding) {
559   MPFRNumber inputX(x, precision, rounding);
560   MPFRNumber inputY(y, precision, rounding);
561   switch (op) {
562   case Operation::Hypot:
563     return inputX.hypot(inputY);
564   default:
565     __builtin_unreachable();
566   }
567 }
568 
569 template <typename InputType>
570 cpp::EnableIfType<cpp::IsFloatingPointType<InputType>::Value, MPFRNumber>
571 binary_operation_two_outputs(Operation op, InputType x, InputType y,
572                              int &output, unsigned int precision,
573                              RoundingMode rounding) {
574   MPFRNumber inputX(x, precision, rounding);
575   MPFRNumber inputY(y, precision, rounding);
576   switch (op) {
577   case Operation::RemQuo:
578     return inputX.remquo(inputY, output);
579   default:
580     __builtin_unreachable();
581   }
582 }
583 
584 template <typename InputType>
585 cpp::EnableIfType<cpp::IsFloatingPointType<InputType>::Value, MPFRNumber>
586 ternary_operation_one_output(Operation op, InputType x, InputType y,
587                              InputType z, unsigned int precision,
588                              RoundingMode rounding) {
589   // For FMA function, we just need to compare with the mpfr_fma with the same
590   // precision as InputType.  Using higher precision as the intermediate results
591   // to compare might incorrectly fail due to double-rounding errors.
592   MPFRNumber inputX(x, precision, rounding);
593   MPFRNumber inputY(y, precision, rounding);
594   MPFRNumber inputZ(z, precision, rounding);
595   switch (op) {
596   case Operation::Fma:
597     return inputX.fma(inputY, inputZ);
598   default:
599     __builtin_unreachable();
600   }
601 }
602 
603 // Remark: For all the explain_*_error functions, we will use std::stringstream
604 // to build the complete error messages before sending it to the outstream `OS`
605 // once at the end.  This will stop the error messages from interleaving when
606 // the tests are running concurrently.
607 template <typename T>
608 void explain_unary_operation_single_output_error(Operation op, T input,
609                                                  T matchValue,
610                                                  double ulp_tolerance,
611                                                  RoundingMode rounding,
612                                                  testutils::StreamWrapper &OS) {
613   unsigned int precision = get_precision<T>(ulp_tolerance);
614   MPFRNumber mpfrInput(input, precision);
615   MPFRNumber mpfr_result;
616   mpfr_result = unary_operation(op, input, precision, rounding);
617   MPFRNumber mpfrMatchValue(matchValue);
618   std::stringstream ss;
619   ss << "Match value not within tolerance value of MPFR result:\n"
620      << "  Input decimal: " << mpfrInput.str() << '\n';
621   __llvm_libc::fputil::testing::describeValue("     Input bits: ", input, ss);
622   ss << '\n' << "  Match decimal: " << mpfrMatchValue.str() << '\n';
623   __llvm_libc::fputil::testing::describeValue("     Match bits: ", matchValue,
624                                               ss);
625   ss << '\n' << "    MPFR result: " << mpfr_result.str() << '\n';
626   __llvm_libc::fputil::testing::describeValue(
627       "   MPFR rounded: ", mpfr_result.as<T>(), ss);
628   ss << '\n';
629   ss << "      ULP error: " << std::to_string(mpfr_result.ulp(matchValue))
630      << '\n';
631   OS << ss.str();
632 }
633 
634 template void
635 explain_unary_operation_single_output_error<float>(Operation op, float, float,
636                                                    double, RoundingMode,
637                                                    testutils::StreamWrapper &);
638 template void explain_unary_operation_single_output_error<double>(
639     Operation op, double, double, double, RoundingMode,
640     testutils::StreamWrapper &);
641 template void explain_unary_operation_single_output_error<long double>(
642     Operation op, long double, long double, double, RoundingMode,
643     testutils::StreamWrapper &);
644 
645 template <typename T>
646 void explain_unary_operation_two_outputs_error(
647     Operation op, T input, const BinaryOutput<T> &libc_result,
648     double ulp_tolerance, RoundingMode rounding, testutils::StreamWrapper &OS) {
649   unsigned int precision = get_precision<T>(ulp_tolerance);
650   MPFRNumber mpfrInput(input, precision);
651   int mpfrIntResult;
652   MPFRNumber mpfr_result = unary_operation_two_outputs(op, input, mpfrIntResult,
653                                                        precision, rounding);
654   std::stringstream ss;
655 
656   if (mpfrIntResult != libc_result.i) {
657     ss << "MPFR integral result: " << mpfrIntResult << '\n'
658        << "Libc integral result: " << libc_result.i << '\n';
659   } else {
660     ss << "Integral result from libc matches integral result from MPFR.\n";
661   }
662 
663   MPFRNumber mpfrMatchValue(libc_result.f);
664   ss << "Libc floating point result is not within tolerance value of the MPFR "
665      << "result.\n\n";
666 
667   ss << "            Input decimal: " << mpfrInput.str() << "\n\n";
668 
669   ss << "Libc floating point value: " << mpfrMatchValue.str() << '\n';
670   __llvm_libc::fputil::testing::describeValue(
671       " Libc floating point bits: ", libc_result.f, ss);
672   ss << "\n\n";
673 
674   ss << "              MPFR result: " << mpfr_result.str() << '\n';
675   __llvm_libc::fputil::testing::describeValue(
676       "             MPFR rounded: ", mpfr_result.as<T>(), ss);
677   ss << '\n'
678      << "                ULP error: "
679      << std::to_string(mpfr_result.ulp(libc_result.f)) << '\n';
680   OS << ss.str();
681 }
682 
683 template void explain_unary_operation_two_outputs_error<float>(
684     Operation, float, const BinaryOutput<float> &, double, RoundingMode,
685     testutils::StreamWrapper &);
686 template void explain_unary_operation_two_outputs_error<double>(
687     Operation, double, const BinaryOutput<double> &, double, RoundingMode,
688     testutils::StreamWrapper &);
689 template void explain_unary_operation_two_outputs_error<long double>(
690     Operation, long double, const BinaryOutput<long double> &, double,
691     RoundingMode, testutils::StreamWrapper &);
692 
693 template <typename T>
694 void explain_binary_operation_two_outputs_error(
695     Operation op, const BinaryInput<T> &input,
696     const BinaryOutput<T> &libc_result, double ulp_tolerance,
697     RoundingMode rounding, testutils::StreamWrapper &OS) {
698   unsigned int precision = get_precision<T>(ulp_tolerance);
699   MPFRNumber mpfrX(input.x, precision);
700   MPFRNumber mpfrY(input.y, precision);
701   int mpfrIntResult;
702   MPFRNumber mpfr_result = binary_operation_two_outputs(
703       op, input.x, input.y, mpfrIntResult, precision, rounding);
704   MPFRNumber mpfrMatchValue(libc_result.f);
705   std::stringstream ss;
706 
707   ss << "Input decimal: x: " << mpfrX.str() << " y: " << mpfrY.str() << '\n'
708      << "MPFR integral result: " << mpfrIntResult << '\n'
709      << "Libc integral result: " << libc_result.i << '\n'
710      << "Libc floating point result: " << mpfrMatchValue.str() << '\n'
711      << "               MPFR result: " << mpfr_result.str() << '\n';
712   __llvm_libc::fputil::testing::describeValue(
713       "Libc floating point result bits: ", libc_result.f, ss);
714   __llvm_libc::fputil::testing::describeValue(
715       "              MPFR rounded bits: ", mpfr_result.as<T>(), ss);
716   ss << "ULP error: " << std::to_string(mpfr_result.ulp(libc_result.f)) << '\n';
717   OS << ss.str();
718 }
719 
720 template void explain_binary_operation_two_outputs_error<float>(
721     Operation, const BinaryInput<float> &, const BinaryOutput<float> &, double,
722     RoundingMode, testutils::StreamWrapper &);
723 template void explain_binary_operation_two_outputs_error<double>(
724     Operation, const BinaryInput<double> &, const BinaryOutput<double> &,
725     double, RoundingMode, testutils::StreamWrapper &);
726 template void explain_binary_operation_two_outputs_error<long double>(
727     Operation, const BinaryInput<long double> &,
728     const BinaryOutput<long double> &, double, RoundingMode,
729     testutils::StreamWrapper &);
730 
731 template <typename T>
732 void explain_binary_operation_one_output_error(
733     Operation op, const BinaryInput<T> &input, T libc_result,
734     double ulp_tolerance, RoundingMode rounding, testutils::StreamWrapper &OS) {
735   unsigned int precision = get_precision<T>(ulp_tolerance);
736   MPFRNumber mpfrX(input.x, precision);
737   MPFRNumber mpfrY(input.y, precision);
738   FPBits<T> xbits(input.x);
739   FPBits<T> ybits(input.y);
740   MPFRNumber mpfr_result =
741       binary_operation_one_output(op, input.x, input.y, precision, rounding);
742   MPFRNumber mpfrMatchValue(libc_result);
743   std::stringstream ss;
744 
745   ss << "Input decimal: x: " << mpfrX.str() << " y: " << mpfrY.str() << '\n';
746   __llvm_libc::fputil::testing::describeValue("First input bits: ", input.x,
747                                               ss);
748   __llvm_libc::fputil::testing::describeValue("Second input bits: ", input.y,
749                                               ss);
750 
751   ss << "Libc result: " << mpfrMatchValue.str() << '\n'
752      << "MPFR result: " << mpfr_result.str() << '\n';
753   __llvm_libc::fputil::testing::describeValue(
754       "Libc floating point result bits: ", libc_result, ss);
755   __llvm_libc::fputil::testing::describeValue(
756       "              MPFR rounded bits: ", mpfr_result.as<T>(), ss);
757   ss << "ULP error: " << std::to_string(mpfr_result.ulp(libc_result)) << '\n';
758   OS << ss.str();
759 }
760 
761 template void explain_binary_operation_one_output_error<float>(
762     Operation, const BinaryInput<float> &, float, double, RoundingMode,
763     testutils::StreamWrapper &);
764 template void explain_binary_operation_one_output_error<double>(
765     Operation, const BinaryInput<double> &, double, double, RoundingMode,
766     testutils::StreamWrapper &);
767 template void explain_binary_operation_one_output_error<long double>(
768     Operation, const BinaryInput<long double> &, long double, double,
769     RoundingMode, testutils::StreamWrapper &);
770 
771 template <typename T>
772 void explain_ternary_operation_one_output_error(
773     Operation op, const TernaryInput<T> &input, T libc_result,
774     double ulp_tolerance, RoundingMode rounding, testutils::StreamWrapper &OS) {
775   unsigned int precision = get_precision<T>(ulp_tolerance);
776   MPFRNumber mpfrX(input.x, precision);
777   MPFRNumber mpfrY(input.y, precision);
778   MPFRNumber mpfrZ(input.z, precision);
779   FPBits<T> xbits(input.x);
780   FPBits<T> ybits(input.y);
781   FPBits<T> zbits(input.z);
782   MPFRNumber mpfr_result = ternary_operation_one_output(
783       op, input.x, input.y, input.z, precision, rounding);
784   MPFRNumber mpfrMatchValue(libc_result);
785   std::stringstream ss;
786 
787   ss << "Input decimal: x: " << mpfrX.str() << " y: " << mpfrY.str()
788      << " z: " << mpfrZ.str() << '\n';
789   __llvm_libc::fputil::testing::describeValue("First input bits: ", input.x,
790                                               ss);
791   __llvm_libc::fputil::testing::describeValue("Second input bits: ", input.y,
792                                               ss);
793   __llvm_libc::fputil::testing::describeValue("Third input bits: ", input.z,
794                                               ss);
795 
796   ss << "Libc result: " << mpfrMatchValue.str() << '\n'
797      << "MPFR result: " << mpfr_result.str() << '\n';
798   __llvm_libc::fputil::testing::describeValue(
799       "Libc floating point result bits: ", libc_result, ss);
800   __llvm_libc::fputil::testing::describeValue(
801       "              MPFR rounded bits: ", mpfr_result.as<T>(), ss);
802   ss << "ULP error: " << std::to_string(mpfr_result.ulp(libc_result)) << '\n';
803   OS << ss.str();
804 }
805 
806 template void explain_ternary_operation_one_output_error<float>(
807     Operation, const TernaryInput<float> &, float, double, RoundingMode,
808     testutils::StreamWrapper &);
809 template void explain_ternary_operation_one_output_error<double>(
810     Operation, const TernaryInput<double> &, double, double, RoundingMode,
811     testutils::StreamWrapper &);
812 template void explain_ternary_operation_one_output_error<long double>(
813     Operation, const TernaryInput<long double> &, long double, double,
814     RoundingMode, testutils::StreamWrapper &);
815 
816 template <typename T>
817 bool compare_unary_operation_single_output(Operation op, T input, T libc_result,
818                                            double ulp_tolerance,
819                                            RoundingMode rounding) {
820   unsigned int precision = get_precision<T>(ulp_tolerance);
821   MPFRNumber mpfr_result;
822   mpfr_result = unary_operation(op, input, precision, rounding);
823   double ulp = mpfr_result.ulp(libc_result);
824   return (ulp <= ulp_tolerance);
825 }
826 
827 template bool compare_unary_operation_single_output<float>(Operation, float,
828                                                            float, double,
829                                                            RoundingMode);
830 template bool compare_unary_operation_single_output<double>(Operation, double,
831                                                             double, double,
832                                                             RoundingMode);
833 template bool compare_unary_operation_single_output<long double>(
834     Operation, long double, long double, double, RoundingMode);
835 
836 template <typename T>
837 bool compare_unary_operation_two_outputs(Operation op, T input,
838                                          const BinaryOutput<T> &libc_result,
839                                          double ulp_tolerance,
840                                          RoundingMode rounding) {
841   int mpfrIntResult;
842   unsigned int precision = get_precision<T>(ulp_tolerance);
843   MPFRNumber mpfr_result = unary_operation_two_outputs(op, input, mpfrIntResult,
844                                                        precision, rounding);
845   double ulp = mpfr_result.ulp(libc_result.f);
846 
847   if (mpfrIntResult != libc_result.i)
848     return false;
849 
850   return (ulp <= ulp_tolerance);
851 }
852 
853 template bool compare_unary_operation_two_outputs<float>(
854     Operation, float, const BinaryOutput<float> &, double, RoundingMode);
855 template bool compare_unary_operation_two_outputs<double>(
856     Operation, double, const BinaryOutput<double> &, double, RoundingMode);
857 template bool compare_unary_operation_two_outputs<long double>(
858     Operation, long double, const BinaryOutput<long double> &, double,
859     RoundingMode);
860 
861 template <typename T>
862 bool compare_binary_operation_two_outputs(Operation op,
863                                           const BinaryInput<T> &input,
864                                           const BinaryOutput<T> &libc_result,
865                                           double ulp_tolerance,
866                                           RoundingMode rounding) {
867   int mpfrIntResult;
868   unsigned int precision = get_precision<T>(ulp_tolerance);
869   MPFRNumber mpfr_result = binary_operation_two_outputs(
870       op, input.x, input.y, mpfrIntResult, precision, rounding);
871   double ulp = mpfr_result.ulp(libc_result.f);
872 
873   if (mpfrIntResult != libc_result.i) {
874     if (op == Operation::RemQuo) {
875       if ((0x7 & mpfrIntResult) != (0x7 & libc_result.i))
876         return false;
877     } else {
878       return false;
879     }
880   }
881 
882   return (ulp <= ulp_tolerance);
883 }
884 
885 template bool compare_binary_operation_two_outputs<float>(
886     Operation, const BinaryInput<float> &, const BinaryOutput<float> &, double,
887     RoundingMode);
888 template bool compare_binary_operation_two_outputs<double>(
889     Operation, const BinaryInput<double> &, const BinaryOutput<double> &,
890     double, RoundingMode);
891 template bool compare_binary_operation_two_outputs<long double>(
892     Operation, const BinaryInput<long double> &,
893     const BinaryOutput<long double> &, double, RoundingMode);
894 
895 template <typename T>
896 bool compare_binary_operation_one_output(Operation op,
897                                          const BinaryInput<T> &input,
898                                          T libc_result, double ulp_tolerance,
899                                          RoundingMode rounding) {
900   unsigned int precision = get_precision<T>(ulp_tolerance);
901   MPFRNumber mpfr_result =
902       binary_operation_one_output(op, input.x, input.y, precision, rounding);
903   double ulp = mpfr_result.ulp(libc_result);
904 
905   return (ulp <= ulp_tolerance);
906 }
907 
908 template bool compare_binary_operation_one_output<float>(
909     Operation, const BinaryInput<float> &, float, double, RoundingMode);
910 template bool compare_binary_operation_one_output<double>(
911     Operation, const BinaryInput<double> &, double, double, RoundingMode);
912 template bool compare_binary_operation_one_output<long double>(
913     Operation, const BinaryInput<long double> &, long double, double,
914     RoundingMode);
915 
916 template <typename T>
917 bool compare_ternary_operation_one_output(Operation op,
918                                           const TernaryInput<T> &input,
919                                           T libc_result, double ulp_tolerance,
920                                           RoundingMode rounding) {
921   unsigned int precision = get_precision<T>(ulp_tolerance);
922   MPFRNumber mpfr_result = ternary_operation_one_output(
923       op, input.x, input.y, input.z, precision, rounding);
924   double ulp = mpfr_result.ulp(libc_result);
925 
926   return (ulp <= ulp_tolerance);
927 }
928 
929 template bool compare_ternary_operation_one_output<float>(
930     Operation, const TernaryInput<float> &, float, double, RoundingMode);
931 template bool compare_ternary_operation_one_output<double>(
932     Operation, const TernaryInput<double> &, double, double, RoundingMode);
933 template bool compare_ternary_operation_one_output<long double>(
934     Operation, const TernaryInput<long double> &, long double, double,
935     RoundingMode);
936 
937 } // namespace internal
938 
939 template <typename T> bool round_to_long(T x, long &result) {
940   MPFRNumber mpfr(x);
941   return mpfr.round_to_long(result);
942 }
943 
944 template bool round_to_long<float>(float, long &);
945 template bool round_to_long<double>(double, long &);
946 template bool round_to_long<long double>(long double, long &);
947 
948 template <typename T> bool round_to_long(T x, RoundingMode mode, long &result) {
949   MPFRNumber mpfr(x);
950   return mpfr.round_to_long(get_mpfr_rounding_mode(mode), result);
951 }
952 
953 template bool round_to_long<float>(float, RoundingMode, long &);
954 template bool round_to_long<double>(double, RoundingMode, long &);
955 template bool round_to_long<long double>(long double, RoundingMode, long &);
956 
957 template <typename T> T round(T x, RoundingMode mode) {
958   MPFRNumber mpfr(x);
959   MPFRNumber result = mpfr.rint(get_mpfr_rounding_mode(mode));
960   return result.as<T>();
961 }
962 
963 template float round<float>(float, RoundingMode);
964 template double round<double>(double, RoundingMode);
965 template long double round<long double>(long double, RoundingMode);
966 
967 } // namespace mpfr
968 } // namespace testing
969 } // namespace __llvm_libc
970