Skip to content

Commit 835b7b5

Browse files
committed
[libc] Alternative algorithm for decimal FP printf
The existing options for bin→dec float conversion are all based on the Ryū algorithm, which generates 9 output digits at a time using a table lookup. For users who can't afford the space cost of the table, the table-lookup subroutine is replaced with one that computes the needed table entry on demand, but the algorithm is otherwise unmodified. The performance problem with computing table entries on demand is that now you need to calculate a power of 10 for each 9 digits you output. But if you're calculating a custom power of 10 anyway, it's easier to just compute one, and multiply the _whole_ mantissa by it. This patch adds a header file alongside `float_dec_converter.h`, which replaces the whole Ryū system instead of just the table-lookup routine, implementing this alternative simpler algorithm. The result is accurate enough to satisfy (minimally) the accuracy demands of IEEE 754-2019 even in 128-bit long double. The new float128 test cases demonstrate this by testing the cases closest to the 39-digit rounding boundary. In my tests of generating 39 output digits (the maximum number supported by this algorithm) this code is also both faster and smaller than the USE_DYADIC_FLOAT version of the existing Ryū code.
1 parent 57466db commit 835b7b5

File tree

12 files changed

+911
-8
lines changed

12 files changed

+911
-8
lines changed

libc/config/config.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@
3030
"value": false,
3131
"doc": "Use the same mode for double and long double in printf."
3232
},
33+
"LIBC_CONF_PRINTF_FLOAT_TO_STR_USE_FLOAT320": {
34+
"value": false,
35+
"doc": "Use an alternative printf float implementation based on 320-bit floats"
36+
},
3337
"LIBC_CONF_PRINTF_DISABLE_FIXED_POINT": {
3438
"value": false,
3539
"doc": "Disable printing fixed point values in printf and friends."

libc/docs/configure.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ to learn about the defaults for your platform and target.
4343
- ``LIBC_CONF_PRINTF_DISABLE_WRITE_INT``: Disable handling of %n in printf format string.
4444
- ``LIBC_CONF_PRINTF_FLOAT_TO_STR_NO_SPECIALIZE_LD``: Use the same mode for double and long double in printf.
4545
- ``LIBC_CONF_PRINTF_FLOAT_TO_STR_USE_DYADIC_FLOAT``: Use dyadic float for faster and smaller but less accurate printf doubles.
46+
- ``LIBC_CONF_PRINTF_FLOAT_TO_STR_USE_FLOAT320``: Use an alternative printf float implementation based on 320-bit floats
4647
- ``LIBC_CONF_PRINTF_FLOAT_TO_STR_USE_MEGA_LONG_DOUBLE_TABLE``: Use large table for better printf long double performance.
4748
* **"pthread" options**
4849
- ``LIBC_CONF_RAW_MUTEX_DEFAULT_SPIN_COUNT``: Default number of spins before blocking if a mutex is in contention (default to 100).

libc/src/__support/CPP/algorithm.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ template <class T> LIBC_INLINE constexpr const T &min(const T &a, const T &b) {
2626
return (a < b) ? a : b;
2727
}
2828

29+
template <class T> LIBC_INLINE constexpr T abs(T a) { return a < 0 ? -a : a; }
30+
2931
template <class InputIt, class UnaryPred>
3032
LIBC_INLINE constexpr InputIt find_if_not(InputIt first, InputIt last,
3133
UnaryPred q) {

libc/src/__support/FPUtil/dyadic_float.h

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,40 @@
2626
namespace LIBC_NAMESPACE_DECL {
2727
namespace fputil {
2828

29+
// Decide whether to round up a UInt at a given bit position, based on
30+
// the current rounding mode. The assumption is that the caller is
31+
// going to make the integer `value >> rshift`, and then might need to
32+
// round it up by 1 depending on the value of the bits shifted off the
33+
// bottom.
34+
//
35+
// `logical_sign` causes the behavior of FE_DOWNWARD and FE_UPWARD to
36+
// be reversed, which is what you'd want if this is the mantissa of a
37+
// negative floating-point number.
38+
template <size_t Bits>
39+
LIBC_INLINE constexpr bool
40+
need_to_round_up(const LIBC_NAMESPACE::UInt<Bits> &value, size_t rshift,
41+
Sign logical_sign) {
42+
switch (quick_get_round()) {
43+
case FE_TONEAREST:
44+
if (rshift > 0 && rshift <= Bits && value.get_bit(rshift - 1)) {
45+
// We round up, unless the value is an exact halfway case and
46+
// the bit that will end up in the units place is 0, in which
47+
// case tie-break-to-even says round down.
48+
return value.get_bit(rshift) != 0 || (value << (Bits - rshift + 1)) != 0;
49+
} else {
50+
return false;
51+
}
52+
case FE_TOWARDZERO:
53+
return false;
54+
case FE_DOWNWARD:
55+
return logical_sign.is_neg() && (value << (Bits - rshift)) != 0;
56+
case FE_UPWARD:
57+
return logical_sign.is_pos() && (value << (Bits - rshift)) != 0;
58+
default:
59+
__builtin_unreachable();
60+
}
61+
}
62+
2963
// A generic class to perform computations of high precision floating points.
3064
// We store the value in dyadic format, including 3 fields:
3165
// sign : boolean value - false means positive, true means negative
@@ -101,6 +135,27 @@ template <size_t Bits> struct DyadicFloat {
101135
return exponent + (Bits - 1);
102136
}
103137

138+
// Produce a correctly rounded DyadicFloat from a too-large mantissa,
139+
// by shifting it down and rounding if necessary.
140+
template <size_t MantissaBits>
141+
LIBC_INLINE constexpr static DyadicFloat<Bits>
142+
round(Sign result_sign, int result_exponent,
143+
const LIBC_NAMESPACE::UInt<MantissaBits> &input_mantissa,
144+
size_t rshift) {
145+
MantissaType result_mantissa(input_mantissa >> rshift);
146+
if (need_to_round_up(input_mantissa, rshift, result_sign)) {
147+
++result_mantissa;
148+
if (result_mantissa == 0) {
149+
// Rounding up made the mantissa integer wrap round to 0,
150+
// carrying a bit off the top. So we've rounded up to the next
151+
// exponent.
152+
result_mantissa.set_bit(Bits - 1);
153+
++result_exponent;
154+
}
155+
}
156+
return DyadicFloat(result_sign, result_exponent, result_mantissa);
157+
}
158+
104159
#ifdef LIBC_TYPES_HAS_FLOAT16
105160
template <typename T, bool ShouldSignalExceptions>
106161
LIBC_INLINE constexpr cpp::enable_if_t<
@@ -374,6 +429,34 @@ template <size_t Bits> struct DyadicFloat {
374429

375430
return new_mant;
376431
}
432+
433+
LIBC_INLINE constexpr MantissaType
434+
as_mantissa_type_rounded(bool *overflowed = nullptr) const {
435+
if (mantissa.is_zero())
436+
return 0;
437+
438+
MantissaType new_mant = mantissa;
439+
if (exponent > 0) {
440+
new_mant <<= exponent;
441+
if (overflowed)
442+
*overflowed = (new_mant >> exponent) != mantissa;
443+
} else if (exponent < 0) {
444+
size_t shift = -exponent;
445+
new_mant >>= shift;
446+
if (need_to_round_up(mantissa, shift, sign))
447+
++new_mant;
448+
}
449+
450+
if (sign.is_neg()) {
451+
new_mant = (~new_mant) + 1;
452+
}
453+
454+
return new_mant;
455+
}
456+
457+
LIBC_INLINE constexpr DyadicFloat operator-() const {
458+
return DyadicFloat(sign.negate(), exponent, mantissa);
459+
}
377460
};
378461

379462
// Quick add - Add 2 dyadic floats with rounding toward 0 and then normalize the
@@ -433,6 +516,12 @@ LIBC_INLINE constexpr DyadicFloat<Bits> quick_add(DyadicFloat<Bits> a,
433516
return result.normalize();
434517
}
435518

519+
template <size_t Bits>
520+
LIBC_INLINE constexpr DyadicFloat<Bits> quick_sub(DyadicFloat<Bits> a,
521+
DyadicFloat<Bits> b) {
522+
return quick_add(a, -b);
523+
}
524+
436525
// Quick Mul - Slightly less accurate but efficient multiplication of 2 dyadic
437526
// floats with rounding toward 0 and then normalize the output:
438527
// result.exponent = a.exponent + b.exponent + Bits,
@@ -464,6 +553,96 @@ LIBC_INLINE constexpr DyadicFloat<Bits> quick_mul(const DyadicFloat<Bits> &a,
464553
return result;
465554
}
466555

556+
// Correctly rounded multiplication of 2 dyadic floats, assuming the
557+
// exponent remains within range.
558+
template <size_t Bits>
559+
LIBC_INLINE constexpr DyadicFloat<Bits>
560+
rounded_mul(const DyadicFloat<Bits> &a, const DyadicFloat<Bits> &b) {
561+
using DblMant = LIBC_NAMESPACE::UInt<(2 * Bits)>;
562+
Sign result_sign = (a.sign != b.sign) ? Sign::NEG : Sign::POS;
563+
int result_exponent = a.exponent + b.exponent + static_cast<int>(Bits);
564+
auto product = DblMant(a.mantissa) * DblMant(b.mantissa);
565+
// As in quick_mul(), renormalize by 1 bit manually rather than countl_zero
566+
if (product.get_bit(2 * Bits - 1) == 0) {
567+
product <<= 1;
568+
result_exponent -= 1;
569+
}
570+
571+
return DyadicFloat<Bits>::round(result_sign, result_exponent, product, Bits);
572+
}
573+
574+
// Approximate reciprocal - given a nonzero a, make a good approximation to 1/a.
575+
// The method is Newton-Raphson iteration, based on quick_mul.
576+
template <size_t Bits, typename = cpp::enable_if_t<(Bits >= 32)>>
577+
LIBC_INLINE constexpr DyadicFloat<Bits>
578+
approx_reciprocal(const DyadicFloat<Bits> &a) {
579+
// Given an approximation x to 1/a, a better one is x' = x(2-ax).
580+
//
581+
// You can derive this by using the Newton-Raphson formula with the function
582+
// f(x) = 1/x - a. But another way to see that it works is to say: suppose
583+
// that ax = 1-e for some small error e. Then ax' = ax(2-ax) = (1-e)(1+e) =
584+
// 1-e^2. So the error in x' is the square of the error in x, i.e. the number
585+
// of correct bits in x' is double the number in x.
586+
587+
// An initial approximation to the reciprocal
588+
DyadicFloat<Bits> x(Sign::POS, -32 - a.exponent - Bits,
589+
uint64_t(0xFFFFFFFFFFFFFFFF) /
590+
static_cast<uint64_t>(a.mantissa >> (Bits - 32)));
591+
592+
// The constant 2, which we'll need in every iteration
593+
DyadicFloat<Bits> two(Sign::POS, 1, 1);
594+
595+
// We expect at least 31 correct bits from our 32-bit starting approximation
596+
size_t ok_bits = 31;
597+
598+
// The number of good bits doubles in each iteration, except that rounding
599+
// errors introduce a little extra each time. Subtract a bit from our
600+
// accuracy assessment to account for that.
601+
while (ok_bits < Bits) {
602+
x = quick_mul(x, quick_sub(two, quick_mul(a, x)));
603+
ok_bits = 2 * ok_bits - 1;
604+
}
605+
606+
return x;
607+
}
608+
609+
// Correctly rounded division of 2 dyadic floats, assuming the
610+
// exponent remains within range.
611+
template <size_t Bits>
612+
LIBC_INLINE constexpr DyadicFloat<Bits>
613+
rounded_div(const DyadicFloat<Bits> &af, const DyadicFloat<Bits> &bf) {
614+
using DblMant = LIBC_NAMESPACE::UInt<(Bits * 2 + 64)>;
615+
616+
// Make an approximation to the quotient as a * (1/b). Both the
617+
// multiplication and the reciprocal are a bit sloppy, which doesn't
618+
// matter, because we're going to correct for that below.
619+
auto qf = fputil::quick_mul(af, fputil::approx_reciprocal(bf));
620+
621+
// Switch to BigInt and stop using quick_add and quick_mul: now
622+
// we're working in exact integers so as to get the true remainder.
623+
DblMant a = af.mantissa, b = bf.mantissa, q = qf.mantissa;
624+
q <<= 2; // leave room for a round bit, even if exponent decreases
625+
a <<= af.exponent - bf.exponent - qf.exponent + 2;
626+
DblMant qb = q * b;
627+
if (qb < a) {
628+
DblMant too_small = a - b;
629+
while (qb <= too_small) {
630+
qb += b;
631+
++q;
632+
}
633+
} else {
634+
while (qb > a) {
635+
qb -= b;
636+
--q;
637+
}
638+
}
639+
640+
DyadicFloat<(Bits * 2)> qbig(qf.sign, qf.exponent - 2, q);
641+
auto qfinal = DyadicFloat<Bits>::round(qbig.sign, qbig.exponent + Bits,
642+
qbig.mantissa, Bits);
643+
return qfinal;
644+
}
645+
467646
// Simple polynomial approximation.
468647
template <size_t Bits>
469648
LIBC_INLINE constexpr DyadicFloat<Bits>

libc/src/__support/big_int.h

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -936,6 +936,18 @@ struct BigInt {
936936
// Return the i-th word of the number.
937937
LIBC_INLINE constexpr WordType &operator[](size_t i) { return val[i]; }
938938

939+
// Return the i-th bit of the number.
940+
LIBC_INLINE constexpr bool get_bit(size_t i) const {
941+
const size_t word_index = i / WORD_SIZE;
942+
return 1 & (val[word_index] >> (i % WORD_SIZE));
943+
}
944+
945+
// Set the i-th bit of the number.
946+
LIBC_INLINE constexpr void set_bit(size_t i) {
947+
const size_t word_index = i / WORD_SIZE;
948+
val[word_index] |= WordType(1) << (i % WORD_SIZE);
949+
}
950+
939951
private:
940952
LIBC_INLINE friend constexpr int cmp(const BigInt &lhs, const BigInt &rhs) {
941953
constexpr auto compare = [](WordType a, WordType b) {
@@ -989,12 +1001,6 @@ struct BigInt {
9891001
LIBC_INLINE constexpr void clear_msb() {
9901002
val.back() &= mask_trailing_ones<WordType, WORD_SIZE - 1>();
9911003
}
992-
993-
LIBC_INLINE constexpr void set_bit(size_t i) {
994-
const size_t word_index = i / WORD_SIZE;
995-
val[word_index] |= WordType(1) << (i % WORD_SIZE);
996-
}
997-
9981004
LIBC_INLINE constexpr static Division divide_unsigned(const BigInt &dividend,
9991005
const BigInt &divider) {
10001006
BigInt remainder = dividend;

libc/src/__support/sign.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ struct Sign {
2929
static const Sign POS;
3030
static const Sign NEG;
3131

32+
LIBC_INLINE constexpr Sign negate() const { return Sign(!is_negative); }
33+
3234
private:
3335
LIBC_INLINE constexpr explicit Sign(bool is_negative)
3436
: is_negative(is_negative) {}

libc/src/stdio/printf_core/CMakeLists.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ endif()
1616
if(LIBC_CONF_PRINTF_FLOAT_TO_STR_NO_SPECIALIZE_LD)
1717
list(APPEND printf_config_copts "-DLIBC_COPT_FLOAT_TO_STR_NO_SPECIALIZE_LD")
1818
endif()
19+
if(LIBC_CONF_PRINTF_FLOAT_TO_STR_USE_FLOAT320)
20+
list(APPEND printf_config_copts "-DLIBC_COPT_FLOAT_TO_STR_USE_FLOAT320")
21+
endif()
1922
if(LIBC_CONF_PRINTF_DISABLE_FIXED_POINT)
2023
list(APPEND printf_config_copts "-DLIBC_COPT_PRINTF_DISABLE_FIXED_POINT")
2124
endif()

libc/src/stdio/printf_core/converter_atlas.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@
2626
// defines convert_float_decimal
2727
// defines convert_float_dec_exp
2828
// defines convert_float_dec_auto
29+
#ifdef LIBC_COPT_FLOAT_TO_STR_USE_FLOAT320
30+
#include "src/stdio/printf_core/float_dec_converter_limited.h"
31+
#else
2932
#include "src/stdio/printf_core/float_dec_converter.h"
33+
#endif
3034
// defines convert_float_hex_exp
3135
#include "src/stdio/printf_core/float_hex_converter.h"
3236
#endif // LIBC_COPT_PRINTF_DISABLE_FLOAT

0 commit comments

Comments
 (0)