https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92985
Bug ID: 92985 Summary: missed optimization opportunity for switch linear transformation Product: gcc Version: 10.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: barry.revzin at gmail dot com Target Milestone: --- From Peter Dimov on Slack: #include <cstddef> struct X { int x, y, z; int operator[]( std::size_t i ) const noexcept { switch( i ) { case 0: return x; case 1: return y; case 2: return z; default: __builtin_unreachable(); } } }; int f( X const& x, std::size_t i ) { return x[ i ]; } compiled with -O2 (or -O3) emits: f(X const&, unsigned long): cmp rsi, 1 je .L2 cmp rsi, 2 jne .L6 mov eax, DWORD PTR [rdi+8] ret .L2: mov eax, DWORD PTR [rdi+4] ret .L6: mov eax, DWORD PTR [rdi] ret But it should be able to just emit: mov eax, DWORD PTR [rdi+rsi*4] ret