Skip to content

Missed optimization (-O3): llvm doesn't transform a loop into a constant #111037

@dcci

Description

@dcci

https://godbolt.org/z/oPKMWx871

Inline code:

long patatino() {
    long x = 0;
    for (int i = 0; i < 5; ++i) {
        while (x < 10) {
            if (x % 2 == 0) {
                x += 2;
            } else {
                x += 1;
            }
        }
        while ((x * 2) % 7 == 3 && (x + 1) % 5 != 0) {
            x = x;
        }
        while (((x * 3) % 11 == 5) && ((x + 2) % 3 != 0) && ((x * x) % 13 == 7)) {
            x = x;
        }
        while (((x * 17) % 23 == 11) && ((x + 3) % 7 != 0) && ((x * x * x) % 19 == 13) && ((x * x * x * x) % 29 == 21)) {
            x = x;
        }
        while (((x * 37) % 41 == 23) && ((x + 5) % 11 != 0) && ((x * x * x * x * x) % 43 == 31) && ((x * x * x * x * x * x) % 47 == 37)) {
            x = x;
        }
        while (((x * 53) % 59 == 31) && ((x + 7) % 13 != 0) && ((x * x * x * x * x * x * x) % 61 == 43) && ((x * x * x * x * x * x * x * x) % 67 == 53) && ((x * x * x * x * x * x * x * x * x) % 71 == 61)) {
            x = x;
        }
    }
    if (false) {
        x = 42;
    }
    return x;
}

The optimal codegen for this is:

patatino():
        mov     eax, 10
        ret

while LLVM generates a loop.

Probably can be reduced a bit, but that's a start.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions