<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/64369>64369</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[LICM]Missed optimization: loop invariants for global variables
</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>
Hello, I noticed that clang16 doesn't seem to recognize loop invariants very well for global variables:
https://godbolt.org/z/Y34G5W5bY
```c
extern int var_14;
extern int var_24;
void test(int var_2, int var_3, int var_8) {
for (int i_2 = -3247424; i_2 < 19; i_2 += var_3 + 1056714155)
{
var_24 += var_8;
var_24 += var_14 + var_2; //loop invariants
i_2+=i_2/3;
}
}
```
clang16 -O3:
Missed optimization of `var_14 + var_2`:
```
define dso_local void @test(int, int, int)(i32 noundef %var_2, i32 noundef %var_3, i32 noundef %var_8) local_unnamed_addr {
entry:
%0 = load i32, ptr @var_14, align 4
%add3 = add i32 %var_3, 1056714155
%var_24.promoted = load i32, ptr @var_24, align 4
br label %for.body
for.cond.cleanup: ; preds = %for.body
store i32 %add2, ptr @var_24, align 4
ret void
for.body: ; preds = %entry, %for.body
%i_2.011 = phi i32 [ -3247424, %entry ], [ %add5, %for.body ]
%add2910 = phi i32 [ %var_24.promoted, %entry ], [ %add2, %for.body ]
%add = add nsw i32 %add2910, %var_8
%add1 = add i32 %add, %var_2
%add2 = add i32 %add1, %0
%div = sdiv i32 %i_2.011, 3
%add4 = add i32 %add3, %i_2.011
%add5 = add i32 %add4, %div
%cmp = icmp slt i32 %add5, 19
br i1 %cmp, label %for.body, label %for.cond.cleanup
}
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyMVluP6jYQ_jXmZbTItwTywMNhEe2RetTHavuCnNiAK2NHtmG7--srm4SEwJ5TtNr4Mt83M_7GFxGCPlilVqhYo2IzE-d4dH7191vBy1n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