Bug 81834 - loop with increment conditional on IV is not optimized out
Summary: loop with increment conditional on IV is not optimized out
Status: RESOLVED FIXED
Alias: None
Product: gcc
Classification: Unclassified
Component: tree-optimization (show other bugs)
Version: 7.1.1
: P3 enhancement
Target Milestone: 11.0
Assignee: Not yet assigned to anyone
URL:
Keywords: missed-optimization
Depends on:
Blocks:
 
Reported: 2017-08-12 21:52 UTC by Geoffrey Allott
Modified: 2021-12-17 06:47 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Known to work: 11.1.0, 11.2.0, 12.0
Known to fail: 10.3.0, 9.1.0
Last reconfirmed: 2017-08-16 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Geoffrey Allott 2017-08-12 21:52:45 UTC
The following code:

int main() {
    for(int i=0; i += i < 1000, i < 1000;);
}

optimizes on x86_64 to the following code:

main:
.LFB0:
    xorl    %eax, %eax
.L2:
    xorl    %edx, %edx
    cmpl    $999, %eax
    setle   %dl
    addl    %edx, %eax
    cmpl    $999, %eax
    jle .L2
    xorl    %eax, %eax
    ret

I would expect the loop to be removed completely.
Comment 1 Richard Biener 2017-08-16 08:03:30 UTC
There's a chicken-and-egg issue in optimization -- proving that i < 1000 is always
true for the increment requires the number of iterations to be known and that
requires this condition to be simplified.

optimistic VRP should be able to figure this out together with SCEV but SCEV
isn't fed with the intermediate VRP info nor does VRP query SCEV during
iteration at the right point.

Quite an arcane case though...

clang doesn't get it either.
Comment 2 Geoffrey Allott 2017-08-17 06:41:11 UTC
Hi Richard, I agree that this seems quite 'arcane' at first glance; I should explain that I found it when an empty for loop failed to optimize out in rust - the reduced test case failed to optimize in clang and also gcc, so I posted it here. My thought is that this kind of pattern might be more common than it seems at first glance, after other code has been reduced.
null
Comment 3 Andrew Pinski 2021-12-17 06:47:37 UTC
Fixed for GCC 11, by the ranger patches for eVRP.