https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129108

            Bug ID: 129108
           Summary: wrong code: float, double, long double and _Float128
                    to _Decimal128 conversions of some exact integers
                    above 10^34 are one ulp too small in directed decimal
                    rounding modes (libbid multiplies a truncated product
                    by 10)
           Product: gcc
           Version: 16.2.0
            Status: UNCONFIRMED
          Keywords: dfp, wrong-code
          Severity: normal
          Priority: P3
         Component: libgcc
          Assignee: unassigned at gcc dot gnu.org
          Reporter: mt at debian dot org
  Target Milestone: ---

At run time, conversions from float, double, long double and _Float128
to _Decimal128 give a result one ulp too small in magnitude for some
integers above 10^34 that are exactly representable in _Decimal128,
when the decimal rounding mode is downward, upward or toward zero.  In
the two round-to-nearest modes the value is right.

The decimal rounding mode is set with libgcc's __dfp_set_round, as
gcc.dg/dfp/dfp-round.h does (GCC ignores #pragma STDC FENV_DEC_ROUND,
and glibc does not provide fe_dec_setround, which is in libdfp).

$ cat t.c
/* Conversions of exact integers above 10^34 from binary floating types
   to _Decimal128 in the directed decimal rounding modes.
   Assumes a little-endian target with BID decimal floating point.  */
#include <stdio.h>
#include <string.h>

/* libgcc's decimal rounding mode, as in gcc.dg/dfp/dfp-round.h.  */
extern void __dfp_set_round (int);
static const char *const mode[] = { "tonearest", "downward", "upward",
                                    "towardzero", "tonearestfromzero" };

/* The exact values, c * 10^q with 10^33 <= c < 10^34:
   f = 7007572518061652131473775319318528E2
   d = 9302463557808195107998157141704704E7
   q = 6837911965441426492985327554037472E2
   x = 5413282904202223559069829192220672E3 (x87 only)  */
volatile float f = 0x1.0decp+119f;
volatile double d = 0x1.115ff51f5fbp+136;
volatile _Float128 q = 0x1.0763048d9f80d935e1aa77e1d95fp+119f128;
#if __LDBL_MANT_DIG__ == 64
volatile long double x = 0x8.251ee81099a7e44p+119L;
#endif

static int bad;

static void
show (const char *type, _Decimal128 got, _Decimal128 want)
{
  unsigned long long w[2];
  unsigned __int128 c;
  char buf[40], *p = buf + sizeof buf;
  memcpy (w, &got, 16);
  /* Coefficient and exponent (results here are not in the 11 form).  */
  c = ((unsigned __int128) (w[1] & 0x1ffffffffffffULL) << 64) | w[0];
  *--p = 0;
  do
    *--p = '0' + c % 10;
  while ((c /= 10) != 0);
  printf ("  %-10s %016llx%016llx = %c%sE%d%s\n", type, w[1], w[0],
          w[1] >> 63 ? '-' : '+', p, (int) ((w[1] >> 49) & 0x3fff) - 6176,
          got == want ? "" : "  WRONG, one ulp too small");
  bad |= got != want;
}

int
main (void)
{
  for (int m = 0; m < 5; m++)
    {
      /* volatile, so that the conversions stay between the two calls.  */
      volatile _Decimal128 r[8];
      __dfp_set_round (m);
      r[0] = f;         /* __bid_extendsftd */
      r[1] = -f;
      r[2] = d;         /* __bid_extenddftd */
      r[3] = -d;
      r[4] = q;         /* __bid_extendtftd */
      r[5] = -q;
#if __LDBL_MANT_DIG__ == 64
      r[6] = x;         /* __bid_extendxftd */
      r[7] = -x;
#endif
      __dfp_set_round (0);
      printf ("%s:\n", mode[m]);
      show ("float", r[0], 7007572518061652131473775319318528E2DL);
      show ("-float", r[1], -7007572518061652131473775319318528E2DL);
      show ("double", r[2], 9302463557808195107998157141704704E7DL);
      show ("-double", r[3], -9302463557808195107998157141704704E7DL);
      show ("_Float128", r[4], 6837911965441426492985327554037472E2DL);
      show ("-_Float128", r[5], -6837911965441426492985327554037472E2DL);
#if __LDBL_MANT_DIG__ == 64
      show ("x87", r[6], 5413282904202223559069829192220672E3DL);
      show ("-x87", r[7], -5413282904202223559069829192220672E3DL);
#endif
    }
  return bad;
}

$ gcc -O0 t.c -o t && ./t; echo $?
tonearest:
  float      30455980000000000000000000000000 =
+7007572518061652131473775319318528E2
  -float     b0455980000000000000000000000000 =
-7007572518061652131473775319318528E2
  double     304fcaa598e000000000000000000000 =
+9302463557808195107998157141704704E7
  -double    b04fcaa598e000000000000000000000 =
-9302463557808195107998157141704704E7
  _Float128  3045512295302853018ca5f8eb5e86e0 =
+6837911965441426492985327554037472E2
  -_Float128 b045512295302853018ca5f8eb5e86e0 =
-6837911965441426492985327554037472E2
downward:
  float      3045597fffffffffffffffffffffffff =
+7007572518061652131473775319318527E2  WRONG, one ulp too small
  -float     b0455980000000000000000000000000 =
-7007572518061652131473775319318528E2
  double     304fcaa598dfffffffffffffffffffff =
+9302463557808195107998157141704703E7  WRONG, one ulp too small
  -double    b04fcaa598e000000000000000000000 =
-9302463557808195107998157141704704E7
  _Float128  3045512295302853018ca5f8eb5e86df =
+6837911965441426492985327554037471E2  WRONG, one ulp too small
  -_Float128 b045512295302853018ca5f8eb5e86e0 =
-6837911965441426492985327554037472E2
upward:
  float      30455980000000000000000000000000 =
+7007572518061652131473775319318528E2
  -float     b045597fffffffffffffffffffffffff =
-7007572518061652131473775319318527E2  WRONG, one ulp too small
  double     304fcaa598e000000000000000000000 =
+9302463557808195107998157141704704E7
  -double    b04fcaa598dfffffffffffffffffffff =
-9302463557808195107998157141704703E7  WRONG, one ulp too small
  _Float128  3045512295302853018ca5f8eb5e86e0 =
+6837911965441426492985327554037472E2
  -_Float128 b045512295302853018ca5f8eb5e86df =
-6837911965441426492985327554037471E2  WRONG, one ulp too small
towardzero:
  float      3045597fffffffffffffffffffffffff =
+7007572518061652131473775319318527E2  WRONG, one ulp too small
  -float     b045597fffffffffffffffffffffffff =
-7007572518061652131473775319318527E2  WRONG, one ulp too small
  double     304fcaa598dfffffffffffffffffffff =
+9302463557808195107998157141704703E7  WRONG, one ulp too small
  -double    b04fcaa598dfffffffffffffffffffff =
-9302463557808195107998157141704703E7  WRONG, one ulp too small
  _Float128  3045512295302853018ca5f8eb5e86df =
+6837911965441426492985327554037471E2  WRONG, one ulp too small
  -_Float128 b045512295302853018ca5f8eb5e86df =
-6837911965441426492985327554037471E2  WRONG, one ulp too small
tonearestfromzero:
  float      30455980000000000000000000000000 =
+7007572518061652131473775319318528E2
  -float     b0455980000000000000000000000000 =
-7007572518061652131473775319318528E2
  double     304fcaa598e000000000000000000000 =
+9302463557808195107998157141704704E7
  -double    b04fcaa598e000000000000000000000 =
-9302463557808195107998157141704704E7
  _Float128  3045512295302853018ca5f8eb5e86e0 =
+6837911965441426492985327554037472E2
  -_Float128 b045512295302853018ca5f8eb5e86e0 =
-6837911965441426492985327554037472E2
1

This is aarch64 (GCC 15.2.0 and 16.2.0), where long double is
_Float128.  The output is the same at -O2.  On x86_64 (GCC 16.2.0) the
output has the same lines and two x87 lines per mode; those in the
directed modes are:

downward:
  x87        30470ae53c6c9eee93ffffffffffffff =
+5413282904202223559069829192220671E3  WRONG, one ulp too small
  -x87       b0470ae53c6c9eee9400000000000000 =
-5413282904202223559069829192220672E3
upward:
  x87        30470ae53c6c9eee9400000000000000 =
+5413282904202223559069829192220672E3
  -x87       b0470ae53c6c9eee93ffffffffffffff =
-5413282904202223559069829192220671E3  WRONG, one ulp too small
towardzero:
  x87        30470ae53c6c9eee93ffffffffffffff =
+5413282904202223559069829192220671E3  WRONG, one ulp too small
  -x87       b0470ae53c6c9eee93ffffffffffffff =
-5413282904202223559069829192220671E3  WRONG, one ulp too small

The conversion of the _Float128 value also raises the decimal inexact
flag (__dfp_test_except (FE_INEXACT) is nonzero after it) in all five
modes, including the two in which the value is right.

Expected result
---------------
Each operand is an integer that is exactly representable in
_Decimal128.  For example
0x1.0763048d9f80d935e1aa77e1d95fp+119 = 683791196544142649298532755403747200
= 6837911965441426492985327554037472 * 10^2 (checked with exact rational
arithmetic, as are the other three values in the comment).

C23 (N3220) 6.3.1.5p1: "When a value of real floating type is converted
to a real floating type, if the value being converted can be represented
exactly in the new type, it is unchanged."  The result therefore does
not depend on the rounding mode.  The coefficient has 34 digits and does
not end in 0, so the value has exactly one encoding:
6837911965441426492985327554037472E2, BID 3045512295302853018ca5f8eb5e86e0
(b045... for the negative value).  libgcc returns the representable
neighbour below, 6837911965441426492985327554037471E2 (...86df), in
exactly the modes that round toward zero for that sign: downward for
positive values, upward for negative values, and toward zero.

Scope
-----
- All four libgcc conversions to _Decimal128 are affected:
  __bid_extendsftd, __bid_extenddftd, __bid_extendxftd and
  __bid_extendtftd, i.e. binary32_to_bid128, binary64_to_bid128,
  binary80_to_bid128 and binary128_to_bid128 in bid_binarydecimal.c.
  The conversions to _Decimal32 and _Decimal64 do not contain the code
  described below (a breakpoint table selects their exponent); I did
  not test them here.
- Only exact results with a positive decimal exponent can fail, i.e.
  integers x = c * 10^q with 10^33 <= c < 10^34 and q >= 1.  Exact
  integers below 10^34 and exact values c / 2^a are handled by the
  special cases at the start of the functions.  Such integers exist up
  to FLT_MAX for float (q <= 5), below 10^56 for double (q <= 22), below
  10^61 for x87 (q <= 27) and below 10^82 for _Float128 (q <= 48).
- A sample of 2000 random such values per format (each in the five modes
  and with random sign) gives, per format, 221 to 261 failing values
  (11 to 13 per cent), each failing in exactly the two truncating modes
  for its sign, always one ulp toward zero.  In a differential test of
  413,772 conversions against an exact oracle, including inexact
  conversions, every mismatch in this direction is of this kind.

Root cause
----------
libgcc/config/libbid/bid_binarydecimal.c, binary128_to_bid128 (lines
147338-147350 on master).  binary32_to_bid128 (146834), binary64_to_bid128
(147003) and binary80_to_bid128 (147172) normalise the input to a 113-bit
significand and then run the same code:

// Make adjustive shift, ignoring the lower 128 bits

  e = -(241 + e + f);
  srl256 (z.w[5], z.w[4], z.w[3], z.w[2], e);

// Now test against 10^33 and so decide on adjustment
// I feel there ought to be a smarter way of doing the multiplication

  if (lt128 (z.w[5], z.w[4], 54210108624275ull, 4089650035136921600ull)) {
    __mul_10x256_to_256 (z.w[5], z.w[4], z.w[3], z.w[2], z.w[5], z.w[4],
                         z.w[3], z.w[2]);
    e_out = e_out - 1;
  }

z is the 384-bit product of the significand and a power of ten from
innertable_sig/outertable_sig.  z.w[5]:z.w[4] is the provisional
coefficient and z.w[3]:z.w[2] are the round/sticky words; z.w[1] and
z.w[0] are dropped.  The decimal exponent e_out is estimated from the
binary exponent alone and can be one too large; the provisional
coefficient is then below 10^33 and the code multiplies the truncated
256 bits by 10.

For the _Float128 value above, the estimate gives exponent 3 and the
multiplier innertable_sig[61] (about 10^-3).  The provisional result is
683791196544142649298532755403747 with round/sticky words
0x33333333333333333333333333333333, the fraction 0.2 truncated to 128
bits.  Times 10 this becomes 6837911965441426492985327554037471 with
round/sticky words 0xfffffffffffffffffffffffffffffffe, instead of
6837911965441426492985327554037472 with zero round/sticky words.  The
two round-to-nearest modes, and the directed mode that rounds away from
zero for the sign, round this up to the right value; the truncating
modes (roundbound_128 entries {~0ull, ~0ull}) keep the coefficient one
too small, and the nonzero round/sticky words also set the inexact
flag.

The multipliers are never below the exact power of ten, and exceed it
by a relative 2^-250 at most (I checked all 32,879 exponents from -16607
to 16271), so without the multiplication by 10 an exact result gets zero
round/sticky words.  Through the
multiplication by 10, an exact result is wrong in the truncating modes
exactly when its coefficient is not a multiple of 5: the truncated
fraction is (c mod 10) / 10, which has no finite binary expansion unless
c mod 10 is 0 or 5.  A model of this path in Python (tables parsed from
the source) predicts exactly the 6,858 distinct mismatches in our test
sets (format, rounding mode and input), with no extra and no missing
cases.

The code is from the 2007 libbid import (200359e888d1; the file was
renamed and reindented as bid_binarydecimal.c in b2a00c898466,
2007-09-27, and these functions, the tables and srl256 have not changed
since).  The libbid update of 2024-03-27 (affd77d3fe7b) did not change
them.  Intel's Decimal Floating-Point Math Library fixed this by 2011:
version 2.0 (the oldest version on netlib) and the current version 2.0
Update 5 (September 2026) shift and multiply by 10 all six words of z
(LIBRARY/src/bid_binarydecimal.c in IntelRDFPMathLib20U5, lines 145-152,
203-211 and 147389-147398):

  e = -(241 + e + f);
  srl384_short (z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0], e);
  ...
  if (lt128 (z.w[5], z.w[4], 54210108624275ull, 4089650035136921600ull)) {
    __mul_10x384_to_384 (z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0],
                         z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0]);
    e_out = e_out - 1;
  }

With all 384 bits, truncation loses less than 10 units of 2^-256 (of a
coefficient unit) after the multiplication by 10.  The multipliers used
for exact results (innertable_sig[15..63]) exceed the exact power of ten
by a relative 2^-260.4 to 2^-255.2.  That excess is at least 2^101 of
those units, so it outweighs the truncation, and after the
multiplication by 10 it is still less than one unit of the round/sticky
words (2^128 of those units).  Exact results therefore come out with
zero round/sticky words.

Suggested fix
-------------
Port Intel's change (the macros are copied from Intel's library; the
(void)c5 matches GCC's (void)c3 in __mul_10x256_to_256):

--- a/libgcc/config/libbid/bid_binarydecimal.c
+++ b/libgcc/config/libbid/bid_binarydecimal.c
@@ -87,6 +87,17 @@
    (x3) = (x3) >> (c)                                           \
   )

+// Similarly for 6-part result
+
+#define srl384_short(x5,x4,x3,x2,x1,x0,c)                       \
+  ((x0) = ((x1) << (64 - (c))) + ((x0) >> (c)),                 \
+   (x1) = ((x2) << (64 - (c))) + ((x1) >> (c)),                 \
+   (x2) = ((x3) << (64 - (c))) + ((x2) >> (c)),                 \
+   (x3) = ((x4) << (64 - (c))) + ((x3) >> (c)),                 \
+   (x4) = ((x5) << (64 - (c))) + ((x4) >> (c)),                 \
+   (x5) = (x5) >> (c)                                           \
+  )
+
 // Compare "<" two 2-part unsigned integers

 #define lt128(x_hi,x_lo,y_hi,y_lo)                              \
@@ -135,6 +146,19 @@
   (void)c3;                                                    \
 }

+// Likewise a 384-bit number
+
+#define __mul_10x384_to_384(p5,p4,p3,p2,p1,p0,a5,a4,a3,a2,a1,a0)  \
+{ unsigned long long c0,c1,c2,c3,c4,c5;                         \
+  __mul_10x64(p0,c0,a0,0ull);                                   \
+  __mul_10x64(p1,c1,a1,c0);                                     \
+  __mul_10x64(p2,c2,a2,c1);                                     \
+  __mul_10x64(p3,c3,a3,c2);                                     \
+  __mul_10x64(p4,c4,a4,c3);                                     \
+  __mul_10x64(p5,c5,a5,c4);                                     \
+  (void)c5;                                                    \
+}
+
 // Set up indices for low and high parts, depending on the endian-ness.
 // Note that this only affects 128-bit input and output operands, not any
 // of the internal workings, where w[0] is always the low-order part.
@@ -146834,14 +146858,14 @@
 // Make adjustive shift, ignoring the lower 128 bits

   e = -(241 + e + f);
-  srl256 (z.w[5], z.w[4], z.w[3], z.w[2], e);
+  srl384_short (z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0], e);

 // Now test against 10^33 and so decide on adjustment
 // I feel there ought to be a smarter way of doing the multiplication

   if (lt128 (z.w[5], z.w[4], 54210108624275ull, 4089650035136921600ull)) {
-    __mul_10x256_to_256 (z.w[5], z.w[4], z.w[3], z.w[2], z.w[5], z.w[4],
-                         z.w[3], z.w[2]);
+    __mul_10x384_to_384 (z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0],
+                         z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0]);
     e_out = e_out - 1;
   }
 // Set up provisional results
@@ -147003,14 +147027,14 @@
 // Make adjustive shift, ignoring the lower 128 bits

   e = -(241 + e + f);
-  srl256 (z.w[5], z.w[4], z.w[3], z.w[2], e);
+  srl384_short (z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0], e);

 // Now test against 10^33 and so decide on adjustment
 // I feel there ought to be a smarter way of doing the multiplication

   if (lt128 (z.w[5], z.w[4], 54210108624275ull, 4089650035136921600ull)) {
-    __mul_10x256_to_256 (z.w[5], z.w[4], z.w[3], z.w[2], z.w[5], z.w[4],
-                         z.w[3], z.w[2]);
+    __mul_10x384_to_384 (z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0],
+                         z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0]);
     e_out = e_out - 1;
   }
 // Set up provisional results
@@ -147172,14 +147196,14 @@
 // Make adjustive shift, ignoring the lower 128 bits

   e = -(241 + e + f);
-  srl256 (z.w[5], z.w[4], z.w[3], z.w[2], e);
+  srl384_short (z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0], e);

 // Now test against 10^33 and so decide on adjustment
 // I feel there ought to be a smarter way of doing the multiplication

   if (lt128 (z.w[5], z.w[4], 54210108624275ull, 4089650035136921600ull)) {
-    __mul_10x256_to_256 (z.w[5], z.w[4], z.w[3], z.w[2], z.w[5], z.w[4],
-                         z.w[3], z.w[2]);
+    __mul_10x384_to_384 (z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0],
+                         z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0]);
     e_out = e_out - 1;
   }
 // Set up provisional results
@@ -147338,14 +147362,14 @@
 // Make adjustive shift, ignoring the lower 128 bits

   e = -(241 + e + f);
-  srl256 (z.w[5], z.w[4], z.w[3], z.w[2], e);
+  srl384_short (z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0], e);

 // Now test against 10^33 and so decide on adjustment
 // I feel there ought to be a smarter way of doing the multiplication

   if (lt128 (z.w[5], z.w[4], 54210108624275ull, 4089650035136921600ull)) {
-    __mul_10x256_to_256 (z.w[5], z.w[4], z.w[3], z.w[2], z.w[5], z.w[4],
-                         z.w[3], z.w[2]);
+    __mul_10x384_to_384 (z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0],
+                         z.w[5], z.w[4], z.w[3], z.w[2], z.w[1], z.w[0]);
     e_out = e_out - 1;
   }
 // Set up provisional results

The shift count e is between 1 and 63 at these call sites for all
reachable exponents (checked for -16607 to 16271), as srl384_short
requires.

I built bid_binarydecimal.c from master with and without this patch as
a separate object (gcc -O2 -DIN_LIBGCC2 -DENABLE_DECIMAL_BID_FORMAT=1,
on aarch64 with GCC 15.2 and for x86_64 with GCC 16.2) and linked it
into the test case and into a driver for the differential test.  The
unpatched copy gives the same results as libgcc for every case compared.
With the patch, the test case passes (also on x86_64 with x87), and all
binary-to-_Decimal128 cases of our test sets match the exact results:
151,549 on aarch64 (float, double, _Float128) and 222,942 on x86_64
(also 71,393 x87 cases), each in the five rounding modes.  The results
in the other direction do not change.  With the patch, the conversion
of the _Float128 example no longer sets the inexact flag.

A possible testsuite test (gcc.dg/dfp), which aborts with the current
libgcc and passes with the patch:

/* { dg-do run } */
/* { dg-options "-O2" } */
/* { dg-require-effective-target dfp_bid } */

/* Exact conversions to _Decimal128 must not depend on the decimal
   rounding mode.  f = 7007572518061652131473775319318528E2 and
   d = 9302463557808195107998157141704704E7 exactly.  */

#include "dfp-round.h"

volatile float f = 0x1.0decp+119f;
volatile double d = 0x1.115ff51f5fbp+136;

int
main (void)
{
  volatile _Decimal128 rf, rd, rnf, rnd;
  DFP_SETROUND (FE_DEC_TOWARDZERO);
  rf = f;
  rd = d;
  DFP_SETROUND (FE_DEC_UPWARD);
  rnf = -f;
  rnd = -d;
  DFP_SETROUND (FE_DEC_TONEAREST);
  if (rf != 7007572518061652131473775319318528E2DL
      || rd != 9302463557808195107998157141704704E7DL
      || rnf != -7007572518061652131473775319318528E2DL
      || rnd != -9302463557808195107998157141704704E7DL)
    __builtin_abort ();
  return 0;
}

(dfp_bid because DPD targets convert binary to decimal through sprintf,
which has its own rounding problems, PR 97635.)

Reply via email to