Skip to main content
Be Bitwise
x86 AssemblyControl Flow

Conditional Patterns

Conditional jumps handle most control flow, but they aren't the only game in town. x86-64 also gives you CMOVcc (conditional move) and SETcc (conditional set). Both let you pick values or convert flags into bits without branching, and that distinction has heavy consequences for performance and for side-channel security.

CMOVcc - Conditional Move

CMOVcc copies source to destination only when the condition is true. False, and the destination keeps its existing value. No jump fires either way.

nasm
; CMOV syntax: cmovCC destination, source
; destination must be a register, source can be register or memory
cmp rax, rbx
cmovl rax, rbx ; if rax < rbx (signed), rax = rbx
; otherwise rax stays the same

Each conditional jump has a CMOVcc twin:

nasm
cmove rax, rbx ; move if equal (ZF=1)
cmovne rax, rbx ; move if not equal (ZF=0)
cmovg rax, rbx ; move if greater (signed)
cmovge rax, rbx ; move if greater or equal (signed)
cmovl rax, rbx ; move if less (signed)
cmovle rax, rbx ; move if less or equal (signed)
cmova rax, rbx ; move if above (unsigned)
cmovae rax, rbx ; move if above or equal (unsigned)
cmovb rax, rbx ; move if below (unsigned)
cmovbe rax, rbx ; move if below or equal (unsigned)

Replacing an If/Else with CMOVcc

c
// C code
result = (x > y) ? x : y; // max(x, y)
nasm
; With conditional jump (branches)
cmp rdi, rsi
jge .take_x
mov rax, rsi ; result = y
jmp .done
.take_x:
mov rax, rdi ; result = x
.done:
; With CMOVcc (branchless)
mov rax, rdi ; assume result = x
cmp rdi, rsi
cmovl rax, rsi ; if x < y, result = y

Shorter code, zero jumps, and the same instruction count regardless of which path the data wants to take.

Key Concept: Why Branchless Matters

Modern CPUs use branch prediction to guess which way a conditional jump will go and speculatively execute instructions along the predicted path. When the prediction is wrong, the CPU must throw away that work (a "branch misprediction"), which costs 10-20 clock cycles. For data-dependent branches where the pattern is unpredictable (like sorting comparisons), CMOVcc avoids this penalty entirely because there is no branch to predict. Compilers use CMOVcc aggressively in hot loops.

SETcc - Conditional Set

SETcc writes a byte: 1 if the condition holds, 0 otherwise.

nasm
; SETcc destination (must be an 8-bit register or byte memory)
cmp rax, rbx
sete cl ; cl = 1 if rax == rbx, else cl = 0
setne cl ; cl = 1 if rax != rbx, else cl = 0
setg cl ; cl = 1 if rax > rbx (signed), else cl = 0
setl cl ; cl = 1 if rax < rbx (signed), else cl = 0
seta cl ; cl = 1 if rax > rbx (unsigned), else cl = 0
setb cl ; cl = 1 if rax < rbx (unsigned), else cl = 0

It's the conversion you reach for when you need a flag condition as a value to feed into arithmetic:

nasm
; Count how many elements equal zero
; rdi = array pointer, rsi = count
; returns count in rax
xor rax, rax ; count = 0
xor rcx, rcx ; i = 0
.loop:
cmp rcx, rsi
jge .done
cmp qword [rdi + rcx*8], 0
sete dl ; dl = 1 if element is zero, else 0
movzx rdx, dl ; zero-extend to 64 bits
add rax, rdx ; count += (element == 0) ? 1 : 0
inc rcx
jmp .loop
.done:
ret

Jump Tables (Switch Statements)

A long switch statement starts to drag once chained if/else comparisons stack up. A jump table gives you O(1) dispatch:

c
// C switch
switch (op) {
case 0: add_handler(); break;
case 1: sub_handler(); break;
case 2: mul_handler(); break;
case 3: div_handler(); break;
default: error_handler(); break;
}
nasm
; Jump table implementation
; rdi = op (0-3)
dispatch:
cmp rdi, 3
ja .default ; if op > 3, go to default
lea rax, [rel .table] ; base of jump table
movsxd rdx, dword [rax + rdi*4] ; load relative offset
add rax, rdx ; compute absolute address
jmp rax ; jump to handler
; The jump table stores 32-bit offsets relative to its own start.
; It sits in .text, after the jmp, so it's never executed as code.
.table:
dd .case_add - .table
dd .case_sub - .table
dd .case_mul - .table
dd .case_div - .table
.case_add:
; handle add...
jmp .done
.case_sub:
; handle sub...
jmp .done
.case_mul:
; handle mul...
jmp .done
.case_div:
; handle div...
jmp .done
.default:
; handle error...
.done:

Keeping the table in the same section as the handlers makes each dd a plain constant the assembler can work out on its own. Compilers usually put the table in .rodata instead, which needs the assembler and linker to resolve a difference between two sections; GNU as handles that, but in NASM it's simplest to keep both ends of the subtraction in one section.

Jump tables turn up everywhere in compiled code. Spotting them in disassembly is a core reversing skill: an array of addresses or relative offsets, followed by an indirect jump, almost always means a switch statement underneath.

Follow one op through the dispatch. The bounds check is the only thing standing between op and an arbitrary indirect jump, and it uses ja, the unsigned compare, on purpose. An op of -1 is 0xFFFFFFFFFFFFFFFF unsigned, far above 3, so it goes to .default. With a signed jg, -1 would pass and the code would load table[-1], whatever four bytes sit just before the table, and jump there.

Security Note: Branch Prediction Side Channels (Spectre)

The Spectre class of vulnerabilities exploits branch prediction to leak data across security boundaries. When the CPU mispredicts a bounds check, it speculatively runs the code behind it and can load data that should be out of bounds. The results are thrown away, but the cache lines they touched stay warm, and an attacker can measure that. A CMOV isn't predicted, so its result is never guessed. That doesn't stop the surrounding branches from speculating, though, so the standard Spectre v1 defence uses a branchless sequence to clamp the index rather than to avoid speculation: after the bounds check, a cmp plus sbb (or cmov) builds an all-ones or all-zeros mask and ANDs it into the index, so even a mispredicted path can only read element 0. The Linux kernel wraps this up as array_index_nospec().

Constant-Time Comparison

In crypto code, comparing two byte strings has to take the same time no matter where they differ. The branchless pattern:

nasm
; Constant-time comparison of two buffers
; rdi = buf1, rsi = buf2, rdx = length
; Returns: rax = 0 if equal, nonzero if different
constant_time_cmp:
xor rax, rax ; accumulator = 0
xor rcx, rcx ; index = 0
.loop:
cmp rcx, rdx
jge .done
mov r8b, [rdi + rcx] ; load byte from buf1
xor r8b, [rsi + rcx] ; XOR with byte from buf2
or al, r8b ; accumulate differences (no branch!)
inc rcx
jmp .loop
.done:
; rax is 0 only if all bytes matched
; The loop ALWAYS runs for the full length -- no early exit
ret

The trick: XOR lands on 0 for matching bytes and nonzero for mismatches. OR rolls those differences into the accumulator without branching. The loop always runs for the whole buffer, so timing reveals nothing about where the first mismatch happens.

Branchless Min and Max

nasm
; Branchless min(rdi, rsi) -> rax
mov rax, rdi
cmp rdi, rsi
cmovg rax, rsi ; if rdi > rsi, take rsi (the smaller one)
; Branchless max(rdi, rsi) -> rax
mov rax, rdi
cmp rdi, rsi
cmovl rax, rsi ; if rdi < rsi, take rsi (the larger one)
; Branchless absolute value of rdi -> rax
mov rax, rdi
neg rdi ; rdi = -rdi, and SF now describes -rdi
cmovns rax, rdi ; if -rdi is not negative, the original was <= 0: take -rdi
; (neg sets SF from its result, so test "not signed" on the negated value.
; INT64_MIN stays INT64_MIN, just as abs() would overflow in C.)

Branchless Conditional Add

nasm
; Add bonus to score only if player has the powerup flag
; rdi = score, rsi = bonus, rdx = flags
xor eax, eax ; rax = 0, the bonus if the flag is clear
test rdx, POWERUP_FLAG
cmovnz rax, rsi ; rax = bonus if flag set, else 0
add rdi, rax ; score += conditional bonus

Summary

TechniqueWhen to usePerformanceSecurity
Conditional jumpsMost control flowGood with predictable patternsTiming-variable
CMOVccSmall if/else, branchless neededBest for unpredictable patternsConstant-time
SETccBoolean result from comparisonGood for flag-to-value conversionConstant-time
Jump tablesMany cases (switch)O(1) dispatchNeeds bounds check

What is Next

The next lesson is a hands-on challenge that pulls the whole module together: comparisons, loops, conditional logic, branchless patterns, all wired into one program.