Skip to content

Missed optimization: Reassociate multiplies by constants to shrink said constants #143622

Open
@Alcaro

Description

@Alcaro
int a(int b, int c, int d, int e)
{
    return b*1000+c*100+d*10+e;
}
int a2(int b, int c, int d, int e)
{
    return ((b*10+c)*10+d)*10+e;
}

Expected: Same for both.

Actual: a2 is a series of lea, as expected, but former contains two imul.

GCC also misses this optimization, but MSVC performs it. https://godbolt.org/z/1fs9xhsdb

The missed optimization also shows up on ARM and RISC-V, where a loads three different constants, but a2 reuses the same one. https://godbolt.org/z/qzMEv1b8j https://godbolt.org/z/bTYzY4vGa (and GCC optimizes mul by 10 to some shifts and adds, but that's a separate missed optimization)

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