Repository navigation
IR 07 control flow
Relevant source files
The following files were used as context for generating this wiki page:
Inside a basic block, instructions run top to bottom. Between blocks, control moves only through the terminator at the end of each block. A terminator either jumps to other blocks (br, switch), leaves the function (ret), or states that control can never reach that point (unreachable). call is not a terminator: execution comes back to the next instruction after the call.
This page covers ret, unconditional and conditional br, switch, unreachable and call, and gives a short introduction to invoke and exceptions. How terminators form a graph is on CFG and Loops.
Instruction.def lists the terminators first, in lines 126-139:
| Opcode (text) | C++ class | Successors | Purpose |
|---|---|---|---|
ret |
ReturnInst |
none | Return from the function |
br label %d |
UncondBrInst |
1 | Unconditional jump |
br i1 %c, label %t, label %f |
CondBrInst |
2 | Two-way conditional jump |
switch |
SwitchInst |
many | Multi-way jump on an integer |
indirectbr |
IndirectBrInst |
many | Jump to a computed block address |
invoke |
InvokeInst |
2 | Call that may throw |
resume, cleanupret, catchret, catchswitch
|
... | Exception handling | |
unreachable |
UnreachableInst |
none | Control never gets here |
callbr |
CallBrInst |
many | asm goto |
Version note. Older LLVM releases, and most tutorials, use a single
BranchInstclass for both kinds ofbr. In this checkout it is split intoUncondBrInstandCondBrInst. The text syntax is unchanged: the parser readsbrand creates one class or the other depending on whether a condition is present.
Sources: llvm/include/llvm/IR/Instruction.def:126-139, llvm/lib/AsmParser/LLParser.cpp:8050-8071
ret i32 %v ; illustrative: return a value
ret void ; return from a void functionThe type must match the function's return type. A function may contain several ret instructions, one in each exit block.
Sources: llvm/include/llvm/IR/Instructions.h:3065
; illustrative: int abs(int x) { if (x < 0) x = -x; return x; }
define i32 @abs(i32 %x) {
entry:
%neg = icmp slt i32 %x, 0
br i1 %neg, label %then, label %done ; conditional: CondBrInst
then:
%nx = sub nsw i32 0, %x
br label %done ; unconditional: UncondBrInst
done:
%r = phi i32 [ %nx, %then ], [ %x, %entry ]
ret i32 %r
}- The condition of a conditional
brmust be ani1, usually fromicmporfcmp. - Targets are written
label %name. A label is aBasicBlockvalue used as an operand. - If the condition is poison, the behaviour is undefined (see Arithmetic).
- The
phiindonechooses%xor%nxdepending on which block came before; this is explained on SSA and Phi.
Sources: llvm/include/llvm/IR/Instructions.h:3151, llvm/include/llvm/IR/Instructions.h:3217
; illustrative: switch (op) { case 0: ...; case 1: ...; default: ... }
switch i32 %op, label %default [
i32 0, label %case0
i32 1, label %case1
]A switch names a default target, then a list of constant values and their targets. The back end lowers it to a jump table, a binary search of compares, or a bit test, whichever is cheaper. simplifycfg may turn a short chain of icmp/br into a switch, or the reverse.
Sources: llvm/include/llvm/IR/Instructions.h:3296
unreachable says that execution can never get here. Clang emits it after a call to a noreturn function such as abort(), and at the end of a non-void function that falls off its end. Optimizers treat reaching it as undefined behaviour, so they may delete any code path that must lead to it.
call void @abort() ; illustrative
unreachableSources: llvm/include/llvm/IR/Instructions.h:4662
; illustrative
%r = call i32 @add(i32 %a, i32 %b)
call void @free(ptr %p)
%r2 = tail call i32 %fnptr(i32 1) ; indirect call through a pointer
%m = call i32 @llvm.smax.i32(i32 %a, i32 %b) ; an intrinsic- The callee is a
ptr: either a function name (direct call) or any pointer value (indirect call). - The function type is written on the call, so with opaque pointers the call itself states the parameter types.
-
tailis a hint that the call can reuse the caller's stack frame;musttailmakes that required. - Functions whose names start with
llvm.are intrinsics: built-in operations such asllvm.memcpy,llvm.smaxorllvm.dbg.valuethat passes and back ends understand directly.
How a call becomes argument registers and a branch-and-link instruction is covered by the Calling Conventions wiki.
Sources: llvm/include/llvm/IR/Instructions.h:1597, llvm/include/llvm/IR/Instruction.def:211
In C++, a call that may throw must say where to go if it does. invoke is a call that is also a terminator with two successors:
; illustrative
%r = invoke i32 @may_throw()
to label %ok unwind label %lpad
ok:
ret i32 %r
lpad:
%ex = landingpad { ptr, i32 } cleanup
; run destructors, then:
resume { ptr, i32 } %ex
}On a normal return control goes to %ok. If an exception is thrown it goes to %lpad, whose first instruction must be a landingpad. A plain call inside a function compiled with exceptions enabled is allowed only if the callee is nounwind, or if an exception may simply propagate out of the caller.
- Every block ends in exactly one terminator, and only terminators move control between blocks.
- In this checkout
bris two classes,UncondBrInstandCondBrInst; the text form is stillbr. -
callreturns to the next instruction;invokeis a call that is also a terminator.
- 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