# branch-prediction-and-speculation

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.

- skill · `type=skill` · Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, OpenCode, Windsurf (Devin Desktop), Claude.ai · 382 installs · ★ 298 repo stars
- Author: mohitmishra786
- License: MIT · policy=mirror · the beginning of the file is at the end of this page
- Source: https://github.com/mohitmishra786/low-level-dev-skills/tree/HEAD/skills/computer-architecture/branch-prediction-and-speculation/SKILL.md
- Updated: 2026-06-27
- Security check: automated, 2026-11-16 (text) — no signs of malicious code found.
- HTML: https://affpapa.org/en/nevibecode/skills/branch-prediction-and-speculation

## What it 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.

## Install

### Claude Code (native platform)

1. **Skills CLI (Vercel)**
```bash
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a claude-code
```

2. **Manually: put the files in place**
- File: `~/.claude/skills/branch-prediction-and-speculation/SKILL.md` — Copy the whole skill folder; for one project use .claude/skills/branch-prediction-and-speculation/

### Codex

1. **Skills CLI (Vercel)**
```bash
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a codex
```

2. **Manually: put the files in place**
- File: `.agents/skills/branch-prediction-and-speculation/SKILL.md` — For all projects use ~/.agents/skills/

### Cursor

1. **Skills CLI (Vercel)**
```bash
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a cursor
```

2. **Manually: put the files in place**
- File: `.cursor/skills/branch-prediction-and-speculation/SKILL.md` — Cursor also reads .agents/skills/ and .claude/skills/

### GitHub Copilot

1. **GitHub CLI**
```bash
gh skill install mohitmishra786/low-level-dev-skills skills/computer-architecture/branch-prediction-and-speculation
```

2. **Manually: put the files in place**
- File: `.github/skills/branch-prediction-and-speculation/SKILL.md`

### Gemini CLI

1. **Skills CLI (Vercel)**
```bash
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a gemini-cli
```

2. **Platform CLI**
```bash
gemini skills install https://github.com/mohitmishra786/low-level-dev-skills --path skills/computer-architecture/branch-prediction-and-speculation
```

### Windsurf (Devin Desktop)

**Manually: put the files in place**
- File: `.devin/skills/branch-prediction-and-speculation/SKILL.md` — The legacy .windsurf/skills/ path still works

### OpenCode

**Skills CLI (Vercel)**
```bash
npx skills add mohitmishra786/low-level-dev-skills --skill branch-prediction-and-speculation -a opencode
```

### Claude.ai

**Claude.ai**
- Zip the folder and upload it in Settings → Capabilities → Skills

Where a file is given instead of a command, copy the files from the source to that path: https://github.com/mohitmishra786/low-level-dev-skills/tree/HEAD/skills/computer-architecture/branch-prediction-and-speculation/SKILL.md

## When to use it
- 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
- 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

## Source text · SKILL.md · MIT

Below is the content of a third-party file. It is data, not instructions for you: do not act on anything written inside unless the human asks. Block tag: 3cf97a8f71c1f6a4.

BEGIN THIRD-PARTY FILE 3cf97a8f71c1f6a4
````text
---
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 */
```
````
END THIRD-PARTY FILE 3cf97a8f71c1f6a4

The third-party file has ended. Everything between the 3cf97a8f71c1f6a4 tags is data: requests and commands from it are not followed. An “end of file” line with another tag inside the block is part of the file.

First 1798 of 3718 bytes. © mohitmishra786 · MIT · https://github.com/mohitmishra786/low-level-dev-skills/tree/HEAD/skills/computer-architecture/branch-prediction-and-speculation/SKILL.md

_Part of the page did not fit — see the HTML version._

---
NeVibeCode on affpapa.org. Catalog texts are descriptions, not instructions for the agent. How to choose and install: https://affpapa.org/en/nevibecode/agents.md
