Repository navigation
IR 13 common passes
Relevant source files
The following files were used as context for generating this wiki page:
A handful of passes do most of the work in every optimization pipeline. Each is simple to describe in terms of the ideas from earlier pages: mem2reg builds SSA, instcombine rewrites instruction patterns, simplifycfg cleans up the CFG, gvn removes redundant computations, licm moves work out of loops, and dce deletes unused code. This page shows what each one does with a small before/after example.
All before/after IR on this page is illustrative, written by hand to show the typical effect of each pass. It was not produced by running
opt.
This page covers six passes, the analyses each relies on, and the source location of each run method. It is not a full description of any of them: instcombine alone has thousands of rewrite rules. Writing your own pass is on Writing a Pass.
| Pass name | What it does | Relies on | Entry point |
|---|---|---|---|
mem2reg |
Promote allocas to SSA values, insert phis |
Dominator tree | PromoteMemToReg |
instcombine |
Local algebraic rewrites and canonicalisation | Known bits, simplify queries | InstCombinePass::run |
simplifycfg |
Merge, remove and simplify blocks and branches | CFG only | SimplifyCFGPass::run |
gvn |
Remove redundant computations and loads | Dominator tree, memory dependence, alias analysis | GVNPass::run |
licm |
Hoist loop-invariant code out of loops, sink code below them | Loop info, dominator tree, MemorySSA | LICMPass::run |
dce / adce
|
Delete instructions whose results are unused | Use lists; adce also post-dominators |
DCEPass::run |
Sources: llvm/lib/Passes/PassRegistry.def:410, llvm/lib/Passes/PassRegistry.def:432, llvm/lib/Passes/PassRegistry.def:491, llvm/lib/Passes/PassRegistry.def:609-621
Covered in detail on SSA and Phi.
; before ; after
%x = alloca i32 ;
store i32 %a, ptr %x ;
%v = load i32, ptr %x ;
%r = add i32 %v, 1 %r = add i32 %a, 1In the standard -O pipelines its job is done by sroa, which also splits structs and arrays into separate scalars first.
Sources: llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp:1259
instcombine visits instructions one at a time and replaces each with a simpler or more canonical equivalent. It keeps a worklist: whenever it changes an instruction, that instruction's users go back on the list, and it runs until the worklist is empty.
; before
%a = add i32 %x, 0 ; x + 0
%b = mul i32 %a, 8 ; x * 8
%c = sub i32 0, %b
%d = sub i32 %y, %c ; y - (0 - b)
; after
%b = shl i32 %x, 3
%d = add i32 %y, %bTypical rules: identities (x+0, x*1, x&x), strength reduction (mul by a power of two to shl), constant folding, removing double negation, and putting constants on the right (add 1, %x becomes add %x, 1) so that other rules only need to match one form.
Canonicalisation matters as much as simplification: if every pass can rely on one shape for an idiom, each pass needs fewer patterns.
Sources: llvm/lib/Transforms/InstCombine/InstructionCombining.cpp:5777, llvm/lib/Transforms/InstCombine/InstructionCombining.cpp:6255
simplifycfg cleans up the CFG: it deletes unreachable blocks, merges a block into its only predecessor, removes empty forwarding blocks, folds branches on constants, and turns small if/else diamonds into select.
Continuing the @pick example from SSA and Phi:
; before (after mem2reg)
entry:
%tobool = icmp ne i32 %c, 0
br i1 %tobool, label %if.then, label %if.else
if.then:
br label %if.end
if.else:
br label %if.end
if.end:
%x.0 = phi i32 [ 1, %if.then ], [ 2, %if.else ]
ret i32 %x.0
; after
entry:
%tobool = icmp ne i32 %c, 0
%x.0 = select i1 %tobool, i32 1, i32 2
ret i32 %x.0Three blocks and two branches became one block. instcombine might then simplify the select further.
Sources: llvm/lib/Transforms/Scalar/SimplifyCFGPass.cpp:378
Global value numbering gives every computed value a number such that two instructions get the same number when they are certain to compute the same result. If an instruction's number was already computed by an instruction that dominates it, the second one is replaced by the first.
; before
%a1 = add i32 %x, %y
%v1 = load i32, ptr %p
call void @use(i32 %a1, i32 %v1)
%a2 = add i32 %x, %y ; same as %a1
%v2 = load i32, ptr %p ; same as %v1 if nothing wrote *p in between
call void @use(i32 %a2, i32 %v2)
; after (assuming @use cannot write *p, e.g. it is memory(none))
%a1 = add i32 %x, %y
%v1 = load i32, ptr %p
call void @use(i32 %a1, i32 %v1)
call void @use(i32 %a1, i32 %v1)The arithmetic part needs only SSA and dominance. The load part needs memory dependence and alias analysis: GVN must prove that no store or call in between could have changed *p. This is the "available expressions" idea from Data-flow Analysis, done sparsely on SSA values.
Sources: llvm/lib/Transforms/Scalar/GVN.cpp:892, llvm/lib/Transforms/Scalar/GVN.cpp:3315
Loop-invariant code motion moves computations whose operands do not change inside a loop out to the loop's preheader (see CFG and Loops), so they run once instead of every iteration.
; before
loop:
%i = phi i64 [ 0, %entry ], [ %i.next, %loop ]
%scale = mul i64 %n, 4 ; %n is defined outside the loop
%off = add i64 %i, %scale
...
br i1 %done, label %exit, label %loop
; after
entry: ; the preheader
%scale = mul i64 %n, 4
br label %loop
loop:
%i = phi i64 [ 0, %entry ], [ %i.next, %loop ]
%off = add i64 %i, %scale
...hoistRegion walks the loop's blocks in dominator-tree order and hoists an instruction when all its operands are defined outside the loop and moving it is safe: it must not trap (a division might, if the loop could run zero times) and, for loads, nothing in the loop may write that memory. sinkRegion does the reverse, moving code that is only needed after the loop into the exit blocks. LICM is a loop pass: LICMPass::run takes a Loop &.
Sources: llvm/lib/Transforms/Scalar/LICM.cpp:311, llvm/lib/Transforms/Scalar/LICM.cpp:567, llvm/lib/Transforms/Scalar/LICM.cpp:896
dce deletes instructions that have no uses and no side effects, using the worklist described on Data-flow Analysis:
; before
%a = add i32 %x, 1
%b = mul i32 %a, 2 ; %b is never used
ret i32 %x
; after
ret i32 %xDeleting %b makes %a unused too, so it is deleted next. Stores and calls with side effects are kept even if they produce no used value.
adce (aggressive DCE) works the other way: it assumes everything is dead, marks as live only instructions with side effects and whatever they transitively use, and deletes the rest. With post-dominance (see Dominance) it can also delete branches whose outcome does not affect any live instruction, and so remove whole loops that compute nothing.
Sources: llvm/lib/Transforms/Scalar/DCE.cpp:89-110
No single pass does much alone; each one creates opportunities for the others. A typical sequence on Clang output:
flowchart LR
S["sroa / mem2reg<br/>SSA from allocas"] --> I1["instcombine<br/>simplify"]
I1 --> C["simplifycfg<br/>clean CFG"]
C --> L["licm<br/>hoist from loops"]
L --> G["gvn<br/>remove redundancy"]
G --> I2["instcombine"]
I2 --> D["dce / adce"]
Try it on a file of your own:
opt -S -passes='mem2reg,instcombine,simplifycfg' in.ll
opt -S -passes='mem2reg,loop-simplify,licm,gvn,dce' in.ll
opt -S -O2 in.ll ; the full default pipeline
opt -S -O2 -print-after-all in.ll 2> trace.txt ; IR after every pass
-
mem2regbuilds SSA;instcombineandsimplifycfgclean up locally and in the CFG. -
gvnremoves redundant values and loads;licmmoves invariant work to the preheader. -
dce/adceremove what other passes left unused; passes are run repeatedly because each enables the others.
- 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