liveBook · Manning

Branchless alternative

As explained in Hacking Cryptography

Branchless programming implements conditional behavior without control-flow paths that diverge according to input conditions.

A branchless alternative implements conditional behavior without allowing the input condition to select different control-flow paths. Instead of an if branch, it uses a conditional move such as CMOV, so the same instruction sequence executes whether the predicate is true or false. This avoids branch prediction based on secret-dependent conditions and can support constant-time implementations. section 10.5

Use the technique with these engineering rules:

  • Replace a conditional update with a predicate-controlled move rather than relying on an input-dependent branch. section 10.5
  • Check timing behavior with both irregular and predictable inputs; ordinary branches may run differently when branch prediction succeeds. section 10.5
  • Treat compiler and processor details as part of the implementation: the example uses GCC inline assembly and Intel CMOV instructions. section 10.5

Summing values above a threshold

A conventional loop adds array[i] only when array[i] exceeds 500. The branchless version initializes increment to zero, conditionally moves array[i] into increment with CMOVG, and then always adds increment. Both versions return the same sum, while the benchmark reports different timings for random and sorted arrays.

How Hacking Cryptography covers it

How deep it goes
Explains branch prediction, CMOV semantics, inline assembly, and a benchmark, but does not generalize beyond the demonstrated processor instruction.
Examples
Demonstrates threshold summation over random and sorted integer arrays using branching and CMOV-based implementations.
What it assumes
Assumes familiarity with C loops and comparisons while explaining branch prediction and CMOV behavior through a concrete summation task.
What you can do after
Build it from scratch using GCC inline assembly and CMOV to implement a conditional, branchless array operation.
How it connects
Connects constant-time programming with control flow, branch prediction, conditional moves, and inline assembly.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Hacking Cryptography. The section links point to the parts of the book it draws on.