https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98817
Bug ID: 98817
Summary: Optimize if (a != b) a = b;
Product: gcc
Version: 11.0
Status: UNCONFIRMED
Keywords: missed-optimization
Severity: normal
Priority: P3
Component: middle-end
Assignee: unassigned at gcc dot gnu.org
Reporter: antoshkka at gmail dot com
Target Milestone: ---
Consider the example:
void arithmetic(int& result, int value) {
if (result != value) {
result = value;
}
}
GCC generates the following assembly:
arithmetic(int&, int):
cmp DWORD PTR [rdi], esi
je .L1
mov DWORD PTR [rdi], esi
.L1:
ret
The assembly seems suboptimal, because
1) cmov could be used
2) conditional jump could be totally removed, reducing the binary size and
leaving only one mov instruction:
arithmetic(int&, int):
mov DWORD PTR [rdi], esi
ret
Godbolt playground https://godbolt.org/z/Pdz7eP with above sample and
std::vector::clear() sample that would also benefit from the above
optimization.