Repository navigation
IR 02 structure
Relevant source files
The following files were used as context for generating this wiki page:
An LLVM IR program is a tree of containers: a module holds functions and globals, a function holds basic blocks, and a basic block holds instructions. On top of that tree sits a graph: every instruction that uses a value points to it, and every value keeps a list of its uses. This page explains both.
This page covers the containers (Module, Function, BasicBlock, Instruction), the value hierarchy (Value, User, Use), globals, attributes and metadata. Instruction semantics are on the following pages, starting with Arithmetic.
flowchart TD
M["Module (one .ll file)"] --> G["GlobalVariable @counter"]
M --> F1["Function @main"]
M --> F2["Function @helper (declaration only)"]
F1 --> A["Argument %argc"]
F1 --> B1["BasicBlock entry"]
F1 --> B2["BasicBlock loop"]
B1 --> I1["Instruction %x = add ..."]
B1 --> I2["Terminator br label %loop"]
A complete module (illustrative):
; ModuleID = 'example.c'
source_filename = "example.c"
target datalayout = "e-m:e-i64:64-i128:128-n32:64-S128"
target triple = "aarch64-unknown-linux-gnu"
@counter = global i32 0, align 4 ; a global variable
declare i32 @puts(ptr) ; a declaration: no body
define i32 @bump(i32 %by) #0 { ; a definition: has blocks
entry:
%old = load i32, ptr @counter, align 4
%new = add i32 %old, %by
store i32 %new, ptr @counter, align 4
ret i32 %new
}
attributes #0 = { nounwind }| Level | Class | What it holds |
|---|---|---|
| Module | Module |
Globals, functions, the target triple and data layout, named metadata |
| Function | Function |
Arguments, a list of basic blocks (none for a declare), attributes |
| Basic block | BasicBlock |
A list of instructions; the last one is a terminator |
| Instruction | Instruction |
An opcode, a type and operands |
Function derives from GlobalObject: a function is a global value, and its name @bump is its address. BasicBlock derives from Value, which is why a block label such as label %loop can be an operand of a branch.
Sources: llvm/include/llvm/IR/Function.h:65, llvm/include/llvm/IR/BasicBlock.h:61
A basic block is a sequence of instructions with one entry (the top) and one exit (the terminator at the bottom). Control never jumps into the middle of a block. Two rules follow:
- Every block ends in exactly one terminator (
ret,br,switch,unreachable, ...).BasicBlock::getTerminator()returns it, or null if the block is malformed. -
phiinstructions, if any, must come first in the block, see SSA and Phi.
The first block of a function is its entry block. It has no predecessors, and it is where allocas for local variables are conventionally placed.
Sources: llvm/include/llvm/IR/BasicBlock.h:237
Almost everything in IR is a Value: arguments, instructions, basic blocks, functions, globals and constants. A User is a value that has operands, which includes every instruction. Each operand slot is a Use, which links the user to the value it uses.
classDiagram
Value <|-- Argument
Value <|-- BasicBlock
Value <|-- User
User <|-- Instruction
User <|-- Constant
Constant <|-- GlobalValue
GlobalValue <|-- GlobalObject
GlobalObject <|-- Function
GlobalObject <|-- GlobalVariable
class Value { type, name, use list }
class User { operand list of Use }
class Use { Val, Parent user }
For %new = add i32 %old, %by:
- The
addinstruction is aUserwith twoUses. - Use 0 points to
%old(theload), use 1 points to%by(anArgument). -
%oldkeeps theaddon its use list, so%old->users()finds it.
Because SSA gives each value exactly one definition, the def-use graph is just these pointers. V->replaceAllUsesWith(W) walks V's use list and redirects every Use to W; this is the basic move of most transformations.
// Illustrative: print every instruction that uses value V.
for (User *U : V->users())
if (auto *I = dyn_cast<Instruction>(U))
errs() << *I << "\n";Sources: llvm/include/llvm/IR/Value.h:75, llvm/include/llvm/IR/User.h:44, llvm/include/llvm/IR/Use.h:35
| Prefix | Scope | Examples |
|---|---|---|
@ |
Module (global) |
@main, @counter, @puts
|
% |
Function (local) |
%a, %sum, %entry
|
! |
Metadata |
!0, !dbg, !tbaa
|
# |
Attribute group | #0 |
Names are optional. An unnamed value is printed with a number, %0, %1, ..., assigned in order through the function, which is why Clang output is full of %0, %1. Names are only for humans; passes compare Value* pointers, never names.
Attributes are facts attached to functions, parameters or return values that passes may rely on:
| Attribute | Meaning |
|---|---|
nounwind |
The function never throws an exception |
readnone / memory(none)
|
The function does not touch memory |
noalias on a ptr parameter |
No other pointer visible to the function aliases it (like C restrict) |
nonnull, dereferenceable(N)
|
Pointer facts |
noinline, alwaysinline, optnone
|
Inliner and optimizer controls |
Metadata is extra information that may be dropped without changing the meaning of the program: debug locations (!dbg), type-based alias info (!tbaa), loop hints (!llvm.loop), branch weights (!prof). It is written after the instruction:
%v = load i32, ptr %p, align 4, !tbaa !5 ; illustrative- Module, function, block, instruction is a strict containment tree.
- Every block ends in exactly one terminator.
- Everything is a
Value; operands areUses; use lists give def-use chains for free.
- 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