https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114661

            Bug ID: 114661
           Summary: Bit operations not optimized to multiplication
           Product: gcc
           Version: 14.0
            Status: UNCONFIRMED
          Keywords: missed-optimization
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: antoshkka at gmail dot com
  Target Milestone: ---

Consider the example:

unsigned mul(unsigned char c) {
    if (c > 3) __builtin_unreachable();
    return c << 18 | c << 15 |
        c << 12 | c << 9 |
        c << 6 | c << 3 | c;
}

GCC with -O2 generates the following assembly:

mul(unsigned char):
  movzx edi, dil
  lea edx, [rdi+rdi*8]
  lea eax, [0+rdx*8]
  mov ecx, edx
  sal edx, 15
  or eax, edi
  sal ecx, 9
  or eax, ecx
  or eax, edx
  ret

However it could be optimized to just:

mul(unsigned char):
  imul eax, edi, 299593
  ret

Compiling with -Os does not help.

Godbolt playground: https://godbolt.org/z/YszzMbovK

P.S.: without `c << 18 | c << 15 |` the bit operations are transformed to
multiplication.

Reply via email to