I was told that the branches in the code
int value = //some number;
if(value > some_other_value)
value *= 23;
else
value -= 5;
can be eliminated via bitwise masking (in order to enable SIMD optimization for the code):
const int Mask = (some_other_value-value)>>31;
value = ((value * 23)&Mask)|((value-5)&~Mask);
However, I do not understand how this works (even though I understand what operations are being used here and how the results will look in binary). Furthermore, how generally applicable is this? What if the original code was instead something like
if(value & 1 == 1)
value *= 23;
else
value -= 5;
Would the branch-removed code still be the same? Otherwise, what is the purpose of the mask and how should I go about creating it? What is happening here?
value == 1
andsome_other_value = INT_MIN
.1
's if the condition is true, and all0
's otherwise (note the comment from @Fanael though). Then, both possible values are calculated (value*23
andvalue-5
), but only one of them taken byand
-combining the results with the mask, and its negation respectively. One of theand
-combinations will be 0, the other one will contain the calculation result. The finalor
-operation combines them (effectively being an assignment since one operand of theor
-operation is 0)