by monocasa · 6y ago · 0 comments
if( value1 < 0 || value2 < 0 || value3 < 0 ) {
to temp = value1 | value2 | value3;
if( temp < 0 ) {
Taking a sort of hardware, Boolean logic view makes this possible, as VHDL generally does this when synthesed.This is most of the inner loop of a barycentric coordinate rasterizer, so I was pretty concerned about micro-optimizations when I was checking.
N.B. the || (logical or) operator is an "early out" operator whereas the | (binary or) operator is NOT
The compiler would need to look for special cases of value1, value2 and value3... such as: are any of them volatile, perhaps one refers to a memory mapped I/O device, perhaps one if actually a function call, or array dereference, or pointer dereference, what about value1 being a "char" which needs to be promoted before it can be or'd, what about any of the "values" being a constant < 0 which would short circuit the "if" statement and remove the need for any tests.
As I said, this is not as simple as it first appears.
A predicable branch is almost free in a modern processor.
Clang will optimize
bool swap_if(bool c,
int& a, int& b) {
int ta = a, tb = b;
a = (-c & tb)|((c-1) & ta);
b = (-c & ta)|((c-1) & tb);
return c;
}
into cmov instructions. Used in a quicksort partition loop as l += swap_if(
*r <= pv, *l, *r);
It makes quicksort fully 2x as fast as the usual branch.