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

            Bug ID: 129157
           Summary: wrong code at -O0 and above: `(long) ((c ? 0UL -
                    (unsigned long) (c ? -128 : -128) : 0ULL) % 7) % 5ULL`
                    folded to 0
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: wrong-code
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: haoxintu at gmail dot com
  Target Milestone: ---

Hi,

There might be another case where GCC may miscompile it for years. All versions
of GCC from 4.8.5 abort on it.

$cat repro.c

__attribute__((noinline)) unsigned long long f (int c)
{
  /* c != 0: 0UL - (unsigned long) -128 == 128, 128 % 7 == 2, 2 % 5 == 2.  */
  return (long) ((c ? 0UL - (unsigned long) (c ? -128 : -128) : 0ULL) % 7) %
5ULL;
}

int main (void)
{
  if (f (1) != 2)
    __builtin_abort ();
  return 0;
}


$ gcc -O0 repro.c && ./a.out     # Aborted (also -O1, -O2, -O3, -Os, and with
-fwrapv)
$ clang -O0 repro.c && ./a.out   # ok
$ g++ -O0 repro.c && ./a.out     # ok
```

There should be no undefined behaviour: all arithmetic is unsigned, and
converting 2 to `long` is exact. clang
with `-fsanitize=address,undefined` reports nothing.

Godbolt (gcc trunk aborts, clang trunk is correct):
https://godbolt.org/z/bj6K8P6Eq

Thanks.

Reply via email to