Repository navigation
Computer Architecture 06 memory 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.
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.
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 |
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 (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.
// 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 |
| 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
| 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
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
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
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"]
- 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.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look