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

            Bug ID: 112660
           Summary: missed-optimization: combine shifts when shifted out
                    bits are known 0
           Product: gcc
           Version: 13.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: goon.pri.low at gmail dot com
  Target Milestone: ---

This function here we know the shifted out bits have to be 0:

int unopt(int v) {
    if (v & 3) return -1;
    return v >> 2 << 5;
}

unopt:
        test    dil, 3
        jne     .L3
        sar     edi, 2
        mov     eax, edi
        sal     eax, 5
        ret
.L3:
        mov     eax, -1
        ret

Therefore we could combine the shifts:

int opt(int v) {
    if (v & 3) return -1;
    return v << 3;
}

opt:
        test    dil, 3
        jne     .L7
        lea     eax, [0+rdi*8]
        ret
.L7:
        mov     eax, -1
        ret

Reply via email to