Repository navigation
IR 06 memory
Relevant source files
The following files were used as context for generating this wiki page:
SSA values live in unlimited virtual registers, but programs also need memory: stack variables, globals, the heap and anything reached through a pointer. LLVM IR touches memory only through a few explicit instructions. alloca reserves stack space, load reads, store writes, and getelementptr computes addresses without touching memory at all.
This page covers alloca, load, store, getelementptr (with worked offset calculations), and gives a short introduction to atomics and fences. How mem2reg removes most allocas is on SSA and Phi.
| Opcode | C++ class | Purpose |
|---|---|---|
alloca |
AllocaInst |
Reserve space in the current function's stack frame |
load |
LoadInst |
Read a value of a stated type from an address |
store |
StoreInst |
Write a value to an address |
getelementptr |
GetElementPtrInst |
Compute an address from a base pointer and indices |
fence |
FenceInst |
Order memory operations between threads |
cmpxchg |
AtomicCmpXchgInst |
Atomic compare and exchange |
atomicrmw |
AtomicRMWInst |
Atomic read-modify-write (add, xchg, max, ...) |
Sources: llvm/include/llvm/IR/Instruction.def:171-179
%x = alloca i32, align 4 ; illustrative: int x;
%buf = alloca [16 x i8], align 1 ; char buf[16];alloca returns a ptr to fresh stack memory that is freed automatically when the function returns. The memory starts uninitialised. Clang puts every local variable, and every parameter, in an alloca in the entry block, because that is easy to generate; mem2reg later turns most of them into SSA values.
Sources: llvm/include/llvm/IR/Instructions.h:65
; illustrative: x = x + 1;
%old = load i32, ptr %x, align 4
%new = add nsw i32 %old, 1
store i32 %new, ptr %x, align 4-
load <type>, ptr <addr>reads. Because pointers are opaque, the type is written on the instruction. -
store <type> <value>, ptr <addr>writes. The value comes first, then the address.storeproduces no value. -
align Npromises that the address is a multiple of N. Lying about alignment is undefined behaviour. -
volatile(load volatile i32, ...) forbids the optimizer from removing or merging the access, for memory-mapped hardware.
Sources: llvm/include/llvm/IR/Instructions.h:197, llvm/include/llvm/IR/Instructions.h:338
getelementptr (GEP) computes base + offset, where the offset comes from walking a type with a list of indices. It never reads memory; it only does arithmetic. Its form is:
%p = getelementptr [inbounds] <source element type>, ptr %base, <idx0>, <idx1>, ...
The rules:
- The first index steps over whole copies of the source element type, as in C pointer arithmetic
base + idx0. - Each later index steps into the current type: an array index picks an element, a struct index (always a constant
i32) picks a field.
These assume the AArch64 data layout: i32 is 4 bytes, ptr and i64 are 8 bytes, aligned to their size.
Array element. int a[10]; ... &a[i]
; illustrative
@a = global [10 x i32] zeroinitializer
%p = getelementptr inbounds [10 x i32], ptr @a, i64 0, i64 %iIndex 0 steps over 0 whole arrays, index %i picks element i: offset = 0 * 40 + i * 4.
The same address can be written with a simpler source type, and newer Clang usually emits this form:
%p = getelementptr inbounds i32, ptr @a, i64 %i ; offset = i * 4Struct field. struct Point { int x; int y; }; ... &pts[1].y
; illustrative
%struct.Point = type { i32, i32 }
%q = getelementptr inbounds %struct.Point, ptr %pts, i64 1, i32 1Index 1 steps over one whole Point (8 bytes); field index 1 picks y at offset 4 within it. Total offset 12.
Struct with padding. struct Node { int v; struct Node *next; }; ... &n->next
; illustrative
%struct.Node = type { i32, ptr }
%nx = getelementptr inbounds %struct.Node, ptr %n, i64 0, i32 1ptr is 8-byte aligned, so there are 4 padding bytes after v and next is at offset 8, not 4. The data layout decides this, not the GEP.
| Example | Indices | Offset in bytes |
|---|---|---|
&a[i] |
0, %i on [10 x i32]
|
4*i |
&pts[1].y |
1, 1 on {i32, i32}
|
8 + 4 = 12 |
&n->next |
0, 1 on {i32, ptr}
|
8 |
inbounds promises that the base and the result point into the same allocated object (or one past its end). If that is false the result is poison. It lets alias analysis assume that &a[i] cannot point into some other variable.
A common beginner mistake is to think GEP dereferences a pointer. p->next->v needs two GEPs with a load between them, because following next reads memory:
; illustrative: p->next->v
%nextaddr = getelementptr inbounds %struct.Node, ptr %p, i64 0, i32 1
%next = load ptr, ptr %nextaddr, align 8
%vaddr = getelementptr inbounds %struct.Node, ptr %next, i64 0, i32 0
%v = load i32, ptr %vaddr, align 4Sources: llvm/include/llvm/IR/Instructions.h:1034
For multi-threaded code, loads and stores can be atomic with an ordering, and there are three extra instructions:
; illustrative
%v = load atomic i32, ptr %p acquire, align 4
store atomic i32 1, ptr %p release, align 4
%old = atomicrmw add ptr %counter, i32 1 seq_cst
%pair = cmpxchg ptr %p, i32 %expected, i32 %new seq_cst seq_cst
fence seq_cstThe orderings (monotonic, acquire, release, acq_rel, seq_cst) follow the C++11 memory model. cmpxchg returns a { i32, i1 } struct: the old value and whether the exchange happened. Most optimizations leave atomics alone.
- Only
load,store, atomics and calls touch memory;getelementptris pure arithmetic. - The first GEP index steps over whole objects; later indices step into arrays and structs.
- Clang emits an
allocaper local variable;mem2regremoves most of them.
- 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