Computer Architecture Overview
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Computer architecture
- Wikipedia: Von Neumann architecture
- Wikipedia: Memory hierarchy
- Book: Patterson and Hennessy, Computer Organization and Design (Arm edition)
- Book: Hennessy and Patterson, Computer Architecture: A Quantitative Approach
A computer processor does one simple thing over and over: fetch an instruction from memory, work out what it means, do it, and move on to the next one. Everything in this wiki is about doing that faster. Some techniques do more than one step at once (pipelining), some guess what comes next (branch prediction), some run independent instructions side by side (ILP), some keep data close (caches), and some use many processors together (multicore, GPUs).
> How to read this wiki. No prior hardware knowledge is assumed. Each page starts with an everyday analogy, then gives the real idea, then a diagram. Diagrams and worked examples are illustrative: they show the idea, not the exact design of any particular chip. Facts about Arm come from Arm's public architecture documents, named on each page.
Purpose and Scope
This wiki explains the main ideas of computer organisation and architecture for complete beginners:
| # | Page | One-line summary |
|---|---|---|
| 1 | Overview | This page: the big picture and a map of the wiki |
| 2 | Fundamentals | CPU, memory, instructions, the fetch-execute cycle, performance |
| 3 | Pipelining | An assembly line for instructions, and what breaks it |
| 4 | Branches and Remedies | Why if statements slow the pipeline, and branch prediction |
| 5 | Instruction-Level Parallelism | Superscalar, out-of-order execution, renaming, speculation |
| 6 | Memory and Ordering | Why other cores can see your writes in a surprising order |
| 7 | Caches and Coherence | Small fast memories, and keeping many copies in agreement |
| 8 | Multicore | Many processors on one chip, Amdahl's law |
| 9 | Multithreading | One core running several threads to stay busy |
| 10 | SIMD and GPUs | One instruction on many data items, and why GPUs are fast |
| 11 | Glossary | All the terms in one place |
How a compiler uses these ideas, for example to schedule instructions around pipeline delays, is covered in the Instruction Scheduling wiki and the LLVM IR wiki.
Organisation versus Architecture
The two words in the title mean different things:
| Term | Question it answers | Example |
|---|---|---|
| Architecture (instruction set architecture, ISA) | What can a program ask the processor to do? | "There is an ADD instruction that adds two 64-bit registers" (Arm A64) |
| Organisation (microarchitecture) | How does the hardware actually do it? | "This chip has 4 adders and runs ADD in 1 cycle, out of order" |
Many different chips share one architecture. A small phone core and a large server core can both run the same Arm program, but they are built very differently inside.
flowchart TD
P["Your program<br/>(machine code)"] --> ISA["Instruction set architecture<br/>the contract: Arm A64, x86-64, RISC-V"]
ISA --> M1["Small core<br/>in-order, 1 instruction per cycle"]
ISA --> M2["Big core<br/>out-of-order, 8 instructions per cycle"]
ISA --> M3["Server core<br/>big caches, many cores"]
The Big Picture
flowchart LR
subgraph CPU["Processor chip"]
direction TB
C1["Core 0<br/>pipeline + registers"] --- L1a["L1 cache"]
C2["Core 1<br/>pipeline + registers"] --- L1b["L1 cache"]
L1a --- L2["Shared L2 / L3 cache"]
L1b --- L2
G["GPU<br/>many simple cores"] --- L2
end
L2 --- RAM["Main memory (DRAM)"]
RAM --- D["Storage (SSD)"]
Read the picture from the inside out:
- A core runs instructions. Inside it is a pipeline (Pipelining) that overlaps instructions, and registers, a few dozen very fast storage slots.
- Each core has a small, fast cache that keeps recently used data close (Caches and Coherence).
- Several cores share bigger, slower caches and finally main memory (Multicore).
- A GPU has many simple cores that all do the same thing to different data (SIMD and GPUs).
Sources: Wikipedia: Computer architecture, Wikipedia: Memory hierarchy
Why Speed Is Hard: Three Walls
For decades chips got faster mainly by raising the clock speed. That stopped around 2005, and the reasons explain why the rest of this wiki exists:
| Wall | Problem | Answer the industry chose | Page |
|---|---|---|---|
| Memory wall | Memory got faster far more slowly than processors. A trip to main memory costs hundreds of cycles | Caches, prefetching | Caches and Coherence |
| ILP wall | There is only so much independent work in one stream of instructions | Out-of-order execution, but with limits | ILP |
| Power wall | A faster clock burns much more power and heat | More cores, SIMD units, GPUs, instead of a faster clock | Multicore, SIMD and GPUs |
flowchart TD
A["Goal: run programs faster"] --> B["Do each step faster<br/>higher clock"]
A --> C["Do steps at the same time<br/>parallelism"]
A --> D["Wait less for data<br/>caches"]
B --> B1["Limited by power and heat"]
C --> C1["Within one instruction stream<br/>pipelining, ILP"]
C --> C2["Across many threads<br/>multicore, multithreading"]
C --> C3["Across many data items<br/>SIMD, GPU"]
Key Points
- Architecture is the contract a program sees; organisation is how a chip implements it.
- A core repeatedly fetches, decodes and executes instructions; most tricks overlap or skip waiting in that loop.
- Clock speed stopped rising quickly, so modern speed comes from parallelism and caches.
Fundamentals: CPU, Memory and Instructions
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Von Neumann architecture
- Wikipedia: Instruction set architecture
- Wikipedia: Memory hierarchy
- Arm: Arm Architecture Reference Manual for A-profile architecture (DDI 0487)
- Book: Patterson and Hennessy, Computer Organization and Design (Arm edition), chapters 1-2
A computer is a machine that follows a list of very small instructions such as "add these two numbers" or "copy this number from memory". This page explains the parts of a computer, what an instruction looks like, the loop the processor runs forever, and how to measure how fast it is.
Purpose and Scope
This page covers the von Neumann model (processor, memory, input/output), registers, the ALU and control unit, the instruction set, the fetch-decode-execute cycle, RISC versus CISC, and the basic performance equation. Overlapping instructions is the subject of Pipelining.
The Kitchen Analogy
Think of a cook in a kitchen:
| Kitchen | Computer | Notes |
|---|---|---|
| The cook | Processor (CPU) | Does the work |
| The recipe book | Program in memory | A numbered list of steps |
| A bookmark | Program counter (PC) | Which step is next |
| The cook's two hands | Registers | A few things held right now; instant to use |
| The worktop | Cache | Small, close, fast |
| The pantry | Main memory (RAM) | Large, but a walk away |
| The supermarket | Storage (SSD) | Huge, very slow to reach |
The cook reads a step, does it, moves the bookmark, and repeats. A processor does exactly that, billions of times per second.
The Von Neumann Model
Almost every computer follows the design described by John von Neumann in 1945: one memory holds both the program and its data, and the processor reads both from it over a shared path.
flowchart LR
subgraph CPU["Processor (CPU)"]
CU["Control unit<br/>decides what to do"]
ALU["ALU<br/>arithmetic and logic"]
REG["Registers<br/>X0..X30, SP, PC"]
CU --> ALU
REG <--> ALU
end
MEM["Memory<br/>program + data"] <-->|"address, data"| CPU
IO["Input / output<br/>keyboard, screen, network"] <--> CPU
| Part | Job |
|---|---|
| Registers | Tiny, very fast storage inside the CPU. Arm A64 has 31 general-purpose 64-bit registers, X0 to X30 |
| ALU (arithmetic logic unit) | Adds, subtracts, compares, does AND/OR/shift |
| Control unit | Reads each instruction and tells the other parts what to do |
| Program counter (PC) | Holds the memory address of the next instruction |
| Memory | A long array of bytes, each with a numbered address |
Because instructions and data share the path to memory, the processor often waits for memory. This is called the von Neumann bottleneck, and caches (Caches and Coherence) exist mainly to ease it.
Sources: Wikipedia: Von Neumann architecture
What an Instruction Looks Like
An instruction is a number, usually 4 bytes on Arm, that encodes one small operation. Written in assembly language it is readable:
// illustrative Arm A64 assembly for: total = price * qty + tax
LDR X1, [X0] // load price from memory address in X0 into X1
LDR X2, [X0, #8] // load qty from the next 8 bytes
MUL X3, X1, X2 // X3 = X1 * X2
LDR X4, [X0, #16] // load tax
ADD X5, X3, X4 // X5 = X3 + X4
STR X5, [X0, #24] // store total back to memory
Instructions fall into a few groups:
| Group | Examples | What it does |
|---|---|---|
| Arithmetic / logic | ADD, SUB, MUL, AND, LSL | Compute on registers |
| Memory | LDR (load), STR (store) | Move data between memory and registers |
| Control flow | B (branch), B.EQ, CBZ, BL (call), RET | Change which instruction runs next |
| Compare | CMP | Set condition flags used by conditional branches |
Arm is a load/store architecture: arithmetic only works on registers, so data must be loaded first and stored afterwards. That is why the example above has more LDRs than calculations.
Sources: Wikipedia: Instruction set architecture
The Fetch-Decode-Execute Cycle
The processor runs this loop forever:
flowchart TD
F["1. Fetch<br/>read instruction at PC from memory"] --> D["2. Decode<br/>what operation? which registers?"]
D --> E["3. Execute<br/>ALU does the work"]
E --> M["4. Memory<br/>load or store if needed"]
M --> W["5. Write back<br/>put result in a register"]
W --> P["6. Update PC<br/>next instruction, or branch target"]
P --> F
Following ADD X5, X3, X4 through the loop:
| Step | What happens |
|---|---|
| Fetch | Read the 4 bytes at the address in PC |
| Decode | It is an ADD; sources X3 and X4; destination X5 |
| Execute | ALU computes X3 + X4 |
| Memory | Nothing to do: ADD does not touch memory |
| Write back | Result goes into X5 |
| Update PC | PC = PC + 4 |
A simple processor does all six steps for one instruction before starting the next. Pipelining overlaps them.
RISC and CISC
| RISC (reduced instruction set) | CISC (complex instruction set) | |
|---|---|---|
| Examples | Arm, RISC-V | x86 |
| Instruction size | Fixed (Arm A64: 4 bytes) | Variable (x86: 1 to 15 bytes) |
| Memory access | Only loads and stores | Many instructions can read memory directly |
| Decoding | Simple | Complex |
| Instructions per program | More | Fewer |
In practice modern x86 chips translate their complex instructions into simple RISC-like internal operations ("micro-ops"), so inside, big RISC and CISC cores look much alike.
Measuring Performance
The time a program takes is:
Execution time = Instruction count × CPI × Clock period
| Term | Meaning | Decided by |
|---|---|---|
| Instruction count | How many instructions run | Program, compiler, ISA |
| CPI (cycles per instruction) | Average clock cycles per instruction | Microarchitecture: pipeline, caches, prediction |
| Clock period | Length of one cycle (1 / frequency) | Circuit design and power |
IPC (instructions per cycle) is 1 / CPI. Big modern cores aim for IPC above 1 by running several instructions per cycle (ILP).
Worked Example
A program runs 2 billion instructions on a 2 GHz processor (clock period 0.5 ns).
| Design | CPI | Time |
|---|---|---|
| Simple, non-pipelined, 5 cycles per instruction | 5 | 2×10⁹ × 5 × 0.5 ns = 5.0 s |
| Pipelined, ideal | 1 | 2×10⁹ × 1 × 0.5 ns = 1.0 s |
| Pipelined with stalls (cache misses, branches) | 1.5 | 1.5 s |
| Superscalar, 2 per cycle | 0.5 | 0.5 s |
The rest of this wiki is mostly about lowering CPI.
The Memory Hierarchy
Fast memory is small and expensive; big memory is slow. So computers use layers:
flowchart TD
R["Registers<br/>~1 KB, under 1 ns"] --> L1["L1 cache<br/>32-64 KB per core, ~1 ns"]
L1 --> L2["L2 cache<br/>0.5-2 MB, ~3-5 ns"]
L2 --> L3["L3 / system cache<br/>several MB shared, ~10-20 ns"]
L3 --> RAM["Main memory (DRAM)<br/>GBs, ~80-100 ns"]
RAM --> SSD["Storage (SSD)<br/>TBs, ~100 µs"]
Sizes and times are typical orders of magnitude, not figures for a particular chip. The trick that makes this work is locality: programs tend to reuse recent data (temporal locality) and use data next to recent data (spatial locality). See Caches and Coherence.
Sources: Wikipedia: Memory hierarchy
Key Points
- A CPU has registers, an ALU and a control unit; memory holds both program and data.
- The processor loops: fetch, decode, execute, memory, write back, update PC.
- Time = instructions × CPI × clock period; most architecture tricks reduce CPI.
Pipelining
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Instruction pipelining
- Wikipedia: Hazard (computer architecture)
- Book: Patterson and Hennessy, Computer Organization and Design (Arm edition), chapter 4
Pipelining is an assembly line for instructions. Instead of finishing one instruction completely before starting the next, the processor splits the work into stages and keeps every stage busy with a different instruction. Each instruction still takes the same time from start to finish, but a new one finishes every cycle.
Purpose and Scope
This page covers the laundry analogy, the classic five-stage pipeline, speedup, and the three kinds of hazard (structural, data, control) with their fixes: stalls, forwarding and reordering. Branches get their own page, Branches and Remedies.
The Laundry Analogy
Doing four loads of laundry, each needing wash (30 min), dry (30 min), fold (30 min):
One at a time: wash, dry and fold load 1, then start load 2. Four loads take 4 × 90 = 360 minutes.
Pipelined: as soon as load 1 moves to the dryer, load 2 goes in the washer.
| Time (min) | 0-30 | 30-60 | 60-90 | 90-120 | 120-150 | 150-180 |
|---|---|---|---|---|---|---|
| Washer | Load 1 | Load 2 | Load 3 | Load 4 | ||
| Dryer | Load 1 | Load 2 | Load 3 | Load 4 | ||
| Folding | Load 1 | Load 2 | Load 3 | Load 4 |
Four loads take 180 minutes. Each load still takes 90 minutes, but one finishes every 30 minutes once the line is full. That is the whole idea: pipelining improves throughput (jobs per hour), not latency (time for one job).
The Five-Stage Pipeline
The textbook pipeline uses the steps from Fundamentals as stages:
flowchart LR
IF["IF<br/>Instruction fetch"] --> ID["ID<br/>Decode, read registers"]
ID --> EX["EX<br/>Execute (ALU)"]
EX --> MEM["MEM<br/>Memory access"]
MEM --> WB["WB<br/>Write back"]
Between stages sit pipeline registers that hold each instruction's partial results, so each stage works on its own instruction independently.
Five instructions flowing through (each column is one clock cycle):
| Instruction | C1 | C2 | C3 | C4 | C5 | C6 | C7 | C8 | C9 |
|---|---|---|---|---|---|---|---|---|---|
| I1 | IF | ID | EX | MEM | WB | ||||
| I2 | IF | ID | EX | MEM | WB | ||||
| I3 | IF | ID | EX | MEM | WB | ||||
| I4 | IF | ID | EX | MEM | WB | ||||
| I5 | IF | ID | EX | MEM | WB |
From cycle 5 onward one instruction finishes every cycle, so the ideal CPI is 1.
How Much Faster?
With k stages of equal length, the ideal speedup approaches k. For n instructions:
Unpipelined time = n × k cycles
Pipelined time = k + (n − 1) cycles (k to fill the pipe, then 1 per instruction)
For 1000 instructions and 5 stages: 5000 versus 1004 cycles, a speedup of about 4.98.
In real chips the speedup is lower because stages are not equal (the slowest stage sets the clock), pipeline registers add delay, and hazards force the pipeline to wait.
Sources: Wikipedia: Instruction pipelining
Hazards: When the Assembly Line Breaks
A hazard is a situation where the next instruction cannot do its stage in the next cycle.
flowchart TD
H["Hazard"] --> S["Structural<br/>two instructions need the same hardware"]
H --> D["Data<br/>an instruction needs a result not yet produced"]
H --> C["Control<br/>we don't know which instruction comes next"]
S --> S1["Fix: duplicate hardware<br/>(separate instruction and data caches)"]
D --> D1["Fix: forwarding, stalls, reordering"]
C --> C1["Fix: branch prediction<br/>(see Branches page)"]
Structural Hazards
If instruction fetch (IF) and a load (MEM) both need memory in the same cycle and there is only one memory port, one must wait. Real processors avoid this with separate L1 instruction and data caches.
Data Hazards
ADD X1, X2, X3 // writes X1 in WB (cycle 5)
SUB X4, X1, X5 // wants X1 in ID (cycle 3) -- too early!
SUB reads X1 two cycles before ADD writes it. This is a read-after-write (RAW) dependence, the only kind that is a true dependence.
| Name | Pattern | Is it real? |
|---|---|---|
| RAW (read after write) | I2 reads what I1 writes | Yes, a true dependence: I2 needs I1's value |
| WAR (write after read) | I2 writes what I1 reads | Only a name clash; fixed by register renaming (ILP) |
| WAW (write after write) | I2 writes what I1 writes | Only a name clash; fixed by renaming |
Fix 1: Stall. Insert empty cycles ("bubbles") until the value is ready.
| C1 | C2 | C3 | C4 | C5 | C6 | C7 | C8 | |
|---|---|---|---|---|---|---|---|---|
| ADD | IF | ID | EX | MEM | WB | |||
| SUB | IF | stall | stall | ID | EX | MEM | WB |
Two wasted cycles.
Fix 2: Forwarding (bypassing). The result of ADD exists at the end of its EX stage (cycle 3). Extra wires send it straight to the ALU input for SUB's EX stage in cycle 4, without waiting for write-back.
flowchart LR
subgraph ADD["ADD X1, X2, X3"]
A1["IF"] --> A2["ID"] --> A3["EX<br/>X1 computed"] --> A4["MEM"] --> A5["WB"]
end
subgraph SUB["SUB X4, X1, X5"]
B1["IF"] --> B2["ID"] --> B3["EX<br/>uses X1"] --> B4["MEM"] --> B5["WB"]
end
A3 -->|"forward"| B3
No stall at all.
The load-use case. A load only gets its data at the end of MEM, so forwarding cannot fully hide it:
LDR X1, [X0] // X1 available after MEM (cycle 4)
ADD X2, X1, X3 // needs X1 at start of EX (cycle 4) -> 1-cycle stall
Fix 3: Reorder. The compiler (or the hardware, see ILP) moves an independent instruction into the gap:
// before: 1 stall // after: no stall
LDR X1, [X0] LDR X1, [X0]
ADD X2, X1, X3 LDR X4, [X0, #8] // independent, fills the gap
LDR X4, [X0, #8] ADD X2, X1, X3
This is exactly what a compiler's instruction scheduler does, see the Instruction Scheduling wiki.
Sources: Wikipedia: Hazard (computer architecture)
Control Hazards
After a branch the processor does not know which instruction to fetch next until the branch is resolved, several stages later. That is big enough to need its own page: Branches and Remedies.
Deeper Pipelines
Splitting work into more, shorter stages allows a faster clock. Modern high-performance cores have well over 10 stages. The cost is that each hazard wastes more cycles: a branch resolved in stage 15 throws away up to 14 stages of work if it was guessed wrong.
| Pipeline depth | Clock | Cost of a mistake |
|---|---|---|
| Short (5 stages) | Slower | Small |
| Deep (15-20 stages) | Faster | Large |
Key Points
- Pipelining overlaps instruction stages; it improves throughput, not the latency of one instruction.
- Hazards are structural (shared hardware), data (RAW dependences) or control (branches).
- Forwarding removes most data stalls; a load followed immediately by its use still stalls unless reordered.
Branches and Remedies
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Branch predictor
- Wikipedia: Hazard (computer architecture)
- Wikipedia: Speculative execution
- Book: Hennessy and Patterson, Computer Architecture: A Quantitative Approach, chapter 3
A branch is the processor's version of a fork in the road: an if, a loop test or a function call. The pipeline needs to fetch the next instruction every cycle, but it only learns which way the branch goes several stages later. Waiting wastes cycles; guessing is faster but sometimes wrong. This page explains the problem and the remedies, from simple stalls to modern branch predictors.
Purpose and Scope
This page covers why branches cause control hazards, the cost of waiting, static prediction, dynamic prediction (1-bit, 2-bit counters, history-based predictors), the branch target buffer, the return stack, what happens on a misprediction, and branch-free code. The out-of-order machinery that lets a core run far ahead of a predicted branch is on ILP.
The Fork-in-the-Road Analogy
You are driving and reach a junction, but the sign telling you which way to go is 5 km past the junction. You can:
| Option | Processor equivalent | Cost |
|---|---|---|
| Stop and wait until someone tells you | Stall | Always lose time |
| Guess a direction and keep driving; turn back if wrong | Predict and speculate | Free if right, expensive if wrong |
| Remember which way you went last time here | Dynamic prediction | Usually right for repeated trips |
Why Branches Hurt the Pipeline
// illustrative: if (x == 0) y = 1; else y = 2;
CMP X0, #0
B.NE else // which instruction comes next?
MOV X1, #1
B done
else:
MOV X1, #2
done:
In the five-stage pipeline from Pipelining, the branch is fetched in IF but its outcome is only known in EX. Meanwhile the fetch stage has to fetch something in the next two cycles.
| Cycle | C1 | C2 | C3 | C4 |
|---|---|---|---|---|
B.NE | IF | ID | EX (outcome known) | MEM |
| next? | IF ? | ID ? | ||
| next? | IF ? |
flowchart TD
F["Fetch a branch"] --> Q{"Outcome known yet?"}
Q -->|"No (most of the time)"| C{"What to do?"}
C --> S["Stall: fetch nothing<br/>lose cycles on every branch"]
C --> P["Predict: fetch the guessed path"]
P --> R{"Guess right?"}
R -->|"Yes"| OK["No time lost"]
R -->|"No"| FL["Flush wrong instructions<br/>restart at correct path"]
About one instruction in five or six is a branch in typical code, so stalling on every branch would make the processor much slower. In a deep pipeline the outcome may be known 10-20 stages after fetch, which makes waiting far worse.
Sources: Wikipedia: Hazard (computer architecture)
Remedy 1: Resolve Branches Earlier
Extra hardware can compare registers in the ID stage instead of EX, so only one cycle is lost instead of two. This helps short pipelines but not deep ones.
Remedy 2: Static Prediction
The guess is fixed and does not learn:
| Rule | Reasoning |
|---|---|
| Always predict not taken | Simplest: just keep fetching the next instruction |
| Backward taken, forward not taken (BTFN) | A branch jumping backwards is usually a loop, which repeats; forward branches often skip rare cases |
| Compiler hints | The compiler places the likely path as the fall-through, using profile data or __builtin_expect |
Remedy 3: Dynamic Prediction
The hardware remembers what each branch did before.
1-bit Predictor
Store one bit per branch: "taken last time" or "not taken last time". Predict the same again.
Problem: a loop that runs 10 times then exits. Each time the loop is entered:
| Visit | Actual | 1-bit predicts | Result |
|---|---|---|---|
| Iterations 1-9 | Taken (loop back) | Iter 1: Not taken (left over from last exit) | 1 miss |
| Iteration 10 | Not taken (exit) | Taken | 1 miss |
Two misses per loop run: one at the exit, one when the loop starts again.
2-bit Saturating Counter
Use two bits, so one surprise is not enough to change the prediction:
stateDiagram-v2
[*] --> StronglyTaken
StronglyTaken --> WeaklyTaken: not taken
WeaklyTaken --> StronglyTaken: taken
WeaklyTaken --> WeaklyNotTaken: not taken
WeaklyNotTaken --> WeaklyTaken: taken
WeaklyNotTaken --> StronglyNotTaken: not taken
StronglyNotTaken --> WeaklyNotTaken: taken
StronglyTaken --> StronglyTaken: taken
StronglyNotTaken --> StronglyNotTaken: not taken
Predict taken in the two "Taken" states. For the 10-iteration loop, the exit moves the counter from Strongly Taken to Weakly Taken, which still predicts taken, so the next run starts correctly. Only one miss per loop run.
Correlating and History-Based Predictors
Branches often depend on each other or follow patterns:
if (a == 2) a = 0; // branch 1
if (b == 2) b = 0; // branch 2
if (a != b) ... // branch 3 depends on what 1 and 2 did
A global history register records the outcomes of the last few branches (for example 1101). The predictor uses the branch address combined with that history to pick a counter, so the same branch can get different predictions in different situations.
flowchart LR
PC["Branch address"] --> X["Combine<br/>(e.g. XOR)"]
GH["Global history<br/>last N outcomes"] --> X
X --> T["Table of 2-bit counters"]
T --> P["Prediction: taken / not taken"]
| Predictor | Idea |
|---|---|
| Gshare | XOR branch address with global history to index one table |
| Tournament | Two predictors plus a chooser that learns which one is better per branch |
| TAGE | Several tables using different history lengths; the longest one that matches wins |
| Perceptron | A tiny neural-network-like weighted sum of history bits |
Modern high-end cores use TAGE-like or perceptron-like designs and are right well over 90% of the time on typical code. The exact designs are not published in detail.
Sources: Wikipedia: Branch predictor
Knowing Where: The Branch Target Buffer
Predicting "taken" is not enough; fetch also needs the target address, in the same cycle, before the instruction is even decoded.
| Structure | Answers | Used for |
|---|---|---|
| Branch target buffer (BTB) | "Is the instruction at this address a branch, and where did it go last time?" | Direct and indirect branches |
| Return address stack (RAS) | "Where will this RET return to?" | Push on BL (call), pop on RET |
| Indirect predictor | "Where will this jump through a register go?" | Virtual calls, switch jump tables |
flowchart LR
PC["PC"] --> BTB["BTB lookup"]
PC --> DIR["Direction predictor"]
BTB -->|"target"| MUX{"taken?"}
DIR --> MUX
MUX -->|"yes"| T["Next PC = target"]
MUX -->|"no"| N["Next PC = PC + 4"]
When the Guess Is Wrong
Instructions fetched after a prediction are speculative: they may run, but their results are not made permanent until the branch is confirmed.
sequenceDiagram
participant F as Fetch
participant B as Branch unit
participant P as Pipeline
F->>P: fetch predicted path (speculative)
P->>B: branch reaches execute
B-->>B: compare actual vs predicted
alt correct
B->>P: keep results
else mispredicted
B->>P: flush all younger instructions
B->>F: restart at correct address
end
The misprediction penalty is roughly the number of stages between fetch and branch resolution, often 10-20 cycles on a big core.
Worked example: 20% of instructions are branches, 5% of those are mispredicted, penalty 15 cycles, base CPI 1.
CPI = 1 + 0.20 × 0.05 × 15 = 1 + 0.15 = 1.15
With 10% misprediction instead the CPI is 1.30, so predictor accuracy matters a lot.
Sources: Wikipedia: Speculative execution
Remedy 4: Remove the Branch
If a branch is hard to predict (random data), the compiler can replace it with a conditional select, which has no control hazard at all. On Arm this is CSEL:
// illustrative: y = (x == 0) ? 1 : 2;
MOV X2, #1
MOV X3, #2
CMP X0, #0
CSEL X1, X2, X3, EQ // X1 = (flags say equal) ? X2 : X3
Both values are computed and one is picked. This is a win for unpredictable branches with cheap bodies, and a loss when the branch is predictable and one side is expensive. In compilers this is the select instruction, see LLVM IR: Compare and Select.
Key Points
- Branch outcomes are known late in the pipeline; stalling on every branch is too slow.
- Dynamic predictors (2-bit counters, history-based tables) guess right most of the time; BTB and return stack supply the target.
- A misprediction flushes all younger instructions; cost ≈ pipeline depth. Unpredictable branches can be replaced with conditional selects.
Instruction-Level Parallelism
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Instruction-level parallelism
- Wikipedia: Superscalar processor
- Wikipedia: Out-of-order execution
- Wikipedia: Register renaming
- Wikipedia: Tomasulo's algorithm
- Wikipedia: Speculative execution
- Book: Hennessy and Patterson, Computer Architecture: A Quantitative Approach, chapter 3
Instruction-level parallelism (ILP) means running several instructions from the same program at the same time. A pipeline overlaps instructions in different stages; ILP goes further, starting two, four or eight instructions in the same cycle and running them in whatever order their inputs become ready, while still making the program behave as if it ran one instruction at a time.
Purpose and Scope
This page covers dependences, superscalar issue, out-of-order execution, register renaming, the reorder buffer, speculation, and the limits of ILP, plus VLIW as the compiler-driven alternative. Running several threads at once is on Multithreading.
The Restaurant Kitchen Analogy
A recipe says: 1. boil water (10 min), 2. chop onions (3 min), 3. cook pasta in the water (8 min), 4. fry the onions (5 min).
| One cook, strict order | Several cooks, out of order |
|---|---|
| 10 + 3 + 8 + 5 = 26 min | Cook A boils water then cooks pasta (18 min). Cook B chops then fries onions (8 min) at the same time. Done in 18 min |
Steps 3 depends on step 1 and step 4 depends on step 2, but the two chains are independent. Finding and using such independent chains is exactly what ILP hardware does. The finished dish is the same, as long as nobody serves it before every step is done.
Dependences Decide What Can Overlap
// illustrative
I1: LDR X1, [X0] // load a
I2: ADD X2, X1, #1 // needs X1 from I1
I3: LDR X3, [X0, #8] // independent of I1, I2
I4: MUL X4, X3, X3 // needs X3 from I3
I5: ADD X5, X2, X4 // needs X2 and X4
flowchart TD
I1["I1: LDR X1"] --> I2["I2: ADD X2 = X1+1"]
I3["I3: LDR X3"] --> I4["I4: MUL X4 = X3*X3"]
I2 --> I5["I5: ADD X5 = X2+X4"]
I4 --> I5
The graph has two independent chains. A machine that can start two instructions per cycle can run I1 and I3 together, then I2 and I4, then I5: three steps instead of five. The longest chain (the critical path) sets the minimum time, no matter how wide the machine.
Sources: Wikipedia: Instruction-level parallelism
Superscalar: More Than One per Cycle
A superscalar core fetches, decodes and issues several instructions per cycle and has several execution units.
flowchart LR
F["Fetch<br/>4 instr/cycle"] --> D["Decode<br/>4 instr/cycle"]
D --> ALU1["ALU 1"]
D --> ALU2["ALU 2"]
D --> MUL["Multiplier"]
D --> LS["Load/store unit"]
D --> BR["Branch unit"]
| Width | Ideal IPC | Ideal CPI |
|---|---|---|
| Scalar (1-wide) | 1 | 1 |
| 2-wide | 2 | 0.5 |
| 4-wide | 4 | 0.25 |
In practice dependences, cache misses and branch mispredictions keep real IPC well below the width.
Sources: Wikipedia: Superscalar processor
In-Order versus Out-of-Order
An in-order core issues instructions strictly in program order. If I2 waits for a slow load, everything behind it waits too, even independent work.
An out-of-order (OoO) core lets instructions run as soon as their inputs are ready, then puts results back in program order at the end.
| Cycle | In-order (2-wide) | Out-of-order (2-wide) |
|---|---|---|
| 1 | I1 (load starts) | I1, I3 (both loads start) |
| 2 | I2 waits for X1... | waiting for loads |
| 3 | ...still waiting | I2, I4 |
| 4 | I2, I3 | I5 |
| 5 | I4 | |
| 6 | I5 |
(Illustrative timing, with a load taking 2 cycles.) The out-of-order core hides the load delay by doing other work meanwhile.
The Out-of-Order Engine
flowchart LR
F["Fetch + branch prediction"] --> D["Decode"]
D --> R["Rename<br/>architectural to physical registers"]
R --> ROB["Reorder buffer (ROB)<br/>remembers program order"]
R --> IQ["Issue queue<br/>wait for operands"]
IQ -->|"ready"| EX["Execution units<br/>ALUs, multiplier, load/store"]
EX -->|"result"| IQ
EX --> ROB
ROB --> C["Commit / retire<br/>in program order"]
| Stage | Job |
|---|---|
| Fetch / decode | Bring in instructions along the predicted path (Branches) |
| Rename | Give each result a fresh physical register, removing false dependences |
| Issue queue (reservation stations) | Hold instructions until their inputs are ready, then send them to a free unit |
| Execute | Do the work, possibly out of order |
| Reorder buffer (ROB) | Keep instructions in program order; mark each done when it finishes |
| Commit (retire) | Make results permanent strictly in program order, oldest first |
The idea of waiting in reservation stations and broadcasting results comes from Tomasulo's algorithm (IBM, 1967).
Sources: Wikipedia: Out-of-order execution, Wikipedia: Tomasulo's algorithm
Register Renaming
The program has only 31 general registers, so it reuses names a lot. That creates false dependences (Pipelining called them WAR and WAW):
// illustrative
I1: LDR X1, [X0] // X1 = a
I2: ADD X2, X1, #1 // uses a
I3: LDR X1, [X0, #8] // X1 = b (reuses the name X1!)
I4: ADD X3, X1, #2 // uses b
I3 cannot write X1 before I2 has read it (WAR), even though a and b are unrelated. The hardware has many more physical registers (often a couple of hundred) than architectural ones and gives every new result its own:
| Instruction | Written as | After renaming |
|---|---|---|
| I1 | X1 = load | P10 = load |
| I2 | X2 = X1 + 1 | P11 = P10 + 1 |
| I3 | X1 = load | P12 = load |
| I4 | X3 = X1 + 2 | P13 = P12 + 2 |
Now I1→I2 and I3→I4 are two independent chains. A rename table maps each architectural register to its current physical register. (This is the hardware version of the SSA form used in compilers, see LLVM IR: SSA and Phi.)
Sources: Wikipedia: Register renaming
Speculation and the Reorder Buffer
The core fetches past predicted branches and runs those instructions before it knows the prediction was right. The ROB makes this safe:
flowchart TD
A["Instruction finishes executing"] --> B["Marked done in ROB<br/>(result not yet permanent)"]
B --> C{"Is it the oldest<br/>instruction in the ROB?"}
C -->|"No"| W["Wait"]
W --> C
C -->|"Yes"| D{"Exception or<br/>mispredicted branch?"}
D -->|"No"| E["Commit: update architectural state"]
D -->|"Yes"| F["Flush it and everything younger<br/>restore rename table, refetch"]
Because commit is in order, an exception or misprediction can be handled as if the program ran one instruction at a time: this is called precise exceptions. Stores are held in a store buffer and only written to the cache at commit, so wrong-path stores never become visible.
Speculation can still leave traces in the caches, which is the root of the Spectre family of security attacks.
Sources: Wikipedia: Speculative execution
VLIW: Letting the Compiler Do It
Instead of complex hardware finding parallel instructions at run time, a VLIW (very long instruction word) machine has the compiler pack independent operations into one wide instruction.
| Out-of-order superscalar | VLIW | |
|---|---|---|
| Who finds parallelism | Hardware, at run time | Compiler, ahead of time |
| Hardware complexity | High | Low |
| Handles unpredictable delays (cache misses) | Well | Poorly: the whole bundle stalls |
| Typical use | General-purpose CPUs (Arm Cortex-A/X, x86) | DSPs (for example Qualcomm Hexagon), some accelerators |
Limits of ILP
Even with perfect hardware, ILP is limited by:
| Limit | Why |
|---|---|
| True dependences | A chain of dependent instructions can't be shortened |
| Branch mispredictions | Each one throws away the speculative work |
| Cache misses | A load to main memory takes hundreds of cycles; the ROB fills up waiting |
| Window size | The core can only look ahead as far as its ROB and queues hold (a few hundred instructions) |
| Power and area | Width and window size grow cost faster than performance |
This "ILP wall" is why designers turned to many threads and many data items: Multicore, Multithreading and SIMD and GPUs.
Key Points
- ILP runs independent instructions from one program at the same time; dependences limit it.
- Out-of-order cores rename registers, wait in issue queues, execute when ready, and commit in order via the ROB.
- Speculation runs past predicted branches; in-order commit keeps the result correct and exceptions precise.
Memory and Ordering
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Memory ordering
- Wikipedia: Memory barrier
- Arm: Arm Architecture Reference Manual for A-profile architecture (DDI 0487), section on the memory model
- Arm: Learn the architecture: Memory Systems, Ordering, and Barriers (document 102336)
With one core, memory behaves the way you expect: a load always sees the most recent store to the same address. With several cores, a surprising thing happens: one core can see another core's stores in a different order from the order they were written. This page explains why, what the rules are on Arm and x86, and how barriers and acquire/release instructions restore the order you need.
> All code on this page is illustrative pseudo-assembly or C. It shows behaviour the architecture allows; whether a given chip shows it on a given run is a matter of timing.
Purpose and Scope
This page covers why hardware reorders memory operations (store buffers, out-of-order loads, caches), sequential consistency, the x86 (TSO) and Arm (weakly ordered) models, the message-passing example, barriers (DMB, DSB, ISB) and load-acquire / store-release. How caches keep each single address consistent is on Caches and Coherence.
The Post Office Analogy
You post two letters to a friend: first "I've put the key under the mat", then "The key is ready". The post office does not promise to deliver letters in the order you posted them. Your friend might read "The key is ready", look under the mat, and find nothing yet.
| Post office | Processor |
|---|---|
| Letters | Stores to memory |
| Post office may reorder delivery | Hardware may make stores visible to other cores out of order |
| "Deliver these in order" stamp | A barrier or release store |
| Friend reads letters | Another core's loads |
Why Hardware Reorders
Reordering is a side effect of the speed tricks from earlier pages:
flowchart LR
subgraph Core0["Core 0"]
P0["Pipeline"] --> SB0["Store buffer<br/>stores wait here"]
end
subgraph Core1["Core 1"]
P1["Pipeline"] --> SB1["Store buffer"]
end
SB0 --> C["Caches / memory<br/>(coherent)"]
SB1 --> C
C --> P0
C --> P1
| Cause | Effect |
|---|---|
| Store buffer | A core keeps running after a store; the store reaches the cache later. Its own later loads can complete first (store→load reordering) |
| Out-of-order execution (ILP) | Independent loads may run in any order |
| Store buffer draining in any order (weak models) | Two stores to different addresses may become visible in either order |
| Caches and interconnect | A store may reach some cores sooner than others |
Within one core, the hardware always hides this: the core checks its own store buffer, so a single thread never notices. The surprises only appear between cores.
Sources: Wikipedia: Memory ordering
Sequential Consistency: The Intuitive Model
Sequential consistency (SC) means the result is as if all cores' operations were interleaved into one sequence, with each core's operations kept in program order. It is easy to reason about but costly to implement, so no mainstream CPU guarantees it by default.
The Classic Example: Message Passing
// illustrative. Initially data = 0, flag = 0.
Core 0 (producer) Core 1 (consumer)
STR #42 -> [data] loop: LDR X1 <- [flag]
STR #1 -> [flag] CBZ X1, loop
LDR X2 <- [data]
Can Core 1 read flag = 1 but data = 0?
sequenceDiagram
participant C0 as Core 0
participant M as Memory system
participant C1 as Core 1
C0->>M: store data = 42 (still in store buffer)
C0->>M: store flag = 1 (becomes visible first)
C1->>M: load flag
M-->>C1: 1
C1->>M: load data
M-->>C1: 0 (old value!)
Note over C0,M: data = 42 becomes visible later
| Memory model | Can Core 1 see flag=1, data=0? |
|---|---|
| Sequential consistency | No |
| x86 (TSO) | No: stores become visible in order, and loads are not reordered with other loads |
| Arm (weakly ordered) | Yes, unless the program adds ordering |
The Two Models You Will Meet
| Reordering allowed? | SC | x86-64 (TSO) | Arm A64 |
|---|---|---|---|
| Store then load (different address) | No | Yes (store buffer) | Yes |
| Store then store | No | No | Yes |
| Load then load | No | No | Yes |
| Load then store | No | No | Yes |
| Dependent operations (address depends on loaded value) | No | No | No |
TSO (total store order) on x86 only allows the store buffer effect. Arm is weakly ordered: the hardware may reorder independent accesses in many ways, which lets it be simpler and use less power, but the programmer (or compiler, or language runtime) must say where order matters. Arm does keep order when there is a dependency: if the address of a load comes from an earlier load's value, the two stay in order.
Sources: Wikipedia: Memory ordering
Tools for Restoring Order on Arm
Barriers
| Instruction | Name | What it guarantees |
|---|---|---|
DMB | Data memory barrier | Memory accesses before it are observed before memory accesses after it. Options such as DMB ISH (inner shareable, i.e. other cores), DMB ISHST (stores only), DMB ISHLD (loads before) |
DSB | Data synchronization barrier | Stronger: waits until earlier accesses have completed; used with cache and TLB maintenance |
ISB | Instruction synchronization barrier | Flushes the pipeline so later instructions are fetched again; used after changing system registers or code |
Fixing message passing with barriers:
// illustrative
Core 0 Core 1
STR #42 -> [data] loop: LDR X1 <- [flag]
DMB ISHST // stores in order CBZ X1, loop
STR #1 -> [flag] DMB ISHLD // loads in order
LDR X2 <- [data] // now always 42
Acquire and Release
Barriers order everything, which is more than needed. Arm A64 has one-way ordering built into loads and stores:
| Instruction | Name | Rule |
|---|---|---|
STLR | Store-release | All earlier memory accesses are visible before this store |
LDAR | Load-acquire | All later memory accesses happen after this load |
LDAPR | Load-acquire (RCpc) | A slightly weaker acquire, matching C++ memory_order_acquire (Armv8.3) |
flowchart TD
subgraph P["Core 0"]
A1["STR data = 42"] --> A2["STLR flag = 1<br/>(release: data goes first)"]
end
subgraph Q["Core 1"]
B1["LDAR flag<br/>(acquire: data read after)"] --> B2["LDR data"]
end
A2 -.->|"synchronizes with"| B1
// illustrative
Core 0 Core 1
STR #42 -> [data] loop: LDAR X1 <- [flag]
STLR #1 -> [flag] CBZ X1, loop
LDR X2 <- [data] // always 42
What This Means in C and C++
Programmers normally don't write barriers. They use atomics, and the compiler picks instructions for the target:
// illustrative C11
atomic_int flag; int data;
// producer
data = 42;
atomic_store_explicit(&flag, 1, memory_order_release); // Arm: STLR
// consumer
while (atomic_load_explicit(&flag, memory_order_acquire) == 0) {} // Arm: LDAR or LDAPR
int v = data; // guaranteed 42
| C/C++ order | Typical Arm A64 code | Typical x86-64 code |
|---|---|---|
relaxed load / store | LDR / STR | MOV / MOV |
acquire load | LDAR or LDAPR | MOV |
release store | STLR | MOV |
seq_cst store | STLR | XCHG or MOV + MFENCE |
Note how x86 needs nothing extra for acquire and release: TSO already gives them. That is why code with a missing barrier may work on x86 and fail on Arm. In LLVM IR these orders appear on atomic loads and stores, see LLVM IR: Memory.
Sources: Wikipedia: Memory barrier
Atomic Read-Modify-Write
Incrementing a shared counter needs the read and the write to happen as one indivisible step. Arm provides two styles:
| Style | Instructions | How it works |
|---|---|---|
| Exclusive pair (Armv8.0) | LDXR / STXR | Load and mark the address; the store only succeeds if nobody wrote it meanwhile; loop until success |
| Large System Extensions (Armv8.1) | LDADD, SWP, CAS | One instruction does the whole operation, which scales better with many cores |
flowchart TD
A["LDXR: load counter, mark exclusive"] --> B["ADD 1"]
B --> C["STXR: try to store"]
C --> D{"Succeeded?"}
D -->|"No, another core wrote it"| A
D -->|"Yes"| E["Done"]
Key Points
- Store buffers and out-of-order execution let other cores see memory operations in a different order.
- x86 (TSO) only reorders a store with a later load; Arm may reorder most independent accesses.
- Use acquire/release (
LDAR,STLR), barriers (DMB) or language atomics wherever cross-core order matters.
Caches and Coherence
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: CPU cache
- Wikipedia: Memory hierarchy
- Wikipedia: Cache coherence
- Wikipedia: MESI protocol
- Wikipedia: False sharing
- Arm: Learn the architecture: Memory Systems, Ordering, and Barriers (document 102336)
- Book: Patterson and Hennessy, Computer Organization and Design (Arm edition), chapter 5
Main memory is about a hundred times slower than the processor. A cache is a small, fast memory next to the core that keeps copies of recently used data, so most loads never have to go all the way to main memory. With several cores, each with its own cache, a second problem appears: several copies of the same data must stay in agreement. That is cache coherence.
> Sizes, latencies and examples on this page are typical, illustrative values, not the figures of a particular chip.
Purpose and Scope
This page covers locality, cache lines, hits and misses, how an address finds its place in a cache (direct-mapped, set-associative), replacement, write policies, the three kinds of miss, average access time, coherence with the MESI protocol, snooping versus directories, and false sharing. The ordering of accesses to different addresses is on Memory and Ordering.
The Desk and Library Analogy
| Library | Computer |
|---|---|
| Your desk (holds a few books) | L1 cache |
| The shelf behind you | L2 cache |
| The library down the hall | Main memory |
| You fetch a whole book, not one page | The cache fetches a whole line (typically 64 bytes), not one byte |
| You keep the books you are using on the desk | Temporal locality: recently used data is likely to be used again |
| The page you want next is in the same book | Spatial locality: nearby data is likely to be used soon |
Hits, Misses and Lines
flowchart TD
L["Core issues a load"] --> C{"Is the line in L1?"}
C -->|"Hit (most of the time)"| H["Return data in a few cycles"]
C -->|"Miss"| L2{"In L2?"}
L2 -->|"Hit"| H2["Copy line into L1, return data<br/>(~10-15 cycles)"]
L2 -->|"Miss"| MEM["Fetch line from main memory<br/>(hundreds of cycles)"]
MEM --> FILL["Fill L2 and L1, return data"]
Memory moves between levels in fixed-size blocks called cache lines. A load of one 4-byte integer brings in the whole 64-byte line around it, which is why walking an array in order is fast: the next 15 integers are already there.
| Access pattern | Locality | Cache behaviour |
|---|---|---|
for (i...) sum += a[i]; | Spatial and temporal | Excellent: 1 miss per 16 ints |
| Walking a linked list scattered in memory | Poor spatial | Often a miss per node |
a[i][j] with j in the outer loop (column order in C) | Poor spatial | A miss on almost every access |
Sources: Wikipedia: CPU cache
Where Does a Line Go?
The cache splits each address into three fields:
flowchart LR
A["Address"] --> T["Tag<br/>which line is it?"]
A --> I["Index<br/>which set to look in"]
A --> O["Offset<br/>which byte in the line"]
| Organisation | A line can go in | Pros / cons |
|---|---|---|
| Direct-mapped | Exactly one place | Simple and fast; two hot addresses that map to the same place keep evicting each other |
| N-way set-associative | Any of N places in one set | The common choice (L1 is often 4- to 8-way) |
| Fully associative | Anywhere | No conflicts, but checking every tag is expensive; used for small structures such as TLBs |
Worked Example
A 32 KB, 4-way set-associative cache with 64-byte lines:
Lines = 32 KB / 64 B = 512 lines
Sets = 512 lines / 4 ways = 128 sets
Offset bits = log2(64) = 6 (bits 0-5)
Index bits = log2(128) = 7 (bits 6-12)
Tag bits = the rest (bits 13 and up)
Address 0x0001_2345: offset = 0x05, index = (0x12345 >> 6) & 0x7F = 0x0D (set 13), tag = 0x12345 >> 13 = 0x9. The cache looks in set 13, compares tag 0x9 with the tags of its 4 ways, and reports a hit if one matches and is valid.
flowchart TD
S["Set 13"] --> W0["Way 0: tag 0x4, valid"]
S --> W1["Way 1: tag 0x9, valid ✔ hit"]
S --> W2["Way 2: tag 0x1F, valid"]
S --> W3["Way 3: empty"]
Replacement
On a miss in a full set, one line must be evicted. LRU (least recently used) evicts the line untouched for longest; real caches use cheaper approximations such as pseudo-LRU or random.
Writes
| Policy | On a store | Trade-off |
|---|---|---|
| Write-through | Update the cache and the next level immediately | Simple; uses a lot of bandwidth |
| Write-back | Update the cache only; mark the line dirty; write it out when evicted | Less traffic; the usual choice for L1/L2 |
| Write-allocate | On a store miss, bring the line in first | Pairs with write-back |
| No-write-allocate | On a store miss, write straight to the next level | Pairs with write-through |
Why Misses Happen: The Three Cs
| Kind | Cause | Remedy |
|---|---|---|
| Compulsory (cold) | First ever access to a line | Bigger lines, prefetching (the hardware guesses the next lines and fetches them early) |
| Capacity | The working set is bigger than the cache | Bigger cache, or restructure the loop (blocking/tiling) |
| Conflict | Too many hot lines map to the same set | More associativity |
With several cores there is a fourth kind, coherence misses, explained below.
Average Memory Access Time
AMAT = Hit time + Miss rate × Miss penalty
Worked example: L1 hit 4 cycles, L1 miss rate 5%, L2 hit 12 cycles, L2 miss rate (of L1 misses) 20%, memory 200 cycles.
L2 miss penalty seen by L1 = 12 + 0.20 × 200 = 52 cycles
AMAT = 4 + 0.05 × 52 = 6.6 cycles
Halving the L1 miss rate to 2.5% gives 4 + 0.025 × 52 = 5.3 cycles. Small changes in miss rate matter a lot.
Coherence: Many Copies of One Line
Each core has a private L1 (and often L2). If two cores read the same address, both caches hold a copy. If one core then writes, the other copy is stale.
sequenceDiagram
participant C0 as Core 0 cache
participant C1 as Core 1 cache
participant M as Memory
C0->>M: read X
M-->>C0: X = 0
C1->>M: read X
M-->>C1: X = 0
C0->>C0: write X = 5 (in its cache only)
C1->>C1: read X -> 0 ?? stale!
A coherence protocol guarantees two things for every single address:
- Write propagation: a write eventually becomes visible to all cores.
- Write serialization: all cores see writes to the same address in the same order.
The usual rule that delivers this is single writer, multiple readers: at any moment a line is either writable by one cache, or readable by many, never both.
Sources: Wikipedia: Cache coherence
The MESI Protocol
Each line in each cache is in one of four states:
| State | Meaning | Can read? | Can write without asking? | Same as memory? |
|---|---|---|---|---|
| M Modified | Only copy, has been written | Yes | Yes | No (dirty) |
| E Exclusive | Only copy, not written | Yes | Yes (moves to M silently) | Yes |
| S Shared | Other caches may also have it | Yes | No: must invalidate others first | Yes |
| I Invalid | Not present / stale | No | No | n/a |
stateDiagram-v2
[*] --> I
I --> E: local read, no other copy
I --> S: local read, others have it
I --> M: local write (invalidate others)
E --> M: local write (silent)
E --> S: another core reads
S --> M: local write (invalidate others)
M --> S: another core reads (write back data)
M --> I: another core writes
S --> I: another core writes
E --> I: another core writes
Replaying the stale-read example with MESI:
| Step | Core 0 line | Core 1 line | Message |
|---|---|---|---|
| Core 0 reads X | E | I | read from memory |
| Core 1 reads X | S | S | Core 0 sees the read and downgrades |
| Core 0 writes X = 5 | M | I | invalidate sent; Core 1 drops its copy |
| Core 1 reads X | S | S | Core 0 supplies 5 (and writes back) |
Core 1 now reads 5. Its second read was a coherence miss. Real systems add states (MOESI adds Owned, so a dirty line can be shared without writing memory first; Arm's AMBA CHI interconnect uses a MOESI-style set of states).
Sources: Wikipedia: MESI protocol
Snooping versus Directories
| Snooping | Directory | |
|---|---|---|
| How caches find out | Every request is broadcast; every cache "snoops" | A directory records which caches hold each line; messages go only to them |
| Scales to | A handful of cores | Many cores |
| Used in | Small clusters | Large server chips, many-core systems |
flowchart LR
subgraph Snoop["Snooping"]
A0["Core 0"] --- BUS["Shared bus / broadcast"]
A1["Core 1"] --- BUS
A2["Core 2"] --- BUS
end
subgraph Dir["Directory"]
D["Directory<br/>line X: cores 1, 3"]
B0["Core 0"] -->|"write X?"| D
D -->|"invalidate"| B1["Core 1"]
D -->|"invalidate"| B3["Core 3"]
end
False Sharing
Coherence works on whole lines, not variables. Two cores updating different variables that happen to sit in the same 64-byte line keep stealing the line from each other:
// illustrative
struct { long count0; long count1; } c; // both in one cache line
// thread on core 0: for (...) c.count0++;
// thread on core 1: for (...) c.count1++;
sequenceDiagram
participant C0 as Core 0
participant C1 as Core 1
C0->>C0: write count0 (line in M)
C1->>C0: want line to write count1
C0-->>C1: line moves, Core 0 invalidated
C0->>C1: want line back to write count0
C1-->>C0: line moves again...
The program is correct but can run many times slower. The fix is to put each hot variable on its own line, for example with alignas(64) padding.
Sources: Wikipedia: False sharing
Key Points
- Caches exploit locality and move data in 64-byte lines; an address splits into tag, index and offset.
- AMAT = hit time + miss rate × miss penalty; compulsory, capacity and conflict misses have different remedies.
- Coherence (e.g. MESI) keeps one writer or many readers per line; false sharing is coherence traffic between unrelated variables in one line.
Multicore
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Multi-core processor
- Wikipedia: Amdahl's law
- Wikipedia: Non-uniform memory access
- Wikipedia: Flynn's taxonomy
- Book: Hennessy and Patterson, Computer Architecture: A Quantitative Approach, chapter 5
A multicore processor puts several complete cores on one chip. Each core runs its own stream of instructions, so a program that splits its work into threads can finish sooner. Multicore became the main way to get more performance once clock speeds stopped rising (Overview). This page explains how the cores are connected, how much speedup to expect, and what slows multicore programs down.
> Numbers and chip layouts on this page are illustrative.
Purpose and Scope
This page covers why chips went multicore, Flynn's classification, shared-memory organisation (private and shared caches, interconnect), heterogeneous big.LITTLE designs, Amdahl's and Gustafson's laws, NUMA, and the costs of synchronisation. Keeping the cores' caches consistent is on Caches and Coherence; the order in which they see each other's writes is on Memory and Ordering.
The Office Analogy
| Office | Multicore chip |
|---|---|
| One worker, one desk | One core with its L1 cache |
| Hiring more workers | Adding cores |
| A shared filing cabinet | Shared L3 cache and main memory |
| Workers must agree who edits which file | Coherence and locks |
| A task only one person can do (signing the final report) | The serial part of a program |
| More workers than the hallway can handle | Memory bandwidth limits |
Ten workers can finish a big pile of independent forms ten times faster. They can't make one person's signature faster, and they slow down if they all queue at the same cabinet.
Why Multicore?
flowchart TD
A["Need more performance"] --> B{"Raise clock?"}
B -->|"Power grows steeply with frequency and voltage"| X["Too hot"]
A --> C{"Wider single core?"}
C -->|"ILP wall: little extra gain"| Y["Diminishing returns"]
A --> D["Put 2, 4, 8... cores on the chip<br/>each at a sensible clock"]
D --> E["More total throughput<br/>if software uses threads"]
Two cores at moderate frequency usually give more total work per watt than one core pushed to a very high frequency, but only if the software runs in parallel.
Flynn's Taxonomy
Flynn's 1966 classification counts instruction streams and data streams:
| Single data | Multiple data | |
|---|---|---|
| Single instruction | SISD: a classic single core | SIMD: vector units, GPUs (SIMD and GPUs) |
| Multiple instruction | MISD: rare | MIMD: multicore, clusters (this page) |
Sources: Wikipedia: Flynn's taxonomy
Organisation of a Multicore Chip
flowchart TB
subgraph Chip["Multicore chip (illustrative)"]
direction TB
subgraph C0["Core 0"]
P0["Pipeline"] --- L10["L1 I + L1 D"]
L10 --- L20["Private L2"]
end
subgraph C1["Core 1"]
P1["Pipeline"] --- L11["L1 I + L1 D"]
L11 --- L21["Private L2"]
end
subgraph C2["Core 2"]
P2["Pipeline"] --- L12["L1 I + L1 D"]
L12 --- L22["Private L2"]
end
L20 --- IC["Interconnect<br/>(coherent: ring, mesh or crossbar)"]
L21 --- IC
L22 --- IC
IC --- L3["Shared L3 / system level cache"]
end
L3 --- MC["Memory controller"] --- DRAM["DRAM"]
| Part | Shared or private | Role |
|---|---|---|
| Pipeline, registers | Private | Runs one thread (or more, see Multithreading) |
| L1, often L2 | Private | Fast, close data |
| L3 / system level cache | Shared | Catches data used by several cores; reduces DRAM traffic |
| Interconnect | Shared | Carries requests and coherence messages between caches |
| Memory controller, DRAM | Shared | Total bandwidth is split among all cores |
All cores see one shared address space: this is shared-memory multiprocessing (SMP). Threads communicate simply by reading and writing memory, and the hardware keeps caches coherent.
Sources: Wikipedia: Multi-core processor
Heterogeneous Cores: big.LITTLE
Phones and laptops often mix core types on one chip. Arm calls this big.LITTLE, and later DynamIQ, which allows mixed core types in one cluster.
| Core type | Design | Used for |
|---|---|---|
| Big (performance) | Wide, out-of-order, large caches, high clock | Bursts: launching an app, a game frame |
| Little (efficiency) | Narrow, often in-order, small | Background work, email sync, music |
flowchart LR
T["Thread becomes runnable"] --> S{"Scheduler: how demanding?"}
S -->|"Light / background"| L["Little core<br/>low power"]
S -->|"Heavy / interactive"| B["Big core<br/>high performance"]
L -->|"load grows"| B
B -->|"load drops"| L
All cores implement the same architecture, so the operating system can move a thread between them at any time.
How Much Faster? Amdahl's Law
If a fraction p of a program can run in parallel on N cores and the rest (1 − p) is serial:
Speedup(N) = 1 / ((1 − p) + p / N)
| Parallel fraction p | 2 cores | 4 cores | 8 cores | 64 cores | Limit (∞ cores) |
|---|---|---|---|---|---|
| 50% | 1.33 | 1.60 | 1.78 | 1.97 | 2 |
| 90% | 1.82 | 3.08 | 4.71 | 8.77 | 10 |
| 95% | 1.90 | 3.48 | 5.93 | 15.4 | 20 |
| 99% | 1.98 | 3.88 | 7.48 | 39.3 | 100 |
The serial part sets a hard ceiling: with 10% serial work, no number of cores can give more than 10×.
flowchart LR
subgraph One["1 core: 100 units"]
S1["serial 10"] --> P1["parallel 90"]
end
subgraph Four["4 cores: 32.5 units (3.08x)"]
S2["serial 10"] --> P2["parallel 90 / 4 = 22.5"]
end
Gustafson's law gives the more hopeful view: with more cores people usually solve bigger problems, and the parallel part grows while the serial part stays the same, so scaled speedup ≈ (1 − p) + p × N.
Sources: Wikipedia: Amdahl's law
What Slows Multicore Programs Down
| Cost | Cause | See |
|---|---|---|
| Serial sections | Code only one thread can run | Amdahl's law above |
| Locks and contention | Threads waiting for each other | Below |
| Coherence traffic | Shared data bouncing between caches; false sharing | Caches and Coherence |
| Memory bandwidth | All cores share the memory controllers | |
| Load imbalance | One thread gets more work and the others wait for it | |
| Barriers and atomics | Ordering instructions stall the pipeline | Memory and Ordering |
Locks
A lock (mutex) lets only one thread at a time into a critical section. It is built on atomic read-modify-write instructions such as Arm CAS or LDXR/STXR.
sequenceDiagram
participant T0 as Thread 0
participant L as Lock
participant T1 as Thread 1
T0->>L: acquire (atomic CAS 0 -> 1)
L-->>T0: success
T1->>L: acquire
L-->>T1: busy, wait / spin
T0->>T0: critical section
T0->>L: release (store-release 0)
T1->>L: acquire again
L-->>T1: success
A heavily used lock turns parallel code back into serial code, which shows up as a lower effective p in Amdahl's law.
NUMA: When Memory Is Not Equally Far
Large servers have several chips (sockets), each with its own memory. A core reaches its own socket's memory faster than another socket's.
flowchart LR
subgraph S0["Socket 0"]
CA["Cores 0-31"] --- MA["Local memory A"]
end
subgraph S1["Socket 1"]
CB["Cores 32-63"] --- MB["Local memory B"]
end
CA <-->|"slower remote access"| MB
CB <-->|"slower remote access"| MA
This is non-uniform memory access (NUMA). Operating systems try to place a thread's memory on the same socket as the thread ("first touch" allocation).
Sources: Wikipedia: Non-uniform memory access
Key Points
- Multicore puts several full cores on a chip with private L1/L2, a shared L3 and a coherent interconnect.
- Amdahl's law: the serial fraction limits speedup, however many cores you add.
- Locks, coherence traffic, shared bandwidth and NUMA distance are the main costs; big.LITTLE trades performance for efficiency per thread.
Multithreading in Hardware
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Multithreading (computer architecture)
- Wikipedia: Simultaneous multithreading
- Book: Hennessy and Patterson, Computer Architecture: A Quantitative Approach, chapter 3
A single thread often leaves a core idle: it waits for a cache miss, recovers from a mispredicted branch, or simply has no independent instruction ready. Hardware multithreading lets one core hold the state of several threads at once and switch to another thread whenever the current one stalls, so the expensive execution units stay busy. To the operating system each hardware thread looks like a separate CPU.
> Timelines on this page are illustrative.
Purpose and Scope
This page covers what a hardware thread is, the difference between software and hardware threads, three styles of multithreading (coarse-grained, fine-grained, simultaneous), what is shared and duplicated, the benefits and costs, and how GPUs take the same idea much further. Multiple separate cores are on Multicore.
The Chef with Several Dishes Analogy
A chef is cooking one dish and puts it in the oven for 20 minutes. Rather than stand and wait, the chef starts chopping for a second dish, and comes back to the first when the timer rings.
| Kitchen | Core |
|---|---|
| The chef | The execution units of one core |
| Each dish with its own recipe and progress | A hardware thread: its own registers and PC |
| Waiting for the oven | Waiting for a cache miss |
| Switching to another dish | Switching to another thread |
| One stove shared by all dishes | Caches and execution units shared by all threads |
The chef doesn't get faster at any single dish, but finishes more dishes per hour.
Software Threads and Hardware Threads
| Software thread | Hardware thread | |
|---|---|---|
| Created by | The program (pthread_create, std::thread) | Built into the core |
| Switched by | The operating system, thousands of cycles | The hardware, 0 to a few cycles |
| How many | As many as you like | Fixed: often 1, 2 or 4 per CPU core; many dozens per GPU core |
The operating system schedules software threads onto hardware threads. A 4-core chip with 2 hardware threads per core shows 8 "logical CPUs".
flowchart TD
subgraph SW["Software threads (many)"]
T1["T1"]
T2["T2"]
T3["T3"]
T4["T4"]
T5["T5"]
end
OS["Operating system scheduler"]
T1 --> OS
T2 --> OS
T3 --> OS
T4 --> OS
T5 --> OS
subgraph Core0["Core 0"]
H0["HW thread 0"]
H1["HW thread 1"]
end
subgraph Core1["Core 1"]
H2["HW thread 0"]
H3["HW thread 1"]
end
OS --> H0
OS --> H1
OS --> H2
OS --> H3
What Is Duplicated and What Is Shared
| Duplicated per hardware thread | Shared between threads on a core |
|---|---|
| Program counter | Execution units (ALUs, load/store, FP/SIMD) |
| Architectural registers (or their rename table) | Caches (L1, L2) and TLBs |
| Some status / system registers | Branch predictor tables |
| Issue queues, reorder buffer, physical registers (split or shared) |
Duplicating a register file and a PC is cheap compared with a whole core, so a second hardware thread costs only a small amount of chip area.
Three Styles
Each diagram row is one cycle; each box is an issue slot of a 4-wide core. A, B, C, D are four threads.
flowchart LR
subgraph ST["Single thread"]
direction TB
s1["A A . ."]
s2[". . . . (cache miss)"]
s3[". . . . (cache miss)"]
s4["A . . ."]
end
subgraph CG["Coarse-grained"]
direction TB
c1["A A . ."]
c2["B B B . (switched on miss)"]
c3["B B . ."]
c4["B . . ."]
end
subgraph FG["Fine-grained"]
direction TB
f1["A A . ."]
f2["B B B ."]
f3["C . . ."]
f4["D D . ."]
end
subgraph SMT["Simultaneous (SMT)"]
direction TB
m1["A A B C"]
m2["B B B D"]
m3["C D D A"]
m4["A B C D"]
end
| Style | When it switches | Fills | Example uses |
|---|---|---|---|
| Coarse-grained (switch on event) | Only on a long stall such as a cache miss | Long stalls (vertical waste) | Some older and embedded designs |
| Fine-grained (interleaved) | Every cycle, round-robin between ready threads | Short and long stalls | Barrel processors, some DSPs, GPU warp schedulers |
| Simultaneous multithreading (SMT) | No switching: instructions from several threads issue in the same cycle | Stalls and unused slots within a cycle (horizontal waste) | Intel Hyper-Threading, AMD Zen, some Arm Neoverse and Cortex cores, IBM POWER |
Vertical waste is a whole cycle with nothing issued; horizontal waste is a cycle where only some issue slots are used. Only SMT removes both.
Sources: Wikipedia: Multithreading (computer architecture), Wikipedia: Simultaneous multithreading
SMT Inside an Out-of-Order Core
SMT fits naturally into the out-of-order engine from ILP: renaming turns each thread's registers into physical registers, so instructions from different threads can sit in the same issue queue without confusion.
flowchart LR
FA["Fetch thread A"] --> R["Rename<br/>(one table per thread)"]
FB["Fetch thread B"] --> R
R --> IQ["Shared issue queue"]
IQ --> EX["Shared execution units"]
EX --> ROBA["Commit thread A in order"]
EX --> ROBB["Commit thread B in order"]
Each thread still commits its own instructions in its own program order; the threads simply share the machinery in between.
Benefits and Costs
| Benefit | Cost |
|---|---|
| Higher total throughput when threads stall a lot (memory-bound, branchy code) | Each thread runs somewhat slower than if it had the core alone |
| Cheap: a fraction of a core's area | Threads compete for caches, predictor entries and queues |
| Hides memory latency without software changes | Little gain for code that already uses the core fully (dense maths) |
| Shared structures can leak information between threads (side channels), so some systems disable SMT for security |
Typical gains for two threads per core range from nothing to a few tens of percent, depending on the workload. It is never 2×, because the two threads share one set of execution units.
The GPU Extreme
A GPU applies fine-grained multithreading at huge scale: each GPU core keeps dozens of thread groups (warps or wavefronts) resident at once and picks a ready one every cycle. When one group waits hundreds of cycles for memory, others run. This is how GPUs hide memory latency without large caches or out-of-order logic. See SIMD and GPUs.
sequenceDiagram
participant S as Warp scheduler
participant W1 as Warp 1
participant W2 as Warp 2
participant W3 as Warp 3
S->>W1: issue (load from memory)
Note over W1: waiting ~hundreds of cycles
S->>W2: issue
S->>W3: issue
S->>W2: issue
S->>W3: issue
Note over W1: data arrives
S->>W1: issue (uses loaded data)
Key Points
- A hardware thread is a PC plus a register set; several share one core's execution units and caches.
- Coarse-grained switches on long stalls, fine-grained every cycle, SMT issues from several threads in the same cycle.
- Multithreading raises throughput, not single-thread speed; GPUs push the same idea to dozens of threads per core.
SIMD and GPUs
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Single instruction, multiple data
- Wikipedia: Single instruction, multiple threads
- Wikipedia: Graphics processing unit
- Wikipedia: Flynn's taxonomy
- Arm: Learn the architecture: Introducing Neon (document 102474) and Introduction to SVE (document 102476)
- Book: Hennessy and Patterson, Computer Architecture: A Quantitative Approach, chapter 4
Many programs do the same thing to lots of data: brighten every pixel, add two long arrays, multiply matrices for a neural network. SIMD (single instruction, multiple data) lets one instruction work on several data items at once. A GPU takes the idea much further, with thousands of simple lanes and many threads to hide memory delays. This page explains both, and when each is the right tool.
> Code, sizes and diagrams on this page are illustrative.
Purpose and Scope
This page covers SIMD registers and lanes, Arm Neon and SVE, vectorising a loop, what stops vectorisation, the GPU execution model (SIMT, warps, divergence, occupancy), CPU versus GPU design, and the advantages and limits of GPUs. Multithreading in general is on Multithreading.
The Stamping Analogy
| One stamp | A stamp with 4 heads |
|---|---|
| Stamp one envelope per press | Stamp four envelopes per press |
| 100 envelopes = 100 presses | 100 envelopes = 25 presses |
SIMD is the 4-headed stamp. It only helps when the envelopes are lined up and all need the same stamp.
SIMD on a CPU
A SIMD register holds several values side by side, called lanes. One instruction operates on every lane.
flowchart LR
subgraph A["V1 (4 x 32-bit)"]
a0["1"] --- a1["2"] --- a2["3"] --- a3["4"]
end
subgraph B["V2"]
b0["10"] --- b1["20"] --- b2["30"] --- b3["40"]
end
subgraph C["V0 = V1 + V2 (one ADD)"]
c0["11"] --- c1["22"] --- c2["33"] --- c3["44"]
end
A --> C
B --> C
| Register width | Lanes of 8-bit | 16-bit | 32-bit | 64-bit |
|---|---|---|---|---|
| 128 bits (Arm Neon) | 16 | 8 | 4 | 2 |
Arm Neon and SVE
| Neon (Advanced SIMD) | SVE / SVE2 (Scalable Vector Extension) | |
|---|---|---|
| Register width | Fixed 128 bits (V0-V31) | Chosen by the chip: 128 to 2048 bits, a multiple of 128 (Z0-Z31) |
| Same binary on wider hardware goes faster? | No | Yes: code is written "vector-length agnostic" |
| Loop tail (leftover elements) | Separate scalar loop | Handled by predicate registers (P0-P15) that switch lanes off |
// illustrative: for (i = 0; i < n; i++) c[i] = a[i] + b[i]; (float)
// Neon, 4 floats per step (tail loop not shown)
loop:
LD1 {V0.4S}, [X0], #16 // load 4 floats from a
LD1 {V1.4S}, [X1], #16 // load 4 floats from b
FADD V2.4S, V0.4S, V1.4S // 4 adds at once
ST1 {V2.4S}, [X2], #16 // store 4 floats to c
SUBS X3, X3, #4
B.GT loop
// SVE, any vector length, tail handled by predicate
MOV X4, #0
WHILELT P0.S, X4, X3 // lanes active while i < n
loop:
LD1W Z0.S, P0/Z, [X0, X4, LSL #2]
LD1W Z1.S, P0/Z, [X1, X4, LSL #2]
FADD Z2.S, Z0.S, Z1.S
ST1W Z2.S, P0, [X2, X4, LSL #2]
INCW X4 // i += number of 32-bit lanes
WHILELT P0.S, X4, X3
B.FIRST loop
flowchart LR
subgraph Pred["Last SVE step, n = 10, 8 lanes, i = 8"]
p0["lane 0: i=8 ✔"] --- p1["lane 1: i=9 ✔"] --- p2["lane 2: off"] --- p3["... off"]
end
Sources: Wikipedia: Single instruction, multiple data
Who Writes SIMD Code?
| Way | Effort | Notes |
|---|---|---|
| Auto-vectorisation by the compiler | None | Works for simple loops over arrays |
Intrinsics (vaddq_f32 in arm_neon.h) | Medium | Explicit control from C |
| Assembly | High | Rarely needed |
| Libraries (BLAS, image, ML) | None | Already optimised |
What Stops Vectorisation
| Problem | Example | Why |
|---|---|---|
| Loop-carried dependence | a[i] = a[i-1] + 1 | Each element needs the previous one |
| Possible aliasing | c might overlap a | Compiler can't prove lanes are independent (restrict helps) |
| Irregular access | a[idx[i]] | Needs gather instructions; slower |
| Branches inside the loop | if (a[i] > 0) ... | Needs masks/predicates or select |
| Function calls | f(a[i]) | Unless f can be inlined |
GPUs: SIMD at Enormous Scale
A CPU core is built to run one thread as fast as possible: big caches, branch prediction, out-of-order execution. A GPU is built to run huge numbers of simple threads for maximum total throughput.
flowchart LR
subgraph CPU["CPU: few powerful cores"]
direction TB
K1["Big core<br/>OoO, predictor"]
K2["Big core"]
K3["Big core"]
K4["Big core"]
BC["Large caches"]
end
subgraph GPU["GPU: many simple lanes"]
direction TB
S1["SM / compute unit<br/>32-64 lanes"]
S2["SM"]
S3["SM"]
S4["... dozens more"]
SC["Smaller caches,<br/>very high memory bandwidth"]
end
| CPU | GPU | |
|---|---|---|
| Goal | Low latency for one thread | High throughput for many |
| Cores | A few to a few dozen big ones | Dozens of compute units, thousands of lanes |
| Hiding memory delay | Large caches, out-of-order execution | Switching between many resident threads |
| Control logic per lane | Lots | Little: one instruction drives many lanes |
| Memory | Lower bandwidth, low latency | Very high bandwidth |
| Good at | Branchy, serial, irregular code | Regular, data-parallel code |
SIMT: Threads That Move in Lockstep
You program a GPU as if each data item had its own thread (CUDA, OpenCL, Vulkan compute):
// illustrative CUDA-style kernel: each thread handles one element
__global__ void add(float *a, float *b, float *c, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) c[i] = a[i] + b[i];
}
// launched with about n threads
The hardware groups threads into warps (NVIDIA, 32 threads) or wavefronts (AMD, 32 or 64). All threads in a warp run the same instruction at the same time on different data. This is called SIMT (single instruction, multiple threads): SIMD hardware presented as threads.
flowchart TD
G["Grid: the whole job"] --> B1["Block 0"]
G --> B2["Block 1"]
G --> B3["Block ..."]
B1 --> W1["Warp 0: threads 0-31"]
B1 --> W2["Warp 1: threads 32-63"]
W1 --> L["32 lanes run one instruction together"]
Sources: Wikipedia: Single instruction, multiple threads
Branch Divergence
If threads in one warp take different sides of an if, the warp runs both sides, switching lanes off as needed:
if (threadIdx.x % 2 == 0) x = A(); // even lanes
else x = B(); // odd lanes
flowchart LR
S["Warp reaches if"] --> P1["Run A()<br/>even lanes on, odd off"]
P1 --> P2["Run B()<br/>odd lanes on, even off"]
P2 --> J["Lanes rejoin"]
Half the lanes sit idle during each side, so a divergent branch can halve throughput. Branches where a whole warp goes the same way cost almost nothing.
Hiding Latency with Occupancy
Each compute unit keeps many warps resident and switches between them every cycle (Multithreading). Occupancy is how many warps are resident compared with the maximum. More warps means more work available while others wait for memory, but each warp needs registers, so register-heavy kernels get fewer warps.
Memory Coalescing
GPU memory is fastest when the 32 threads of a warp access 32 neighbouring addresses: the hardware merges them into a few wide transactions. Scattered addresses turn one transaction into many.
| Access by thread i | Result |
|---|---|
a[i] | Coalesced: one or a few transactions |
a[i * 32] | Strided: up to 32 transactions |
a[random[i]] | Scattered: slowest |
Advantages of GPUs
| Advantage | Why |
|---|---|
| Huge throughput on data-parallel work | Thousands of lanes; graphics, matrix maths, ML training and inference |
| Performance per watt for such work | Little control logic per lane; most of the chip does arithmetic |
| High memory bandwidth | Wide memory buses (GDDR, HBM) |
| Latency tolerance | Many resident warps instead of large caches |
| Specialised units | Texture units, and matrix units (tensor cores) for ML |
When a GPU Is the Wrong Tool
| Situation | Why |
|---|---|
| Serial or branchy code | Divergence and no single-thread speed |
| Small problems | Launch and data-copy overhead outweigh the gain |
| Irregular pointer chasing | Poor coalescing, no big caches |
| Frequent CPU↔GPU communication | Transfers over the bus are slow on discrete GPUs (less so on phones, where CPU and GPU share memory) |
flowchart TD
Q["Is the work the same operation on lots of independent data?"] -->|"No"| CPU1["Use the CPU"]
Q -->|"Yes"| S{"Is it small or short?"}
S -->|"Yes"| SIMD["Use CPU SIMD (Neon / SVE)"]
S -->|"No, large"| GPU1["Use the GPU"]
Sources: Wikipedia: Graphics processing unit, Wikipedia: Flynn's taxonomy
Key Points
- SIMD runs one instruction on many lanes; Arm has fixed 128-bit Neon and scalable SVE with predicates.
- GPUs group threads into warps that run in lockstep (SIMT) and hide memory delay by switching warps.
- GPUs win on large, regular, data-parallel work; divergence, scattered memory and small jobs hurt them.
Glossary and Summary
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Computer architecture
- Wikipedia: Memory hierarchy
- Book: Patterson and Hennessy, Computer Organization and Design (Arm edition)
- Book: Hennessy and Patterson, Computer Architecture: A Quantitative Approach
This page puts the whole wiki on one diagram, lists every term used on earlier pages with a one-line meaning, and suggests some self-check questions.
Purpose and Scope
This page covers a one-picture summary, the glossary, self-check questions with answers, and further reading. It introduces no new ideas.
The Whole Wiki in One Picture
flowchart TD
GOAL["Run programs faster<br/>Time = Instructions × CPI × Clock period"] --> ONE["One instruction stream"]
GOAL --> MANY["Many instruction streams"]
GOAL --> DATA["Many data items"]
GOAL --> MEMW["Waiting for memory"]
ONE --> PIPE["Pipelining<br/>overlap stages"]
PIPE --> HAZ["Hazards: structural, data, control"]
HAZ --> FWD["Forwarding, stalls, reordering"]
HAZ --> BP["Branch prediction, BTB, CSEL"]
ONE --> ILP["ILP: superscalar, out-of-order,<br/>renaming, ROB, speculation"]
MANY --> MC["Multicore<br/>Amdahl's law"]
MANY --> MT["Hardware multithreading<br/>coarse, fine, SMT"]
MC --> ORD["Memory ordering<br/>barriers, acquire/release"]
MC --> COH["Cache coherence<br/>MESI, false sharing"]
DATA --> SIMD["SIMD: Neon, SVE"]
DATA --> GPU["GPU: SIMT, warps"]
MEMW --> CACHE["Caches: lines, sets, AMAT"]
CACHE --> COH
MT --> GPU
| If your program is slow because... | Look at |
|---|---|
| It waits for memory a lot | Caches and Coherence, Multithreading |
| It has many unpredictable branches | Branches and Remedies |
| It is one long chain of dependent operations | ILP |
| It runs on one core while others are idle | Multicore |
| Threads slow each other down | Caches and Coherence (false sharing), Multicore (locks) |
| It does the same arithmetic on big arrays | SIMD and GPUs |
| Multithreaded code works on x86 but fails on Arm | Memory and Ordering |
Glossary
| Term | Meaning | Page |
|---|---|---|
| Acquire / release | One-way ordering on a load (acquire) or store (release); Arm LDAR / STLR | Memory and Ordering |
| ALU | Arithmetic logic unit: adds, compares, does logic | Fundamentals |
| Amdahl's law | Speedup is limited by the serial fraction: 1 / ((1−p) + p/N) | Multicore |
| AMAT | Average memory access time = hit time + miss rate × miss penalty | Caches and Coherence |
| Associativity | How many places (ways) in a cache a line may go | Caches and Coherence |
| Barrier (fence) | Instruction that orders memory accesses; Arm DMB, DSB, ISB | Memory and Ordering |
| big.LITTLE | Mixing fast and efficient cores on one chip | Multicore |
| Branch predictor | Hardware that guesses branch direction | Branches and Remedies |
| BTB | Branch target buffer: remembers where branches go | Branches and Remedies |
| Cache line | The unit a cache stores and moves, typically 64 bytes | Caches and Coherence |
| Coherence | Keeping all copies of one address consistent | Caches and Coherence |
| Commit (retire) | Making an instruction's result permanent, in program order | ILP |
| CPI / IPC | Cycles per instruction / instructions per cycle | Fundamentals |
| Critical path | Longest chain of dependent instructions | ILP |
| Divergence | Threads in one GPU warp taking different branch paths | SIMD and GPUs |
| False sharing | Different variables in one cache line causing coherence traffic | Caches and Coherence |
| Forwarding (bypassing) | Sending a result straight to a waiting instruction | Pipelining |
| Hardware thread | A PC plus registers sharing one core's execution units | Multithreading |
| Hazard | Something that stops the next pipeline step: structural, data, control | Pipelining |
| ILP | Instruction-level parallelism: independent instructions run together | ILP |
| ISA | Instruction set architecture: the contract between software and hardware | Overview |
| Lane | One element slot in a SIMD register or GPU warp | SIMD and GPUs |
| Latency / throughput | Time for one job / jobs per unit time | Pipelining |
| Locality | Temporal: reuse soon; spatial: use nearby data | Caches and Coherence |
| MESI | Cache line states: Modified, Exclusive, Shared, Invalid | Caches and Coherence |
| Microarchitecture | How a particular chip implements the ISA | Overview |
| Misprediction penalty | Cycles lost when a branch guess is wrong | Branches and Remedies |
| NUMA | Memory access time depends on which socket owns the memory | Multicore |
| Neon | Arm's fixed 128-bit SIMD extension | SIMD and GPUs |
| Occupancy | How many warps are resident on a GPU compute unit | SIMD and GPUs |
| Out-of-order execution | Running instructions when their inputs are ready, not in program order | ILP |
| Pipeline | Splitting instruction processing into overlapping stages | Pipelining |
| Predicate | A per-lane on/off mask (SVE P registers) | SIMD and GPUs |
| Program counter (PC) | Address of the next instruction | Fundamentals |
| RAW / WAR / WAW | Read-after-write (true), write-after-read and write-after-write (false) dependences | Pipelining |
| Register renaming | Mapping architectural registers to many physical ones to remove false dependences | ILP |
| ROB | Reorder buffer: tracks program order for in-order commit | ILP |
| Sequential consistency | All cores see one interleaving that respects each core's program order | Memory and Ordering |
| SIMD | Single instruction, multiple data | SIMD and GPUs |
| SIMT | Single instruction, multiple threads: the GPU model | SIMD and GPUs |
| SMT | Simultaneous multithreading: several threads issue in one cycle | Multithreading |
| Speculation | Running instructions before knowing they are needed | ILP |
| Stall (bubble) | A cycle where a pipeline stage does no useful work | Pipelining |
| Store buffer | Queue holding stores before they reach the cache | Memory and Ordering |
| Superscalar | Issuing more than one instruction per cycle | ILP |
| SVE | Arm's Scalable Vector Extension, 128 to 2048 bits | SIMD and GPUs |
| TSO | Total store order: x86's memory model | Memory and Ordering |
| VLIW | Very long instruction word: compiler packs parallel operations | ILP |
| Von Neumann bottleneck | Program and data share one path to memory | Fundamentals |
| Warp / wavefront | Group of GPU threads running in lockstep (32 or 64) | SIMD and GPUs |
| Write-back / write-through | Update memory on eviction / on every store | Caches and Coherence |
Self-Check Questions
- A program runs 1 billion instructions at CPI 2 on a 1 GHz clock. How long does it take? (2 s.) (Fundamentals)
- Why does pipelining not make a single instruction finish sooner? (It improves throughput, not latency.) (Pipelining)
LDR X1,[X0]is followed immediately byADD X2,X1,X3. Why does forwarding not remove the stall completely? (The load's data only arrives after MEM.) (Pipelining)- Why does a 2-bit counter mispredict a 10-iteration loop only once per run, when a 1-bit predictor misses twice? (Branches and Remedies)
- 25% of instructions are branches, 4% are mispredicted, the penalty is 20 cycles, base CPI is 1. What is the CPI? (1 + 0.25 × 0.04 × 20 = 1.2.) (Branches and Remedies)
- Which of RAW, WAR and WAW does register renaming remove? (WAR and WAW.) (ILP)
- In the message-passing example, what must the producer and consumer use on Arm? (Store-release and load-acquire, or barriers.) (Memory and Ordering)
- A 64 KB, 8-way cache with 64-byte lines has how many sets? (64 KB / 64 B = 1024 lines; / 8 = 128 sets.) (Caches and Coherence)
- Two threads increment two different counters in one struct and run slower with two cores than with one. Why? (False sharing.) (Caches and Coherence)
- With 80% parallel code, what is the speedup on 8 cores, and the limit? (1 / (0.2 + 0.1) = 3.33; limit 5.) (Multicore)
- Why does SMT never double performance? (Both threads share the same execution units and caches.) (Multithreading)
- Why is
if (threadIdx.x % 2)slow on a GPU butif (blockIdx.x % 2)not? (The first splits every warp; the second sends whole warps one way.) (SIMD and GPUs)
Further Reading
| Resource | Good for |
|---|---|
| Patterson and Hennessy, Computer Organization and Design (Arm edition) | A full beginner course: the material of pages 2-8 in depth |
| Hennessy and Patterson, Computer Architecture: A Quantitative Approach | The next step: ILP, memory hierarchy, multicore, GPUs |
| Arm Learn the architecture guides (developer.arm.com): Memory Systems, Ordering, and Barriers (102336); Introducing Neon (102474); Introduction to SVE (102476) | Arm-specific detail for pages 6, 7 and 10 |
| Arm Architecture Reference Manual for A-profile (DDI 0487) | The definitive rules, for reference rather than reading |
| The Wikipedia articles linked from each page | Quick refreshers and further links |
For how compilers make use of all this, see the Instruction Scheduling wiki and the LLVM IR wiki.