https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113426
Bug ID: 113426
Summary: Missed optimization of loop invariant elimination
Product: gcc
Version: 14.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: 652023330028 at smail dot nju.edu.cn
Target Milestone: ---
Hello, we noticed that maybe there is a missed optimization for loop invariant
elimination.
Loop invariant: a+b.
https://godbolt.org/z/Ebzd3dMPW
int a, b, c;
int n;
int w;
void func(){
for(int i=0;i<100;i++){
c=n;
a+=w;
b-=w;
n=a+b;
}
}
GCC -O3:
func():
mov r9d, DWORD PTR a[rip]
mov r10d, DWORD PTR b[rip]
mov eax, 100
mov edi, DWORD PTR n[rip]
mov esi, DWORD PTR w[rip]
mov ecx, r10d
mov edx, r9d
.L2:
mov r8d, edi
lea edi, [rcx+rdx]
sub ecx, esi
add edx, esi
sub eax, 1
jne .L2
imul edx, esi, -99
lea eax, [rsi+r9]
add r9d, r10d
mov DWORD PTR c[rip], r8d
mov DWORD PTR n[rip], r9d
sub eax, edx
mov DWORD PTR a[rip], eax
mov eax, r10d
sub eax, esi
add eax, edx
mov DWORD PTR b[rip], eax
ret
Expected code (Clang):
func(): # @func()
mov eax, dword ptr [rip + a]
mov ecx, dword ptr [rip + b]
lea edx, [rcx + rax]
imul esi, dword ptr [rip + w], 100
add eax, esi
sub ecx, esi
mov dword ptr [rip + n], edx
mov dword ptr [rip + c], edx
mov dword ptr [rip + a], eax
mov dword ptr [rip + b], ecx
ret
We analyze and find that in the optimization results of GCC, the calculation of
n is actually outside the loop (add r9d, r10d; mov DWORD PTR n[rip], r9d).
However, because of the effect of c=n, a+b is calculated once each time through
the loop.
Hope this analysis will help with this issue.
Thank you very much for your time and effort! We look forward to hearing from
you.