Repository navigation
IR 01 overview
Relevant source files
The following files were used as context for generating this wiki page:
LLVM IR (intermediate representation) is the language that sits between a front end such as Clang and a back end such as the AArch64 code generator. A front end translates source code into IR, the optimizer rewrites IR into faster IR, and a back end translates IR into machine code. This wiki explains IR from the ground up: what it looks like, what each instruction does, and the analyses (CFG, dominance, data flow) that passes use to transform it.
Note on examples. Every IR listing in this wiki is illustrative: hand-written to match what LLVM produces, but not captured from a tool run. The local build at the time of writing had no
clangoropt. Line-numbered source citations were checked against the LLVM checkout at commita2171756.
This wiki is for readers who have never worked with LLVM IR. It covers:
| Topic | Page |
|---|---|
| How a module is organised | Structure |
| Types | Type System |
| The instruction set | Arithmetic, Compare and Select, Memory, Control Flow |
SSA form and phi
|
SSA and Phi |
| Program analysis | CFG and Loops, Dominance, Data-flow Analysis |
| Writing and using passes | Writing a Pass, Common Passes |
| Practice | Exercises, Tooling and Glossary |
What happens after the optimizer, when IR becomes machine instructions, is covered by the SelectionDAG wiki and the Target Bring-up wiki.
Without a shared IR, every language would need its own optimizer and its own back end for every processor: N languages times M targets. With one IR in the middle, each front end only emits IR and each back end only consumes it, so the work is N + M, and every optimization written once on IR benefits every language and every target.
flowchart LR
C["C / C++ (Clang)"] --> IR["LLVM IR"]
R["Rust (rustc)"] --> IR
S["Swift"] --> IR
IR --> OPT["Optimizer (opt passes)"]
OPT --> IR2["Optimized IR"]
IR2 --> A64["AArch64 back end"]
IR2 --> X86["X86 back end"]
IR2 --> GPU["GPU back ends"]
LLVM IR has three properties that make it convenient to optimize:
| Property | Meaning | Why it helps |
|---|---|---|
| Typed | Every value has a type such as i32, double or ptr
|
Passes can check that a rewrite keeps types consistent; the verifier rejects ill-typed IR |
| SSA (static single assignment) | Each value is assigned exactly once | The definition of a value is a single instruction, so "where did this come from?" is a pointer lookup, see SSA and Phi |
| Low level but target independent | Instructions are close to machine operations (add, load, branch) but there are unlimited virtual registers and no fixed calling convention | Optimizations can reason about real costs without knowing the target |
This C function:
int add(int a, int b) { return a + b; }becomes, after optimization, roughly this IR (illustrative):
define i32 @add(i32 %a, i32 %b) {
entry:
%sum = add nsw i32 %a, %b
ret i32 %sum
}Reading it line by line:
-
define i32 @add(i32 %a, i32 %b)defines a function named@addthat returns ani32(32-bit integer). Names starting with@are global (functions and global variables); names starting with%are local to the function. -
entry:is the label of a basic block, a straight-line list of instructions. -
%sum = add nsw i32 %a, %badds twoi32values.nsw("no signed wrap") records that C signed overflow is undefined, see Arithmetic. -
ret i32 %sumreturns the result. Every basic block ends with exactly one such terminator instruction.
The same IR exists in three interchangeable forms:
| Form | File | Produced by | Read by |
|---|---|---|---|
| Text assembly | .ll |
clang -S -emit-llvm, llvm-dis, opt -S
|
Humans, llvm-as, opt, llc
|
| Bitcode | .bc |
clang -c -emit-llvm, llvm-as, opt
|
opt, llc, llvm-dis, the linker for LTO |
| In memory | C++ objects | The IR parser or bitcode reader | Passes |
flowchart LR
LL[".ll text"] -->|llvm-as| BC[".bc bitcode"]
BC -->|llvm-dis| LL
LL -->|parse| MEM["In-memory Module<br/>(Function, BasicBlock, Instruction)"]
BC -->|read| MEM
MEM -->|print| LL
MEM -->|write| BC
The text and bitcode forms are lossless encodings of the in-memory form. Passes only ever see the in-memory form: a Module containing Functions, each containing BasicBlocks, each containing Instructions, all of which derive from Value.
Sources: llvm/include/llvm/IR/Value.h:75, llvm/include/llvm/IR/Function.h:65
All IR opcodes are listed in one file, Instruction.def, grouped by kind:
| Group | Lines | Examples | Page |
|---|---|---|---|
| Terminators | 126-139 |
ret, br, switch, invoke, unreachable
|
Control Flow |
| Unary | 142-144 | fneg |
Arithmetic |
| Binary | 147-168 |
add, fmul, sdiv, shl, xor
|
Arithmetic |
| Memory | 171-179 |
alloca, load, store, getelementptr, atomics |
Memory |
| Casts | 184-199 |
trunc, zext, sext, sitofp, bitcast
|
Arithmetic |
| Other | 207-223 |
icmp, fcmp, phi, call, select, freeze
|
Compare, SSA and Phi |
Sources: llvm/include/llvm/IR/Instruction.def:126-223
The optimizer is a sequence of passes. Each pass either analyses IR (computing facts such as the dominator tree) or transforms it (for example promoting stack variables to registers). opt runs passes by name; the names are registered in PassRegistry.def, for example mem2reg at line 491 and print<domtree> at line 522.
opt -S -passes=mem2reg in.ll -o out.ll
opt -disable-output -passes='print<domtree>' in.ll
Sources: llvm/lib/Passes/PassRegistry.def:491, llvm/lib/Passes/PassRegistry.def:522
- Overview (this page).
- Structure: modules, functions, blocks, instructions, values and uses.
- Type System.
- Arithmetic, Bitwise and Casts.
- Compare and Select.
- Memory.
- Control Flow.
- SSA and Phi.
- CFG and Loops.
- Dominance.
- Data-flow Analysis.
- Writing a Pass.
- Common Passes.
- Exercises, Tooling and Glossary.
- 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