<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/59218>59218</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[missed optimization] Registers saved/restored even if only needed in unlikely path
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
avikivity
</td>
</tr>
</table>
<pre>
Consider
```c++
int g(int);
void f(int* b, int* e) {
while (b != e) {
if (__builtin_expect(*b != 0, false)) [[unlikely]] {
*b = g(*b);
}
++b;
}
}
```
If we believe the __builtin_expect and/or unlikely annotations (had both for extra safety), the loop usually does nothing. So we would expect any register saving and restoring to be pushed to the unlikely section. Yet (-O3):
```asm
f(int*, int*): # @f(int*, int*)
push r14
push rbx
push rax
cmp rdi, rsi
je .LBB0_5
mov rbx, rsi
mov r14, rdi
.LBB0_2: # =>This Inner Loop Header: Depth=1
mov edi, dword ptr [r14]
test edi, edi
jne .LBB0_3
add r14, 4
cmp r14, rbx
jne .LBB0_2
jmp .LBB0_5
.LBB0_3: # in Loop: Header=BB0_2 Depth=1
call g(int)@PLT
mov dword ptr [r14], eax
add r14, 4
cmp r14, rbx
jne .LBB0_2
.LBB0_5:
add rsp, 8
pop rbx
pop r14
ret
```
There are around 10 instructions executed that are only needed if the unlikely branch is taken.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy1VcGOozgQ_Rq4WBOBCXQ4cOh0trUjtbSj2b7sqWVwJXia2Mg2SWe-fsoGkkAns3tZ5GDiKr969WyXS8VPxZOSRnDQQbQJosfhnUV9qwK6ds2PCmnJLqAr7AOaB8n6espBCU62o_WRlAF9IsM3oDsJHgZ_gs-xFg0Q9C7xFQfJ5oaPe8TWOb29lZ1orJBv8NFChZgrhD1PjVyoLWuMw_Aw6RpbJxvxDs0pSDfYPmO7p4dBjN2AeZ3Y2elhMxvwopQTx7PT5WMU8Vqm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