Skip to main content
skill CX Codex

branch-prediction-and-speculation — Claude Code skill

branch-prediction-and-speculation is a Claude Code skill that explains CPU branch prediction and speculative execution to help optimize hot loops and protect code from cache timing leaks.

MIT 382 installs ★ 298 updated 2026-06-27

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a claude-code
Open on GitHub

What branch-prediction-and-speculation does

A processor guesses which path a conditional branch will take and speculatively executes instructions before the actual outcome is resolved. Correct prediction carries near-zero penalty; misprediction costs 10–20+ cycles to flush and restart. The skill teaches how to profile mispredict events using perf, when to use compiler hints like __builtin_expect, and how to refactor into branchless code via conditional move or lookup tables.

Speculative execution—the same mechanism that opened Spectre and Meltdown—allows the CPU to cache data from addresses computed on secret values, even if the speculation later rolls back. The skill explains why this breaks cryptographic code and how the kernel defends with retpoline, IBRS, and KPTI. For applications, this means: if your conditionals depend on secrets, constant-time algorithms without secret-dependent branches are essential.

The skill activates on questions about loop performance, side-channel security, and microarchitectural details. Helps debug why seemingly optimized code underperforms or verify that cryptographic implementations do not leak through cache and prediction.

What it helps with

  • optimize a hot loop with unpredictable branches
  • protect cryptographic functions from Spectre-style cache timing leaks
  • decide between __builtin_expect hints and branchless refactor
  • understand how kernel mitigations (KPTI, retpoline) affect performance
  • profile and diagnose misprediction penalty in production code

Example prompts for the agent

  • Optimize this loop comparison to reduce branch misprediction stalls
  • Rewrite the password comparison function as constant-time against Spectre
  • Explain what perf stat -e branches,branch-misses shows and how to interpret it

How to install branch-prediction-and-speculation

1Skills CLI (Vercel)

npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a claude-code

2Manually: put the files in place

~/.claude/skills/branch-prediction-and-speculation/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/branch-prediction-and-speculation/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about branch-prediction-and-speculation

How do I install branch-prediction-and-speculation in Claude Code?

Run npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a claude-code, then find the configuration at ~/.claude/skills/branch-prediction-and-speculation/SKILL.md.

What does this skill do?

Covers how CPUs predict branches and execute speculatively, why speculation opened security holes (Spectre/Meltdown), and how to write fast and secure code through profiling, branchless refactors, and constant-time patterns.

When does the skill activate?

On questions about loop performance, branch misprediction, speculative execution, Spectre/Meltdown, kernel mitigations, and constant-time cryptography.

Source text

SKILL.md · MIT
---
name: branch-prediction-and-speculation
description: 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.
---

# Branch Prediction and Speculation

## Purpose

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.

## When to Use

- Hot loop branchy code underperforms expectations
- Evaluating `likely`/`unlikely` or branchless refactors
- Understanding kernel `retpoline`, IBRS, and similar mitigations
- Secure coding around secret-dependent branches

## Workflow

### 1. Branch predictor basics

```
Fetch sees conditional branch
├── Predict direction (taken / not-taken)
├── Speculatively execute predicted path
└── On resolve:
    ├── Correct → commit, ~0 penalty (deep pipelines still cost on mispredict)
    └── Wrong → squash, refill from correct PC (10–20+ cycles typical)
```

Patterns: backward branches often predicted taken (loops); forward not-taken.

### 2. Performance patterns

```c
/* Predictable — tight loop backward branch */
for (int i = 0; i < n; i++)
    sum += a[i];

/* Unpredictable — data-dependent */
if (data[i] > threshold)  /* hard to predict */
    rare_path();
```

Techniques: branchless `cmov`/select, lookup tables, sorting data to reduce branches, splitting hot/cold paths.

```c
/* Branchless min (integer) */
int m = a < b ? a : b;  /* compiler may lower to cmov */
```

### 3. Compiler hints (use sparingly)

```c
#define likely(x)   __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)

if (unlikely(ptr == NULL))
    return -EINVAL;
```

Measure with `perf` — hints are not magic on modern predictors.

### 4. Speculative execution and side channels

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):**

- Kernel: retpoline, IBRS/IBPB, STIBP (see kernel `cpu_show_mitigations`)
- Compiler: speculative load hardening (`-mspeculative-load-hardening` on Clang)
- Code: constant-time crypto — no secret-dependent branches or indices

Meltdown (Intel): user load from kernel mapping — fixed by KPTI (separate page tables).

### 5. Measurement

```bash
perf stat -e branches,branch-misses ./app
```

High `branch-misses` ratio → investigate hot branches.

### 6. Agent usage

```
/branch-prediction-and-speculation Make this comparison function constant-time against Spectre-style leakage
```

## Common Problems

| 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 |

## Related Skills

- `skills/computer-architecture/cpu-pipelines-and-hazards` — control hazards
- `skills/security/kernel-security` — KPTI, CET, speculation mitigations
- `skills/low-level-programming/cpu-cache-opt` — cache timing channels
- `skills/profilers/hardware-counters` — branch-misses event
- `skills/runtimes/binary-hardening` — userspace hardening overlap

© mohitmishra786 · MIT · mohitmishra786/low-level-dev-skills

Similar skills

All skills for Security →

From the same set140

The whole set →
apple-silicon A skill for developers building on Apple Silicon: tuning code for unified memory, Metal Performance Shaders, Instruments profiling, Rosetta 2 behavior, and 16KB page size quirks. CX Codex +1 383installs code-generation-and-backends code-generation-and-backends explains LLVM backend stages, from IR legalization to assembly output. Use it to investigate llc, TableGen patterns, or the outline of a new target port. CX Codex +1 382installs jit-compilation jit-compilation teaches the agent to build a JIT: LLVM ORC and LLJIT, Cranelift, inline caches, trampolines, Rust dynasm. Useful for interpreter hot paths and REPLs. CX Codex +1 382installs kernel-testing Skill for Linux kernel testing: KUnit for unit tests, kselftest for regression checks, syzkaller for fuzzing, and LTP for syscall compatibility. Activates on kunit.py queries, syzkaller config, or KernelCI setup. CX Codex +1 382installs os-dev-scratch os-dev-scratch is a Claude Code skill for building a minimal x86-64 OS, from boot stages to drivers and context switching. It activates on questions about kernel boot, interrupts, page tables, or QEMU. CX Codex +1 381installs kernel-security kernel-security — a skill for SELinux and AppArmor policies, seccomp-bpf sandboxing, KASLR, Intel CET, ARM PAC and BTI. Write LSM rules, triage kernel CVEs, and configure kernel mitigations. CX Codex +1 381installs peripherals-from-datasheet peripherals-from-datasheet guides driver development directly from MCU reference manuals. Helpful when writing bare-metal register code without a vendor HAL or migrating peripherals across chips. CX Codex +1 380installs platform-device-model The platform-device-model skill explains Linux platform-driver binding, probe and remove, sysfs, device properties, and deferred probing for kernel work. CX Codex +1 378installs

Project sponsors

Companies that keep this analytics open