https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108406
Bug ID: 108406
Summary: Missed integer optimization on x86-64 unless -fwrapv
is used
Product: gcc
Version: 12.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: jzwinck at gmail dot com
Target Milestone: ---
Consider this C++ code:
#include <cstdint>
// returns a if less than b or if b is INT32_MIN
int32_t special_min(int32_t a, int32_t b)
{
return a < b || b == INT32_MIN ? a : b;
}
GCC with -fwrapv correctly realizes that subtracting 1 from b can eliminate the
special case, and it generates this code for x86-64:
lea edx, [rsi-1]
mov eax, edi
cmp edi, edx
cmovg eax, esi
ret
But without -fwrapv it generates worse code:
mov eax, esi
cmp edi, esi
jl .L4
cmp esi, -2147483648
je .L4
ret
.L4:
mov eax, edi
ret
If I wrote "hand optimized" C++ code trying to implement that optimization, I
understand -fwrapv would be required, otherwise the compiler could decide the
signed overflow is UB. But here the compiler is in control, it knows the
behavior of integer overflow on x86-64, and so it should not matter whether
-fwrapv is used.
Demo: https://godbolt.org/z/o881Mdqoa
Stack Overflow discussion:
https://stackoverflow.com/questions/75110108/gcc-wont-use-its-own-optimization-trick-without-fwrapv
This is somewhat related to #102032 in the sense that it's an optimization
missed without -fwrapv, but the type of optimization is different. It is
possible there's a single solution that would solve both problems (and others).