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

            Bug ID: 129105
           Summary: wrong code: (_Decimal32)INT_MIN and
                    (_Decimal64)INT_MIN are NaNs at run time (signed
                    overflow in libbid bid64_from_int32)
           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: ---

(Bugs 128624, 128634 are in related areas of code, but seem distinct from this
one)

At run time, converting INT_MIN from int to _Decimal32 or _Decimal64
gives a NaN.  The conversion to _Decimal128 is correct, and so is GCC's
constant folding of all three conversions.

$ cat t.c
/* (_Decimal32)INT_MIN and (_Decimal64)INT_MIN at run time.
   Assumes a little-endian target.  */
#include <limits.h>
#include <stdio.h>
#include <string.h>

volatile int v = INT_MIN;               /* forces a libgcc call */
static const _Decimal32 k32 = INT_MIN;  /* folded by GCC */
static const _Decimal64 k64 = INT_MIN;
static const _Decimal128 k128 = INT_MIN;

int
main (void)
{
  _Decimal32 d32 = v;   /* __bid_floatsisd */
  _Decimal64 d64 = v;   /* __bid_floatsidd */
  _Decimal128 d128 = v; /* __bid_floatsitd */
  unsigned int b32, f32;
  unsigned long long b64, f64, b128[2], f128[2];

  memcpy (&b32, &d32, 4);
  memcpy (&f32, &k32, 4);
  memcpy (&b64, &d64, 8);
  memcpy (&f64, &k64, 8);
  memcpy (b128, &d128, 16);
  memcpy (f128, &k128, 16);

  /* Expected: -2147484E3 (rounded to 7 digits), -2147483648E0 (exact).  */
  printf ("_Decimal32:  run time %08x, folded %08x, expected b420c49c\n",
          b32, f32);
  printf ("_Decimal64:  run time %016llx, folded %016llx, "
          "expected b1c0000080000000\n", b64, f64);
  printf ("_Decimal128: run time %016llx%016llx, folded %016llx%016llx, "
          "expected b0400000000000000000000080000000\n",
          b128[1], b128[0], f128[1], f128[0]);

  return b32 != 0xb420c49cU || d32 != -2147484E3DF
         || b64 != 0xb1c0000080000000ULL || d64 != -2147483648E0DD
         || b128[1] != 0xb040000000000000ULL || b128[0] != 0x80000000ULL
         || d128 != -2147483648E0DL;
}

$ gcc -O0 t.c -o t && ./t; echo $?
_Decimal32:  run time fc000000, folded b420c49c, expected b420c49c
_Decimal64:  run time ffffffff80000000, folded b1c0000080000000, expected
b1c0000080000000
_Decimal128: run time b0400000000000000000000080000000, folded
b0400000000000000000000080000000, expected b0400000000000000000000080000000
1

The output is the same at -O1, -O2 and -O3, because the conversion of the
volatile operand is always a call to __bid_floatsisd, __bid_floatsidd or
__bid_floatsitd.

0xfc000000 is a negative quiet NaN.  0xffffffff80000000 is a negative
signaling NaN (all combination-field bits set) with a non-canonical
payload.

Expected result
---------------
C23 (N3220) 6.3.1.4p4: "When a value of integer type is converted to a
decimal floating type, if the value being converted can be represented
exactly in the new type, it is unchanged.  If the value being converted
cannot be represented exactly, the result shall be correctly rounded with
exceptions raised as specified in ISO/IEC 60559."

-2147483648 has 10 digits.  It is exact in _Decimal64 (16 digits) and
_Decimal128 (34 digits), and the preferred quantum exponent of a
conversion from an integer type is 0 (C23 5.2.5.3.4, Table 5.2), so the
results are -2147483648E0: BID 0xb1c0000080000000 and
0xb0400000000000000000000080000000.  _Decimal32 has 7 digits, so the
value is rounded; to nearest with ties to even (the default decimal
rounding mode) this gives -2147484E3 (-2.147484E9), BID 0xb420c49c.
These are the values GCC folds to.

Scope
-----
- Only INT_MIN is affected.  All 2^32 int values were checked on aarch64
  with GCC 15.2 and 16.2: (_Decimal64)x against the BID encoding built
  directly, and (_Decimal32)x against (_Decimal32)(_Decimal128)x.  INT_MIN
  is the only mismatch.
- signed char and short go through the same functions but cannot reach
  INT_MIN; all their values convert correctly.
- long long (bid64_from_int64, bid128_from_int64), __int128 and the
  unsigned types give correct results at their limits and for sampled
  values, except for the double rounding of 64-bit values to _Decimal32
  (PR 128634).

Root cause
----------
libgcc/config/libbid/bid_from_int.c, bid64_from_int32 (lines 43-46 on
master).  __bid_floatsidd uses it directly, and __bid_floatsisd calls it
before bid64_to_bid32:

  if ((x & SIGNMASK32) == SIGNMASK32) {
    // negative int32
    x = ~x + 1; // 2's complement of x
    res = (unsigned int) x | 0xb1c0000000000000ull;

For x == INT_MIN, ~x + 1 overflows int.  x is negative in this branch, so
GCC may assume that the new x is in [1, INT_MAX], where zero and sign
extension give the same result, and it extends (unsigned int) x to 64
bits with a sign extension.  libgcc is built with -O2; bid_from_int.o
from libgcc.a contains:

  aarch64, GCC 16.2.0 (13.3.0, 14.4.1, 15.2.0 and 15.3.0 are similar):
    neg   w0, w0
    mov   x1, #0xb1c0000000000000
    sxtw  x0, w0
    orr   x0, x0, x1

  x86_64, GCC 15.3.0 (12.2.0 and 14.4.0 are the same):
    movabs $0xb1c0000000000000,%rdx
    neg    %edi
    movslq %edi,%rax
    or     %rdx,%rax

For INT_MIN, neg gives 0x80000000, the sign extension gives
0xffffffff80000000, and the OR leaves that unchanged.  bid64_to_bid32
then quiets this NaN and drops its non-canonical payload, which gives
0xfc000000.

A copy of the function built with -fsanitize=undefined reports "negation
of -2147483648 cannot be represented in type 'int'".  Built with GCC 15.2
on aarch64, the copy returns 0xb1c0000080000000 at -O0, -O1 and
-O2 -fwrapv, and 0xffffffff80000000 at -O2.

bid128_from_int32 negates in unsigned arithmetic
(res.w[LOW_128W] = ~((unsigned int) x) + 1;), which is why _Decimal128 is
correct, and so does bid64_from_int64 (C = ~((UINT64) x) + 1;).
bid128_from_int64 (line 326) has the same signed negation, with x of type
SINT64:

    res.w[LOW_128W] = ~x + 1;   // 2's complement of x

This is undefined for LLONG_MIN as well.  No extension follows it, so the
compiled code currently gives the correct result: (_Decimal128)LLONG_MIN
is 0xb0400000000000008000000000000000.

The decimal-to-integer functions (bid64_to_int32.c and the others) negate
UINT64 values (res = -C1;) and do not have this problem.  Converting the
NaNs back with (int) gives -2147483648, which libbid returns for every NaN
(the "integer indefinite" value).  That value equals INT_MIN, so a round
trip through the decimal type hides the bug.

The code dates from the 2007 libbid import (200359e888d1) and is
unchanged on master (e1f58f09244f).  With GCC 16.2.0 for x86_64,
libgcc happens to give the right result, because the code generated
there zero-extends (neg %edi; or %rdi,%rax); the undefined behaviour is
still in the source.

Suggested fix
-------------
--- a/libgcc/config/libbid/bid_from_int.c
+++ b/libgcc/config/libbid/bid_from_int.c
@@ -42,8 +42,7 @@
   // in the lowest 32bits of the result
   if ((x & SIGNMASK32) == SIGNMASK32) {
     // negative int32
-    x = ~x + 1;        // 2's complement of x
-    res = (unsigned int) x | 0xb1c0000000000000ull;
+    res = (~((unsigned int) x) + 1) | 0xb1c0000000000000ull;   // 2's
complement of x
     // (exp << 53)) = biased exp. is 0
   } else {     // positive int32
     res = x | 0x31c0000000000000ull;   // (exp << 53)) = biased exp. is 0
@@ -323,7 +322,7 @@
   // if integer is negative, use the absolute value
   if ((x & SIGNMASK64) == SIGNMASK64) {
     res.w[HIGH_128W] = 0xb040000000000000ull;
-    res.w[LOW_128W] = ~x + 1;  // 2's complement of x
+    res.w[LOW_128W] = ~((UINT64) x) + 1;       // 2's complement of x
   } else {
     res.w[HIGH_128W] = 0x3040000000000000ull;
     res.w[LOW_128W] = x;

With this patch, bid_from_int.c built by GCC 15.2 at -O2 on aarch64 no
longer has the sxtw, the test case above passes when linked with it, and
all 2^32 int values convert correctly.

The testsuite checks decimal-to-integer conversions at the limits
(c-c++-common/dfp/convert-int-max.c) but not the conversion of INT_MIN to
a decimal type.  A possible test, which aborts with the current libgcc
and passes with the patch:

/* { dg-do run } */
/* { dg-options "-O2" } */

volatile int v = -__INT_MAX__ - 1;

int
main (void)
{
  _Decimal32 d32 = v;
  _Decimal64 d64 = v;
  _Decimal128 d128 = v;
  if (d32 != -2147484E3DF || d64 != -2147483648E0DD
      || d128 != -2147483648E0DL)
    __builtin_abort ();
  return 0;
}

Reply via email to