https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128750
Bug ID: 128750
Summary: wrong code with -fwrapv: extract_muldiv distributes a
multiplication into ABS_EXPR; (unsigned) abs (x + 2) *
3U gives 1
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: jeffchen006 at gmail dot com
Target Milestone: ---
Target: x86_64-pc-linux-gnu
#include <cstdio>
int x = 1431655763;
int main() {
printf("%u\n", (unsigned)__builtin_abs(x + 2) * 3U);
}
$ g++ -O0 t.cpp && ./a.out
4294967295
$ g++ -O0 -fwrapv t.cpp && ./a.out
1
Same at -O2 with -fwrapv, and with -fno-strict-overflow (GCC 8 and later).
Clang -fwrapv gives 4294967295.
Expected 4294967295: x + 2 = 1431655765 fits in int, abs gives the same value,
and 1431655765 * 3U = 4294967295 in unsigned arithmetic. The program has no
overflow, so -fwrapv must not change the result.
-fdump-tree-original with -fwrapv:
(unsigned int) ABS_EXPR <x * 3 + 6>
x * 3 + 6 wraps to -1 in int, and abs (-1) = 1.
Cause: extract_muldiv_1 (fold-const.cc). `case ABS_EXPR:` (when the constant is
not negative) falls through to `case NEGATE_EXPR:`:
case NEGATE_EXPR:
/* For division and modulus, type can't be unsigned, as e.g.
(-(x / 2U)) / 2U isn't equal to -((x / 2U) / 2U) for x >= 2.
For signed types, even with wrapping overflow, this is fine. */
if (code != MULT_EXPR && TYPE_UNSIGNED (type))
break;
if ((t1 = extract_muldiv (op0, c, code, wide_type)) != 0)
return fold_build1 (tcode, ctype, fold_convert (ctype, t1));
"Even with wrapping overflow, this is fine" holds for negation (-(a) * c == -(a
* c) modulo 2^N), but not for ABS: abs (a) * c is not abs (a * c) when a * c
wraps. For ABS_EXPR the move should need TYPE_OVERFLOW_UNDEFINED of the operand
type (or no fallthrough).
The same happens with signed char / short operands, and with llabs on a
_BitInt(65) value. Fails on all releases tested (7.5 to trunk).
gcc -Wall -Wextra gives no warnings. The test needs -fwrapv: the bug is that a
fold ignores it. -fno-strict-aliasing does not change the output.
Possible fix: One possible fix is to stop the fallthrough from `case ABS_EXPR:`
to `case NEGATE_EXPR:` in extract_muldiv_1 when the operand type of the
ABS_EXPR does not have TYPE_OVERFLOW_UNDEFINED, so the multiplication is moved
into ABS only when abs (a) * c == abs (a * c) is guaranteed.
gcc version 17.0.0 20261114 (experimental), r17-6275-gfceddda853f,
x86_64-pc-linux-gnu
Configured with: --enable-languages=c,c++ --disable-multilib
--disable-bootstrap --enable-checking=release