<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/63997>63997</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[Reassociate] Missed optimization of expression of addition
</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>
Test code: https://godbolt.org/z/3v5sbe3Ej
```c++
int test()
{
int a,b,c,d,e,f,g;
cin>>a>>b>>c>>d>>g;
e=a+b+c;
f=d+b+c; //can be replaced with the value at line 5
cout<<e<<f;
return 0;
}
```
IR at -O1:
```
%0 = load i32, ptr %a, align 4
%1 = load i32, ptr %b, align 4
%2 = load i32, ptr %c, align 4
%add = add i32 %2, %1
%add5 = add i32 %add, %0
%3 = load i32, ptr %d, align 4
%add6 = add i32 %2, %1
%add7 = add i32 %add6, %3
```
We can easily notice that `b+c` at line 6 in the test code can be replaced with the value at line 5, but the intermediate code generated by LLVM at the optimization level of O1 does not.
I noticed that under the optimization level of O1, `ReassociatePass` changed the order of addition calculation in a+b+c in an attempt to optimize, but the final generated ir only changed the order of addition calculation, whether it missed the value substitution step.
In addition, if we perform the `EarlyCSEPass` after the `ReassociatePass`, then this missed optimization can be done without changing the optimization level.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyMVVGPozYQ_jWTl9FGxAYSHnjYkESqdKerrlWr9s3gIfjk2BEedpv79ZWB7GX3sqeVUEYw33zzzccQqxDM0RGVkG0h2y3UwJ3vy3__ydJ8UXt9Kf-kwNh4TSAfsWM-B5CPIA4gDkeva2956fsjiMN3EAf5lIWa5P4bJDtIHiFPpqsBsY3X-NQ4RqbAIDYgihm5npOIiBGgQFQ1iKoBUWkQFYGoWhDVEeQNsjEO5B7kXk2hnkIzBT2F1yUEcqdAbGsQ2wbkFvFHrgW507e5ac5GOawJezpb1ZDGZ8Mdckf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