Repository navigation
IR 09 cfg
Relevant source files
The following files were used as context for generating this wiki page:
The control flow graph (CFG) of a function has one node per basic block and one edge for each way a terminator can jump. LLVM does not store the CFG as a separate data structure: successors are read from the terminator's operands, and predecessors are found by walking the block's use list. Loops are found from the CFG by the LoopInfo analysis.
This page covers predecessors and successors, the entry and exit blocks, critical edges, and natural loops with their header, preheader, latch and exits. The dominance theory that loop detection relies on is on Dominance.
| Query | How LLVM answers it | Cost |
|---|---|---|
successors(BB) |
The block operands of BB's terminator |
Constant per successor |
predecessors(BB) |
Users of BB (as a Value) that are terminators |
Walks the use list |
pred_empty(BB) |
No predecessors (entry block, or unreachable) | |
BB->getSinglePredecessor() |
The one predecessor, or null |
// Illustrative: print the CFG edges of a function.
for (BasicBlock &BB : F)
for (BasicBlock *Succ : successors(&BB))
errs() << BB.getName() << " -> " << Succ->getName() << "\n";Because a block is a Value and every branch uses it as an operand, the predecessor list is just the block's use list filtered to terminators. That is why pred_begin is an iterator over uses.
Sources: llvm/include/llvm/IR/CFG.h:99-119, llvm/include/llvm/IR/CFG.h:147, llvm/include/llvm/IR/CFG.h:170
Using @sum from SSA and Phi:
flowchart TD
E["entry"] --> C["for.cond<br/>(phis, icmp, br)"]
C -->|true| B["for.body"]
C -->|false| X["for.end<br/>ret"]
B -->|back edge| C
| Block | Predecessors | Successors |
|---|---|---|
entry |
none | for.cond |
for.cond |
entry, for.body
|
for.body, for.end
|
for.body |
for.cond |
for.cond |
for.end |
for.cond |
none (returns) |
opt -passes=dot-cfg in.ll writes one Graphviz .dot file per function (.sum.dot here), which dot -Tpng turns into a picture. The pass is registered as FUNCTION_PASS("dot-cfg", CFGPrinterPass()).
Sources: llvm/lib/Passes/PassRegistry.def:436
A block with no path from the entry block is unreachable. It is valid IR, but analyses such as the dominator tree treat it specially and most passes skip it. simplifycfg deletes such blocks.
An edge A → B is critical if A has more than one successor and B has more than one predecessor. In the diamond below, the edge entry → join is critical:
flowchart TD
E["entry: br %c, %then, %join"] --> T["then"]
E -->|critical| J["join"]
T --> J
There is nowhere to put code that should run only on that edge: putting it at the end of entry also runs it on the way to then, and putting it at the start of join also runs it when coming from then. Passes that need to insert code on edges, such as PHI elimination or partial redundancy elimination, split the edge by inserting a new empty block between A and B. isCriticalEdge(TI, SuccNum) tests an edge, and SplitCriticalEdge in BasicBlockUtils splits it.
Sources: llvm/lib/Analysis/CFG.cpp:106-112
A back edge is an edge whose target dominates its source (the target is always reached before the source). Each back edge defines a natural loop: the target is the loop header, and the loop body is every block that can reach the back edge's source without going through the header.
| Part | Definition | In @sum
|
|---|---|---|
| Header | The single entry block of the loop; dominates every block in it | for.cond |
| Latch | A block with a back edge to the header | for.body |
| Preheader | The single block outside the loop that branches to the header, and only to it | entry |
| Exiting block | A loop block with a successor outside the loop | for.cond |
| Exit block | A block outside the loop reached from an exiting block | for.end |
Loops nest: an inner loop's blocks are a subset of the outer loop's. LoopInfo builds a forest of Loop objects, each with its blocks and its sub-loops. The accessors are on LoopBase: getHeader() returns the first block, getLoopPreheader() and getLoopLatch() return null if there is no unique one.
Many loop passes need a preheader (a place to hoist code into) and a single latch. The loop-simplify pass creates them, which is why it runs before licm and other loop passes.
Sources: llvm/include/llvm/Support/GenericLoopInfo.h:59, llvm/include/llvm/Support/GenericLoopInfo.h:105, llvm/include/llvm/Support/GenericLoopInfo.h:310-320, llvm/include/llvm/Analysis/LoopInfo.h:40, llvm/include/llvm/Analysis/LoopInfo.h:433
opt -disable-output -passes='print<loops>' sum.ll prints the loop forest. For @sum the output has this shape (illustrative):
Loop info for function 'sum':
Loop at depth 1 containing: %for.cond<header><exiting>,%for.body<latch>
The printer is LoopPrinterPass, registered as print<loops>; the analysis it prints is LoopAnalysis.
Sources: llvm/include/llvm/Analysis/LoopInfo.h:594-605, llvm/lib/Passes/PassRegistry.def:526
- The CFG is implicit: successors come from terminators, predecessors from use lists.
- A critical edge goes from a multi-successor block to a multi-predecessor block; split it to insert code on it.
- A natural loop has one header;
loop-simplifygives it a preheader and a single latch.
- 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