https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103857
Bug ID: 103857
Summary: implement ternary without jump (and comparison)
Product: gcc
Version: 12.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: drepper.fsp+rhbz at gmail dot com
Target Milestone: ---
This test case is derived from actual code and I expect it to be not uncommon
in general. Maybe not exactly in this form but perhaps the matcher can catch a
few more cases.
Take this code:
extern void g(int);
void f1(int* a, int b, int c)
{
for (unsigned i = 0; i < 100; ++i)
g(a[i] == b ? c : b);
}
void f2(int* a)
{
for (unsigned i = 0; i < 100; ++i)
g(a[i] == 42 ? 10 : 42);
}
The function 'g' is called in each loop with one of two values which is the
opposite from the one that is match in the condition of the ternary operation.
This allows the respective loops to be rewritten as
for (unsigned i = 0; i < 100; ++i)
g(a[i] ^ c ^ b);
and
for (unsigned i = 0; i < 100; ++i)
g(a[i] ^ 10 ^ 42);
In the former case the c ^ b operation can be hoisted.
This should be faster and smaller in pretty much all situations and on all
platforms.