<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/70597>70597</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Missed optimization of loopDeletion probably because of a missing loopUnswitch
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
ZY546
</td>
</tr>
</table>
<pre>
https://godbolt.org/z/TW9b71zPM
```cpp
int b, c;
int n;
void test() {
for (int i = 0; i < 1000; i += b) {
if(c < 0){
c = n;
}
}
}
```
In the test code, the value of `c` only gets a chance to change when it first enters the loop, so from there we can make the following optimizations:
If initially c<0 holds, then the loop is not executed.
Otherwise, c is a loop invariant for all subsequent iterations of the loop, which can be optimized using loopUnswitch.
Furthermore, if we optimize via loopUnswitch, we see that the entire loop is unnecessary.
Finally, we get the expected code:
```asm
test(): # @test()
cmp dword ptr [rip + c], 0
js .LBB0_1
ret
.LBB0_1: # %if.then
mov eax, dword ptr [rip + n]
mov dword ptr [rip + c], eax
ret
```
But Clang:
```asm
test(): # @test()
mov eax, dword ptr [rip + b]
mov esi, dword ptr [rip + c]
xor ecx, ecx
mov edx, dword ptr [rip + n]
jmp .LBB0_1
.LBB0_3: # %for.inc
add ecx, eax
cmp ecx, 1000
jge .LBB0_4
.LBB0_1: # %for.body
test esi, esi
jns .LBB0_3
mov dword ptr [rip + c], edx
mov esi, edx
jmp .LBB0_3
.LBB0_4: # %for.cond.cleanup
ret
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJycVs1u4zYQfhr6MlhDoizZOugQxzBQoIv20KJoLwVFjiSmFKmSlJ3k6QtScmxlnSK7RhCSw_n5vpmRRsw52WrEiuR7kh9WbPSdsdVff-abYlUb8VJ13g-OZA-EHgk9tkbURvm1sS2hx1dCj7_9Udbb9PXXryQ5kOSBFMn0x4dhkkjtoSb0ETjJ9leRfjudjBTg0XlC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