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

            Bug ID: 97690
           Summary: (cond ? 2 : 0) is not optimized to int(cond) << 1
           Product: gcc
           Version: 11.0
            Status: UNCONFIRMED
          Keywords: missed-optimization
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: redi at gcc dot gnu.org
  Target Milestone: ---

enum E { init=0, active=1, done=2 };

int f(bool d)
{
    return d ? done : init;
}

int g(bool d)
{
    return int(d) << 1;
}

The first function is more readable and less fragile (in case the order of bits
is changed) but GCC produces larger code for it.

For x86_64 with -O3:

f(bool):
        xor     eax, eax
        test    dil, dil
        setne   al
        add     eax, eax
        ret
g(bool):
        movzx   eax, dil
        add     eax, eax
        ret

And for x86_64 -Os:

f(bool):
        neg     dil
        sbb     eax, eax
        and     eax, 2
        ret
g(bool):
        movzx   eax, dil
        add     eax, eax
        ret


Clang produces the same code for both functions at all optimization levels:

f(bool):                                  # @f(bool)
        lea     eax, [rdi + rdi]
        ret
g(bool):                                  # @g(bool)
        lea     eax, [rdi + rdi]
        ret

Reply via email to