Repository navigation
IR 14 tooling glossary
Relevant source files
The following files were used as context for generating this wiki page:
This page collects the command-line tools for working with IR, a set of exercises that follow the order of the wiki, and a glossary of the terms used on earlier pages.
This page covers the IR tools (clang, opt, llvm-as, llvm-dis, llc, lli), the most useful opt options, exercises with hints, and a glossary. All command lines are illustrative; the expected results in the exercises were worked out by hand, not captured from a tool run.
| Tool | Input | Output | Typical use |
|---|---|---|---|
clang -S -emit-llvm |
C/C++ | .ll |
See what IR a C function becomes |
clang -c -emit-llvm |
C/C++ | .bc |
Bitcode for LTO or opt
|
opt |
.ll / .bc
|
.ll / .bc / analysis printouts |
Run passes |
llvm-as |
.ll |
.bc |
Assemble text to bitcode |
llvm-dis |
.bc |
.ll |
Disassemble bitcode to text |
llc |
.ll / .bc
|
.s / .o
|
Run the back end |
lli |
.ll / .bc
|
program output | Execute IR directly with the JIT |
llvm-link |
several .bc
|
one .bc
|
Merge modules |
# Unoptimised IR, but still optimisable by opt (no optnone attribute):
clang -O0 -Xclang -disable-O0-optnone -S -emit-llvm f.c -o f.ll
# Optimised IR, without the names Clang would discard in release builds kept:
clang -O2 -S -emit-llvm -fno-discard-value-names f.c -o f.O2.ll
# Run single passes, check the result:
opt -S -passes='mem2reg,verify' f.ll -o f.m2r.ll
# Analyses:
opt -disable-output -passes='print<domtree>' f.m2r.ll
opt -disable-output -passes='print<postdomtree>' f.m2r.ll
opt -disable-output -passes='print<loops>' f.m2r.ll
opt -disable-output -passes=dot-cfg f.m2r.ll # writes .<fn>.dot files
# See what each pass in -O2 does:
opt -S -O2 -print-after-all f.ll 2> trace.txt
opt -S -O2 -print-changed f.ll 2> changes.txt # only passes that changed IR
opt -disable-output -O2 -debug-pass-manager f.ll # pass and analysis order
The names after -passes= come from PassRegistry.def, for example verify (line 564), dot-cfg (line 436) and the printers at lines 522-530.
Sources: llvm/lib/Passes/PassRegistry.def:436, llvm/lib/Passes/PassRegistry.def:522-530, llvm/lib/Passes/PassRegistry.def:564
Each exercise names the page it practises.
-
Read IR (Overview, Structure). Compile
int sq(int x) { return x * x; }with-O2 -S -emit-llvm. Identify the function definition, the block label, the terminator and every attribute group. Expected core:%mul = mul nsw i32 %x, %xthenret i32 %mul. -
Signedness (Type System, Compare). Compile
int lt(int a, int b){return a<b;}and the same withunsigned. Whichicmppredicate changes? (Hint:sltvsult; nothing else changes.) -
Flags (Arithmetic). Why does
int f(int x){return x+1 > x;}fold toreturn 1at-O2, but theunsignedversion does not? (Hint:nsw.) -
GEP by hand (Memory). For
struct S { char c; int i; long l; }on AArch64, give the byte offsets ofc,i,l, and write the GEP for&s[2].l. (Answer: 0, 4, 8; size 16; offset 216+8 = 40;getelementptr inbounds %struct.S, ptr %s, i64 2, i32 2.)* -
Control flow (Control Flow). Compile a
switchwith four cases. Find theswitchinstruction and its default target. Then compile at-O2and see whether it stays aswitchor becomes a table lookup. -
mem2reg (SSA and Phi). Take
max(a,b)written withif/elseand a local variable. Runopt -passes=mem2regand find thephi. Then addsimplifycfgand confirm it becomes aselect. -
Escaping alloca (SSA and Phi). Add
foo(&x);to exercise 6. Why doesmem2regnow leavexin memory? (Hint:isAllocaPromotable.) -
CFG and loops (CFG and Loops). For a nested
forloop, runprint<loops>and identify each loop's header, latch and depth. Draw the CFG withdot-cfg. -
Dominance by hand (Dominance). For the CFG
entry→A, A→B, A→C, B→D, C→D, D→E, E→A, E→exit, compute the idom of each block and DF(B), DF(D), DF(E). Check withprint<domtree>. (Answer: idom(A)=entry, idom(B)=idom(C)=idom(D)=A, idom(E)=D, idom(exit)=E; DF(B)=DF(C)={D}, DF(D)=DF(E)={A}.) -
Liveness (Data-flow Analysis). Run the worklist algorithm by hand on
B1: a=1; b=2 → B2: c=a+b; if c<10 → (B3: a=c → B2) | B4: return b. Which variables are live into B2? (Answer: {a, b}.) -
Your first pass (Writing a Pass). Build
CountInstsPassand print, per function, the count of each opcode name (I.getOpcodeName()). Compare before and after-O2. -
Transformation (Writing a Pass). Extend
MulToShiftPassto rewriteudiv x, 2^kintolshr x, k. Why is the same rewrite wrong forsdiv? (Hint: try-1 / 2.) -
Pipeline (Common Passes). Write a loop with an invariant multiply. Run
mem2reg,loop-simplify,licmand find where the multiply moved.
| Term | Meaning | Page |
|---|---|---|
| Alloca | Stack allocation instruction; returns a ptr
|
Memory |
| Analysis | A pass that computes a cached result without changing IR | Writing a Pass |
| Back edge | A CFG edge whose target dominates its source | CFG and Loops |
| Basic block | Straight-line instructions ending in one terminator | Structure |
| Bitcode | The binary .bc form of IR |
Overview |
| Canonical form | The one shape passes agree to use for an idiom | Common Passes |
| CFG | Control flow graph of blocks and terminator edges | CFG and Loops |
| Critical edge | Edge from a multi-successor block to a multi-predecessor block | CFG and Loops |
| Data layout | Module string that fixes sizes, alignment and endianness | Type System |
| Dominance frontier | Blocks where a block's dominance ends; where phis go |
Dominance |
| Dominator tree | Tree of immediate dominators | Dominance |
| Fast-math flags | Per-instruction permission to relax IEEE floating-point rules | Arithmetic |
| GEP |
getelementptr, address arithmetic without memory access |
Memory |
| Header | The entry block of a natural loop | CFG and Loops |
| Intrinsic | Built-in function named llvm.*
|
Control Flow |
| Latch | Loop block with a back edge to the header | CFG and Loops |
| Liveness | Whether a value may be read later | Data-flow Analysis |
| Metadata | Optional extra information (!dbg, !tbaa) |
Structure |
| Module | The top-level container: one .ll file |
Structure |
nsw / nuw
|
No signed / unsigned wrap promise | Arithmetic |
| Opaque pointer | The single ptr type, with no pointee type |
Type System |
| Phi | Instruction choosing a value by incoming edge | SSA and Phi |
| Poison | Value from a broken promise; UB only when it reaches a side effect | Arithmetic |
| Post-dominance | Dominance on the reversed CFG | Dominance |
| Preheader | Unique block outside a loop that enters the header | CFG and Loops |
PreservedAnalyses |
What a pass returns to say which analyses are still valid | Writing a Pass |
| SSA | Static single assignment: one definition per value | SSA and Phi |
| Terminator | Last instruction of a block (br, ret, switch, ...) |
Control Flow |
| Use | One operand slot linking a user to a value | Structure |
| Value | Base class of almost everything in IR | Structure |
| Worklist | Queue of items to revisit until a fixed point | Data-flow Analysis |
Sources: llvm/include/llvm/IR/Instruction.def:126-223
- How IR becomes machine instructions: SelectionDAG wiki.
- How a new target plugs into that: Target Bring-up wiki.
- 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