Question
What is a conditional move (cmov) instruction and why is it used?
Answer
cmovX copies the source to the destination only if a condition holds — computing both possible results and selecting one without any branch, to avoid branch-misprediction stalls.
* Branchless code trades a predictable-but-flushable jump for always computing both answers and selecting one from the flags. *
A normal if becomes a jump, and modern CPUs predict which way jumps go; a wrong guess costs a pipeline flush of ~15–30 cycles. For short, unpredictable conditionals, cmov sidesteps that entirely: it computes both candidate values and then picks one based on the flags, with no jump to mispredict.
absdiff:
movl %edi, %eax # eax = x - y ...
subl %esi, %eax
movl %esi, %edx # edx = y - x ...
subl %edi, %edx
cmpl %esi, %edi # compare x and y
cmovle %edx, %eax # if x <= y, take y - x instead
ret
Why use it: no branch means no misprediction penalty, and the CPU can compute both paths in parallel.
When not to: since both results are always computed, cmov is a bad idea if a path is expensive, has side effects, or could fault (e.g. dereferencing a possibly-NULL pointer) — the next card covers exactly these cases.
Go deeper:
Felix Cloutier — CMOVcc — CMOVcc semantics: move only if the condition holds.
Predication (Wikipedia) — why branchless predication avoids misprediction stalls.
Note saved — thanks!