22.4. Avoiding conditional jumps by using flags (all processors)
The most important jumps to eliminate are conditional jumps, especially if they are poorly predictable. Sometimes it is possible to obtain the same effect as a branch by ingenious manipulation of bits and flags. For example you may calculate the absolute value of a signed number without branching:
CDQ XOR EAX,EDX SUB EAX,EDX(On PPlain and PMMX, use MOV EDX,EAX / SAR EDX,31 instead of CDQ).
The carry flag is particularly useful for this kind of tricks:
Setting carry if a value is zero: CMP [VALUE],1
Setting carry if a value is not zero: XOR EAX,EAX / CMP EAX,[VALUE]
Incrementing a counter if carry: ADC EAX,0
Setting a bit for each time the carry is set: RCL EAX,1
Generating a bit mask if carry is set: SBB EAX,EAX
Setting a bit on an arbitrary condition: SETcond AL
Setting all bits on an arbitrary condition: XOR EAX,EAX / SETNcond AL / DEC EAX
(remember to reverse the condition in the last example)
The following example finds the minimum of two unsigned numbers: if (b < a) a = b;
SUB EBX,EAX SBB ECX,ECX AND ECX,EBX ADD EAX,ECX
The next example chooses between two numbers: if (a != 0) a = b; else a = c;
CMP EAX,1 SBB EAX,EAX XOR ECX,EBX AND EAX,ECX XOR EAX,EBX
Whether or not such tricks are worth the extra code depends on how predictable a conditional jump would be, whether the extra pairing or scheduling opportunities of the branch-free code can be utilized, and whether there are other jumps following immediately after which could suffer the penalties of consecutive jumps.