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

            Bug ID: 129109
           Summary: wrong code: _Decimal128 to _Float128 conversion rounds
                    some subnormal results in [2^-16446, 2^-16445) to the
                    wrong neighbour (shift by 64 in libbid
                    bid128_to_binary128)
           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, the conversion from _Decimal128 to _Float128 (long double
on aarch64) gives the wrong one of the two neighbouring values for some
operands whose result is subnormal and lies in [2^-16446, 2^-16445),
i.e. has a 49-bit significand.  This happens in round to nearest (the
default), for values close to a representable number or to a halfway
point: values just below a representable number are rounded down, and
values just below a halfway point are rounded up.  GCC's constant
folding of the same conversions is correct.

$ cat t.c
/* _Decimal128 to binary128 conversions with subnormal results in
   [2^-16446, 2^-16445), round to nearest.
   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" };

/* With ulp = 2^-16494: a is 2^-61.5 ulp below 0x1641aa0000000 ulp, and
   b is 2^-62.5 ulp below the midpoint (0x12084afe23481 + 1/2) ulp.  */
volatile _Decimal128 a = 2535293258477612123583382583422255E-4984DL;
volatile _Decimal128 b = 2054114851702009675624553072449140E-4984DL;

static const _Float128 a_lo = 0x1.641a9fffffffp-16446f128;
static const _Float128 a_hi = 0x1.641aap-16446f128;
static const _Float128 b_lo = 0x1.2084afe23481p-16446f128;
static const _Float128 b_hi = 0x1.2084afe23482p-16446f128;

/* Folded by GCC (round to nearest).  */
static const _Float128 fa = 2535293258477612123583382583422255E-4984DL;
static const _Float128 fb = 2054114851702009675624553072449140E-4984DL;

static int bad;

static void
show (const char *name, _Float128 got, _Float128 want)
{
  unsigned long long w[2], e[2];
  memcpy (w, &got, 16);
  memcpy (e, &want, 16);
  printf ("  %s %016llx%016llx", name, w[1], w[0]);
  if (got != want)
    printf ("  WRONG, expected %016llx%016llx", e[1], e[0]);
  printf ("\n");
  bad |= got != want;
}

int
main (void)
{
  printf ("folded:\n");
  show ("a ", fa, a_hi);
  show ("b ", fb, b_lo);
  for (int m = 0; m < 5; m++)
    {
      /* volatile, so that the conversions stay between the two calls.  */
      volatile _Float128 r[4];
      __dfp_set_round (m);
      r[0] = a;         /* __bid_trunctdtf */
      r[1] = -a;
      r[2] = b;
      r[3] = -b;
      __dfp_set_round (0);
      int near = m == 0 || m == 4;  /* round to nearest */
      printf ("%s:\n", mode[m]);
      show ("a ", r[0], near || m == 2 ? a_hi : a_lo);
      show ("-a", r[1], near || m == 1 ? -a_hi : -a_lo);
      show ("b ", r[2], m == 2 ? b_hi : b_lo);
      show ("-b", r[3], m == 1 ? -b_hi : -b_lo);
    }
  return bad;
}

$ gcc -O0 t.c -o t && ./t; echo $?
folded:
  a  00000000000000000001641aa0000000
  b  000000000000000000012084afe23481
tonearest:
  a  00000000000000000001641a9fffffff  WRONG, expected
00000000000000000001641aa0000000
  -a 80000000000000000001641a9fffffff  WRONG, expected
80000000000000000001641aa0000000
  b  000000000000000000012084afe23482  WRONG, expected
000000000000000000012084afe23481
  -b 800000000000000000012084afe23482  WRONG, expected
800000000000000000012084afe23481
downward:
  a  00000000000000000001641a9fffffff
  -a 80000000000000000001641aa0000000
  b  000000000000000000012084afe23481
  -b 800000000000000000012084afe23482
upward:
  a  00000000000000000001641aa0000000
  -a 80000000000000000001641a9fffffff
  b  000000000000000000012084afe23482
  -b 800000000000000000012084afe23481
towardzero:
  a  00000000000000000001641a9fffffff
  -a 80000000000000000001641a9fffffff
  b  000000000000000000012084afe23481
  -b 800000000000000000012084afe23481
tonearestfromzero:
  a  00000000000000000001641a9fffffff  WRONG, expected
00000000000000000001641aa0000000
  -a 80000000000000000001641a9fffffff  WRONG, expected
80000000000000000001641aa0000000
  b  000000000000000000012084afe23482  WRONG, expected
000000000000000000012084afe23481
  -b 800000000000000000012084afe23482  WRONG, expected
800000000000000000012084afe23481
1

The output is the same at -O2, with GCC 15.2.0 and 16.2.0 on aarch64
and with GCC 16.2.0 for x86_64.  libbid rounds this conversion by the
decimal rounding mode, so the test sets that mode; the first iteration
(tonearest) is the default state.

Expected result
---------------
Exact rational arithmetic (Python fractions), with ulp = 2^-16494, the
spacing of binary128 subnormals:

  a = 2535293258477612123583382583422255E-4984
    = (0x1641a9fffffff + 1 - 2^-61.53) ulp
  b = 2054114851702009675624553072449140E-4984
    = (0x12084afe23481 + 1/2 - 2^-62.55) ulp

Both are below 2^-16382, so the results are subnormal.  The neighbours of
a are 0x1641a9fffffff ulp and 0x1641aa0000000 ulp (0x1.641a9fffffffp-16446
and 0x1.641aap-16446); a is 2^-61.53 ulp from the upper one, so rounding
to nearest gives 0x1641aa0000000 ulp, bits
00000000000000000001641aa0000000.  The neighbours of b are
0x12084afe23481 ulp and 0x12084afe23482 ulp; b is below their midpoint,
so rounding to nearest gives 0x12084afe23481 ulp, bits
000000000000000000012084afe23481.  These are the values GCC folds to.
In each case libgcc returns the other neighbour.

C23 (N3220) F.3 binds casts and implicit conversions between floating
types to the ISO/IEC 60559 convertFormat operation, which is correctly
rounded, and GCC documents for 6.3.1.5 that "C99 Annex F is followed"
(implement-c.texi).  The directed-mode results in the output are
correct.

Scope
-----
- Only results in [2^-16446, 2^-16445) are affected, i.e. decimal
  values from about 1.8225997659412373E-4951 to 3.6451995318824746E-4951.
  There the round word of the computation is off by m, the 49-bit
  significand of the result (see below).  A value whose fraction f (in
  ulps, beyond m) lies in [1 - m * 2^-64, 1) is rounded down instead of
  up, and one with f in [1/2 - m * 2^-64, 1/2) is rounded up instead of
  down; m * 2^-64 is between 2^-16 and 2^-15.  This affects both
  round-to-nearest modes (ties to even and ties away).  In the directed
  modes the result would change only if both rounding words became 0,
  which needs a coincidence of about 2^-128, and no such case was found.
- In our test sets (82,279 _Decimal128 to _Float128 cases, 274 of them
  in this range), all 47 mismatches against the exact results are of
  this kind (29 one ulp too small, 18 one ulp too large), the same on
  aarch64 and x86_64.  No other result range is affected.
- _Decimal128 to x87 long double (bid128_to_binary80) has the same
  block.  There d is 64 for results below the smallest x87 subnormal,
  and after the word move the top word is 0, so the bad shift changes
  only the sticky word.  70,446 such conversions, including values in
  every x87 subnormal range and below it, gave correct results.

Root cause
----------
libgcc/config/libbid/bid_binarydecimal.c, bid128_to_binary128 (lines
145384-145397 on master):

// Check for exponent underflow and compensate by shifting the product
// Cut off the process at precision+2, since we can't really shift further
    if (e_out < 1) {
    int d;
    d = 1 - e_out;
    if (d > 115)
      d = 115;
    if (d >= 64) {
      d -= 64;
      z.w[2] = z.w[3], z.w[3] = z.w[4], z.w[4] = z.w[5], z.w[5] = 0;
    }
    e_out = 1;
    srl256 (z.w[5], z.w[4], z.w[3], z.w[2], d);
  }

with srl256 (lines 80-88):

// Shift 4-part 2^196 * x3 + 2^128 * x2 + 2^64 * x1 + x0
// right by "c" bits (must have c < 64)

#define srl256(x3,x2,x1,x0,c)                                   \
  ((x0) = ((x1) << (64 - (c))) + ((x0) >> (c)),                 \
   (x1) = ((x2) << (64 - (c))) + ((x1) >> (c)),                 \
   (x2) = ((x3) << (64 - (c))) + ((x2) >> (c)),                 \
   (x3) = (x3) >> (c)                                           \
  )

For results in [2^-16446, 2^-16445), d is 64, the word move does the
whole shift, and srl256 is called with c = 0, so it shifts by
64 - 0 = 64, which is undefined (srl128 in the same file handles c == 0;
srl256 does not).  A copy built with -fsanitize=undefined reports, for
the test case:

  bid_binarydecimal.c:145396:5: runtime error: shift exponent 64 is too large
for 64-bit type 'long unsigned int'

and this is the only location it reports on all our test cases.  The
wrong results match a shift by the count modulo 64, which is what the
AArch64 and x86_64 variable-shift instructions do: x << 64 then gives x,
and the macro adds adjacent words.  The round word z.w[3] becomes
z.w[3] + z.w[4] = W + m (mod 2^64), where W holds the first 64 bits
below the result and z.w[4] = m is the result's significand; the sticky
word z.w[2] also changes.  The rounding test

  if (lt128 (roundbound_128[...].w[1], roundbound_128[...].w[0],
             z.w[3], z.w[2]))

then sees a wrong fraction.  For a, W is 2^64 - 6, so W + m wraps to a
small number and the result is rounded down; for b, W is just below
2^63, and W + m is above 2^63.  A Python model of this (exact fraction
bits, sum of the words modulo 2^64, libbid's rounding rule) predicts
exactly the 47 mismatches in our test sets, on both architectures.

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 the function and srl256 have not changed since).  The
libbid update of 2024-03-27 (affd77d3fe7b) did not change it.  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) have, in bid128_to_binary128 and bid128_to_binary80
(LIBRARY/src/bid_binarydecimal.c in IntelRDFPMathLib20U5, lines 145353
and 144996):

    if (d > 0) srl256_short (z.w[5], z.w[4], z.w[3], z.w[2], d);
    if (d > 0) srl256_short (z.w[4], z.w[3], z.w[2], z.w[1], d);

GCC's bid32_to_binary128, bid64_to_binary128, bid32_to_binary80 and
bid64_to_binary80 contain the same block, but _Decimal32 and _Decimal64
values are far above the subnormal ranges, so it cannot be reached
there (Intel's version no longer has it in those functions).

Suggested fix
-------------
Port Intel's change:

--- a/libgcc/config/libbid/bid_binarydecimal.c
+++ b/libgcc/config/libbid/bid_binarydecimal.c
@@ -144976,7 +144976,8 @@
       z.w[1] = z.w[2], z.w[2] = z.w[3], z.w[3] = z.w[4], z.w[4] = 0;
     }
     e_out = 1;
-    srl256 (z.w[4], z.w[3], z.w[2], z.w[1], d);
+    if (d > 0)
+      srl256 (z.w[4], z.w[3], z.w[2], z.w[1], d);
   }
   c_prov = z.w[4];

@@ -145393,7 +145394,8 @@
       z.w[2] = z.w[3], z.w[3] = z.w[4], z.w[4] = z.w[5], z.w[5] = 0;
     }
     e_out = 1;
-    srl256 (z.w[5], z.w[4], z.w[3], z.w[2], d);
+    if (d > 0)
+      srl256 (z.w[5], z.w[4], z.w[3], z.w[2], d);
   }
   c_prov_hi = z.w[5];
   c_prov_lo = z.w[4];

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, all 82,279 _Decimal128
to _Float128 cases match the exact results (and the 70,446 x87 cases
still do), and the results in the other direction do not change.  With
this patch and the one in the companion report, -fsanitize=undefined
reports nothing on our test cases.

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 } */
/* { dg-add-options float128 } */
/* { dg-require-effective-target float128_runtime } */

/* Subnormal results of _Decimal128 to _Float128 conversions in
   [2^-16446, 2^-16445), rounded to nearest.  */

volatile _Decimal128 a = 2535293258477612123583382583422255E-4984DL;
volatile _Decimal128 b = 2054114851702009675624553072449140E-4984DL;

int
main (void)
{
  volatile _Float128 ra = a, rb = b;
  if (ra != 0x1.641aap-16446f128 || rb != 0x1.2084afe23481p-16446f128)
    __builtin_abort ();
  return 0;
}

Reply via email to