Bug 86923 - Missed optimization performing consecutive integer sum, loop not removed
Summary: Missed optimization performing consecutive integer sum, loop not removed
Status: RESOLVED DUPLICATE of bug 65855
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: 9.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2018-08-12 18:12 UTC by nightstrike
Modified: 2018-08-13 17:26 UTC (History)
0 users

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description nightstrike 2018-08-12 18:12:52 UTC
unsigned long f(unsigned int n) {
    unsigned long total = 0;
    for (unsigned int i = 0; i < n; ++i)
        total += i;
    return total;
}

It may not be terribly useful to report this, as I can (and arguably should) write n(n-1)/2 manually, but clang does successfully transform this into:

        lea     eax, [rdi - 1]
        add     edi, -2
        imul    rdi, rax
        shr     rdi
        add     rdi, rax

whereas GCC tries instead to vectorize and process the loop as written.  Obviously, O(1) is preferable to O(n) here.

This applies to both C and C++.
Comment 1 jsm-csl@polyomino.org.uk 2018-08-13 17:13:24 UTC
Isn't this bug 65855?
Comment 2 Andrew Pinski 2018-08-13 17:26:08 UTC
(In reply to joseph@codesourcery.com from comment #1)
> Isn't this bug 65855?

Yes

*** This bug has been marked as a duplicate of bug 65855 ***