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

            Bug ID: 108465
           Summary: Optimize (a < b) == (b < a) to a == b
           Product: gcc
           Version: 13.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: ---

For GCC 12 the following code with -O2:

int compare_eq(int a, int b) {
    return ((a < b) == (b < a));
}

compiles into the following assembly:

compare_eq(int, int):
        cmp     edi, esi
        setl    dl
        setg    al
        cmp     dl, al
        sete    al
        movzx   eax, al
        ret

Which is suboptimal. More optimal assembly would be:

compare_eq(int, int):
        xor     eax, eax
        cmp     edi, esi
        sete    al
        ret

Godbolt Playground: https://godbolt.org/z/4sfcTjjjb

Motivation: in generic C++ code the comparison is often done via a functor. The
algorithm is only allowed to use that functor:

if (__comp(a, b) == __comp(b, a)) {
    return x;
} else if (__comp(b, a)) {
    return y;
}

Because of that, with the inlined functor the comparison becomes ((a < b) == (b
< a))

Reply via email to