Repository navigation
Register Allocation 07.2 inline spiller
Relevant source files
The following files were used as context for generating this wiki page:
This page follows InlineSpiller::spill from start to finish and lists the target hooks it calls. The Fast allocator has its own, much simpler spilling (see Fast Register Allocator).
void InlineSpiller::spill(LiveRangeEdit &edit, AllocationOrder *order) {
++NumSpilledRanges;
Edit = &edit;
Order = order;
...
// Share a stack slot among all descendants of Original.
Original = VRM.getOriginal(edit.getReg());
StackSlot = VRM.getStackSlot(Original);
StackInt = nullptr;
...
collectRegsToSpill();
reMaterializeAll();
// Remat may handle everything.
if (!RegsToSpill.empty())
spillAll();
Edit->calculateRegClassAndHint(MF, VRAI);
}flowchart TD
A["spill(LRE)"] --> B["find Original register;<br/>reuse its stack slot if any"]
B --> C["collectRegsToSpill<br/>the register plus its split 'snippets'"]
C --> D["reMaterializeAll<br/>recompute values where possible"]
D -->|"nothing left"| H["calculateRegClassAndHint"]
D -->|"registers left"| E["spillAll"]
E --> F["assign stack slot; merge into LiveStacks"]
F --> G["spillAroundUses for each register:<br/>fold, or reload before use / store after def"]
G --> H
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:1460-1486
When Greedy splits %v into pieces and several pieces are later spilled, they all hold the same original value. VRM.getOriginal(Reg) finds the register they were split from, and the spiller reuses its slot (VRM.getStackSlot(Original)). All pieces therefore share one slot, and a value stored by one piece can be reloaded by another without extra copies.
collectRegsToSpill starts with the register being spilled and adds snippets: tiny sibling intervals (split from the same original) that are connected to it only by copies (isSnippet). Spilling them together lets the spiller delete those copies (SnippetCopies) instead of turning them into store/load pairs.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:326, llvm/lib/CodeGen/InlineSpiller.cpp:389
reMaterializeAll visits each use of the registers to spill and calls reMaterializeFor. If the value used there was defined by an instruction the target marks rematerialisable, and its operands are still available at the use (LiveRangeEdit::canRematerializeAt), a copy of the defining instruction is inserted right before the use (LiveRangeEdit::rematerializeAt, which calls TargetInstrInfo::reMaterialize) into a new small register. The original definition may become dead; dead definitions are deleted later (DeadRemats, removed in RegAllocBase::postOptimization).
If every use was rematerialised, RegsToSpill ends up empty and no stack slot is created at all. This is why constants never appear as spills.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:674, llvm/lib/CodeGen/InlineSpiller.cpp:834, llvm/lib/CodeGen/LiveRangeEdit.cpp:71-84, llvm/include/llvm/CodeGen/TargetInstrInfo.h:493
// Update LiveStacks now that we are committed to spilling.
if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
StackSlot = VRM.assignVirt2StackSlot(Original);
StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
...
}
...
for (Register Reg : RegsToSpill)
StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
StackInt->getValNumInfo(0));
...
// Spill around uses of all RegsToSpill.
for (Register Reg : RegsToSpill) {
spillAroundUses(Reg);
...
}The stack slot gets its own live interval in LiveStacks. That is what Stack Slot Coloring uses later to let non-overlapping slots share memory. After spillAroundUses, the snippet copies and the spilled registers themselves are deleted.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:1411-1458
For each instruction that uses or defines the register, in this order:
| Check | Action |
|---|---|
DBG_VALUE |
Rewrite it to point at the stack slot; debug info never affects codegen |
| Snippet copy | Skip; it will be deleted |
coalesceStackAccess |
The instruction is already a load or store of the same slot: delete it |
| Copy from a sibling, writing the register |
hoistSpillInsideBB: store the sibling earlier instead, and mark this copy dead |
| Copy from a sibling, reading |
eliminateRedundantSpills: stores downstream of it are not needed |
foldMemoryOperand(Ops) |
Ask the target to fold the slot into the instruction. On success no new register is needed |
| Otherwise | Create a new register NewVReg = Edit->createFrom(Reg); if the instruction reads, insertReload before it; rewrite the operands to NewVReg; if it writes, insertSpill after it |
// Attempt to fold memory ops.
if (foldMemoryOperand(Ops))
continue;
// Create a new virtual register for spill/fill.
Register NewVReg = Edit->createFrom(Reg);
if (RI.Reads)
insertReload(NewVReg, Idx, &MI);
...
if (RI.Writes)
if (hasLiveDef)
insertSpill(NewVReg, true, &MI);Each NewVReg lives from its reload to the instruction, or from the instruction to its store: one instruction long. These are the tiny, unspillable intervals the allocator then queues as RS_Done.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:1315-1408
Both are thin wrappers around the target:
TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
MRI.getRegClass(NewVReg), Register());
LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI); if (IsRealSpill)
TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, isKill, StackSlot,
MRI.getRegClass(NewVReg), Register());
else
// Don't spill undef value.
...
BuildMI(MBB, SpillBefore, MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
.addReg(NewVReg, getKillRegState(isKill));Note the details a target must get right:
- The hooks are called with a virtual register. The instruction you build must accept a virtual register of that class.
- You may emit more than one instruction. The spiller uses a
MachineInstrSpanand gives every new instruction a slot index. (A single-instruction store is also recorded as mergeable for spill hoisting.) - Storing an
IMPLICIT_DEF(an undefined value) is skipped; aKILLis emitted instead.
On AArch64, storeRegToStackSlot for a 32-bit GPR produces the STRWui ... %stack.N, 0 seen in the spill example, and loadRegFromStackSlot produces LDRWui.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:1247-1312, llvm/include/llvm/CodeGen/TargetInstrInfo.h:1199-1219
When allocation finishes, RegAllocBase::postOptimization calls the spiller's postOptimization, which runs HoistSpillHelper::hoistAllSpills. Different pieces of the same original value may each have stored to the shared slot. The helper looks for stores of the same value that can be merged into one, placed at a point that dominates them and runs less often, and removes the rest.
Sources: llvm/lib/CodeGen/InlineSpiller.cpp:1489, llvm/lib/CodeGen/InlineSpiller.cpp:1812, llvm/lib/CodeGen/RegAllocBase.cpp:157-168
| Hook | Required? | Used for |
|---|---|---|
storeRegToStackSlot |
Yes | Spill store |
loadRegFromStackSlot |
Yes | Reload |
isLoadFromStackSlot, isStoreToStackSlot
|
Strongly recommended | Recognising existing slot accesses (coalesceStackAccess, redundant-spill removal, stack slot coloring) |
isReMaterializableImpl (or TableGen isReMaterializable = 1), reMaterialize
|
Recommended | Rematerialisation |
foldMemoryOperandImpl |
Optional | Folding the slot into instructions |
isCopyInstrImpl |
Optional | Recognising target moves as copies (for sibling copies and snippets) |
See TargetInstrInfo Hooks for how to write each one.
- 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