Skip to content

Missed optimization: Imperfect optimization of straightforward std::find #112063

Open
@Alcaro

Description

@Alcaro
static bool any_of_impl(int* first, int* last, int num)
{
    for (; first != last; ++first) {
        if (*first == num)
            return true;
    }
    return false;
}
bool square(int num) {
    int x[] = {1,2,3};
    return any_of_impl(x, x+3, num);
}

bool cube(int num) {
    return num==1 || num==2 || num==3;
}

-O2 or -O3

Expected: Same asm for both

Actual:

square(int):
        cmp     edi, 1
        sete    cl
        add     edi, -2
        test    edi, -2
        sete    al
        or      al, cl
        ret

cube(int):
        dec     edi
        cmp     edi, 3
        setb    al
        ret

The expected result shows up on pretty much any simplification of the input, including moving the +3 to the callee, or changing both functions' return type to int. Feels like some optimizer passes are running in wrong order and confusing each other.

https://godbolt.org/z/88938fP3d

Originally found via a std::ranges::any_of call, hence the function name. It turned into std::find when I reduced it. https://godbolt.org/z/GjsE3vEK4

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