https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106804
Bug ID: 106804
Summary: Poor codegen for selecting and incrementing value
behind a reference
Product: gcc
Version: 12.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: anthony.mikh at yandex dot ru
Target Milestone: ---
Godbolt: https://godbolt.org/z/e9ePs7Ece
For the following source code:
void increment_largest(int& a, int& b) {
++(a > b ? a : b);
}
gcc 12 with -O2 produces the following asm:
increment_largest(int&, int&):
mov edx, DWORD PTR [rdi]
mov eax, DWORD PTR [rsi]
cmp edx, eax
jle .L2
add edx, 1
mov DWORD PTR [rdi], edx
ret
.L2:
add eax, 1
mov DWORD PTR [rsi], eax
ret
For equivalent code using pointers:
void increment_largest(int* a, int* b) {
++*(*a > *b ? a : b);
}
gcc with -O2 gives something slightly different:
increment_largest(int*, int*):
mov edx, DWORD PTR [rdi]
mov eax, DWORD PTR [rsi]
cmp edx, eax
jle .L2
mov eax, edx
mov rsi, rdi
.L2:
add eax, 1
mov DWORD PTR [rsi], eax
ret
If one rewrites code with references to assign the selected reference to a
variable:
void increment_largest(int& a, int& b) {
auto& tgt = (a > b ? a : b);
++tgt;
}
it gives exactly the same asm as the version with pointers. Anyway it is
seemingly worse than what clang-14 -O2 produces for all three sources:
increment_largest(int&, int&):
mov eax, dword ptr [rdi]
cmp eax, dword ptr [rsi]
cmovg rsi, rdi
add dword ptr [rsi], 1
ret
Likely to be related to PR94006.