Branch Prediction and Speculative Execution
See how modern CPUs predict branches and execute speculatively to hide latency, how mispredictions cost cycles, and how side effects led to Spectre-class attacks.
The Pipeline Problem
Modern CPUs are deeply pipelined, fetching and decoding many instructions ahead. But a conditional branch is a fork: the CPU does not yet know which path to fetch. Stalling would waste the whole pipeline.
Branch Prediction
To avoid stalls the CPU predicts which way a branch will go and keeps fetching. If correct, no time is lost. If wrong, the pipeline is flushed — a costly misprediction penalty of 15-20+ cycles.
All lessons in this course
- Cache Coherency and Performance
- Hand-Optimizing Critical Sections
- Buffer Overflows and Shellcode
- Branch Prediction and Speculative Execution