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

            Bug ID: 103660
           Summary: Sub-optimal code with relational operators
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: david at westcontrol dot com
  Target Milestone: ---

I recently looked at some of gcc's "if-conversions" and other optimisations of
expressions involving relational operators - something people might use when
trying to write branchless code.  I know that it is often best to write in the
clearest way, including branches, and let the compiler handle the optimisation.
 But people do try to do this kind of thing by hand.

I tested 6 examples of ways to write a simple "min" function:


int min1(int a, int b) {
    if (a < b) return a; else return b;
}

int min2(int a, int b) {
    return (a < b) ? a : b;
}

int min3(int a, int b) {
    return (a < b) * a | (a >= b) * b;
}

int min4(int a, int b) {
    return (a < b) * a + (a >= b) * b;
}

int min5(int a, int b) {
    const int c = a < b;
    return c * a + (1 - c) * b;
}

int min6(int a, int b) {
    const bool c = a < b;
    return c * a + !c * b;
}


gcc happily optimises the first two versions.  For the next two, it uses
conditional moves for each half of the expression, then combines them with "or"
or "add".  For version 5, it generates two multiply instructions, and version 6
is even worse in trunk (gcc 12).  This last one is a regression - gcc 11
generates the same code for version 6 as for version 4 (not optimal, but not as
bad).

For comparison, clang 5+ generates optimal code for all versions.  I have tried
a number of different targets (godbolt is wonderful for this stuff), with
similar results.
  • [Bug c/103660] New: Sub-optimal ... david at westcontrol dot com via Gcc-bugs

Reply via email to