npx skills add ...
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation
Branch prediction and speculation skill for CPU security and performance. Use when explaining branch predictors, mispredict penalties, speculative execution, Spectre/Meltdown mitigations, or branchless patterns. Activates on queries about branch prediction, speculative execution, Spectre, Meltdown, mispredict, or branchless code.
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation
Explain how modern CPUs predict branches, execute speculatively, recover on mispredict, and why speculation created side channels (Spectre/Meltdown) — linking performance tuning with security-aware low-level coding.
likely/unlikely or branchless refactorsretpoline, IBRS, and similar mitigationsPatterns: backward branches often predicted taken (loops); forward not-taken.
Techniques: branchless cmov/select, lookup tables, sorting data to reduce branches, splitting hot/cold paths.
Measure with perf — hints are not magic on modern predictors.
CPUs may execute instructions before branch outcome is known. If speculated path touches secret-dependent memory, cache state can leak (Spectre variant 1).
Mitigations (high level):
cpu_show_mitigations)-mspeculative-load-hardening on Clang)Meltdown (Intel): user load from kernel mapping — fixed by KPTI (separate page tables).
High branch-misses ratio → investigate hot branches.
| Symptom | Cause | Fix |
|---|---|---|
| Loop slower than expected | Mispredicted exit | Peel iterations; branchless tail |
likely no help | Predictor already good | Profile first |
| Secret leak in crypto | Branches on secret bytes | Constant-time algorithms |
| Mitigation regression | KPTI/retpoline overhead | Accept or isolate secrets |
| "Branchless" slower | CMOV still executes both | Benchmark on target CPU |
skills/computer-architecture/cpu-pipelines-and-hazards — control hazardsskills/security/kernel-security — KPTI, CET, speculation mitigationsskills/low-level-programming/cpu-cache-opt — cache timing channelsskills/profilers/hardware-counters — branch-misses eventskills/runtimes/binary-hardening — userspace hardening overlap/* Branchless min (integer) */
int m = a < b ? a : b; /* compiler may lower to cmov */#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
if (unlikely(ptr == NULL))
return -EINVAL;perf stat -e branches,branch-misses ./app/branch-prediction-and-speculation Make this comparison function constant-time against Spectre-style leakage