Repository navigation
Register Allocation 06.3 regalloc greedy
Relevant source files
The following files were used as context for generating this wiki page:
This page covers Greedy's priority function, its stages, the decision order inside selectOrSplitImpl, eviction, the splitting strategies at a high level, and the extra steps (callee-saved cost, last-chance recoloring, hint recoloring). The mechanics of splitting and spilling are on Spilling and Splitting.
Allocate big, important intervals first. If an interval does not fit, try to push aside something cheaper. If that fails, wait until everything smaller has been placed, then look at the gaps that remain and cut the interval so each piece fits a gap. Pieces that still do not fit are spilled. Because evicted and split intervals are put back in the queue, the allocator keeps refining its answer, and the stage system stops it from looping forever.
Every interval carries a stage, stored in Greedy's ExtraInfo:
enum LiveRangeStage {
/// Newly created live range that has never been queued.
RS_New,
/// Only attempt assignment and eviction. Then requeue as RS_Split.
RS_Assign,
/// Attempt live range splitting if assignment is impossible.
RS_Split,
/// Attempt more aggressive live range splitting that is guaranteed to make
/// progress. This is used for split products that may not be making
/// progress.
RS_Split2,
/// Live range will be spilled. No more splitting will be attempted.
RS_Spill,
/// There is nothing more we can do to this live range. Abort compilation
/// if it can't be assigned.
RS_Done
};stateDiagram-v2
[*] --> RS_New
RS_New --> RS_Assign: first enqueue
RS_Assign --> assigned: free or evicted a register
RS_Assign --> RS_Split: no luck, requeued
RS_Split --> pieces: split succeeded
RS_Split --> RS_Spill: splitting gave nothing
pieces --> RS_Assign: new pieces
pieces --> RS_Split2: piece did not make progress
RS_Split2 --> RS_Spill
RS_Spill --> RS_Done: spilled; reload intervals are RS_Done
RS_Done --> assigned
Stages only move forward, which guarantees termination: an interval can be split only a limited number of times before it is spilled, and the tiny intervals around reloads (RS_Done) are never spilled again. The splitter itself sets stages on the pieces it creates: pieces that would not benefit from further splitting are marked RS_Spill, and pieces that are no smaller than the original (no progress) are marked RS_Split2, which forces the next split to make progress.
Sources: llvm/include/llvm/CodeGen/RegAllocEvictionAdvisor.h:50-72
Greedy's queue is ordered by an unsigned priority from DefaultPriorityAdvisor::getPriority. The bit layout is spelled out in the source:
// Priority bit layout:
// 31 RS_Assign priority
// 30 Preference priority
// if (RegClassPriorityTrumpsGlobalness)
// 29-25 AllocPriority
// 24 GlobalBit
// else
// 29 Global bit
// 28-24 AllocPriority
// 0-23 Size/Instr distanceIn plain words:
| Bit(s) | Set when | Effect |
|---|---|---|
| 31 | Interval is not in stage RS_Split
|
Fresh intervals come before deferred ones. Deferred (RS_Split) intervals are ordered only by size, after everything else |
| 30 | Interval has a known physical-register preference (a hint) | Hinted intervals go first, so their hint is still free |
| 29 (default) | Interval is global (spans several blocks) or is huge | Global intervals before local ones |
| 28–24 |
AllocationPriority of the register class, from TableGen |
A target can push some classes ahead (for example tuples) |
| 23–0 | Global: the interval's size. Local: its distance from the end of the function | Big global intervals first; local intervals in instruction order |
Local intervals (inside one block) are allocated in instruction order. The source comment explains why: they are singly defined, so allocating them in order "produces optimal coloring in the absence of global interference". A local interval is treated as global if its class sets GlobalPriority or if it is longer than twice the number of allocatable registers (measured in instructions).
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:439-509, llvm/include/llvm/Target/Target.td:360-365
Everything Greedy does for one interval is in selectOrSplitImpl:
flowchart TD
A["dequeue V"] --> B["tryAssign: a free register?"]
B -->|"yes, unused callee-saved"| C["tryAssignCSRFirstTime:<br/>is a CSR worth its save/restore?"]
B -->|"yes"| R["return it"]
B -->|"no"| D{"stage != RS_Split?"}
D -->|"yes"| E["tryEvict: push out cheaper intervals"]
E -->|"success"| R
E -->|"fail"| F{"stage < RS_Split?"}
D -->|"no"| F
F -->|"yes"| G["set RS_Split, requeue<br/>(wait for second round)"]
F -->|"no"| H["trySplit"]
H -->|"split made"| S["return 0, pieces queued"]
H -->|"nothing"| I{"RS_Done or not spillable?"}
I -->|"yes"| J["tryLastChanceRecoloring"]
I -->|"no"| K["spill V, pieces become RS_Done"]
The code, abbreviated:
// First try assigning a free register.
auto Order =
AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
if (MCRegister PhysReg =
tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) {
...
}
...
if (Stage != RS_Split) {
if (MCRegister PhysReg =
tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit,
FixedRegisters)) {
...
return PhysReg;
}
}
...
// The first time we see a live range, don't try to split or spill.
// Wait until the second time, when all smaller ranges have been allocated.
// This gives a better picture of the interference to split around.
if (Stage < RS_Split) {
ExtraInfo->setStage(VirtReg, RS_Split);
NewVRegs.push_back(VirtReg.reg());
return MCRegister();
}
if (Stage < RS_Spill && !VirtReg.empty()) {
// Try splitting VirtReg or interferences.
...
MCRegister PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters);
if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore))
return PhysReg;
}
if (Stage >= RS_Done || !VirtReg.isSpillable()) {
return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
RecolorStack, Depth);
}
// Finally spill VirtReg itself.
LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
spiller().spill(LRE, &Order);
ExtraInfo->setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);The "wait for second round" step is the clever part. An interval that cannot get a register on its first visit is not split straight away. It goes to the back of the queue (bit 31 cleared), so by the time it comes back, every other interval has been placed and the allocator can see exactly where the gaps are.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:2655-2755
tryAssign walks the allocation order and stops at the first free register. A free hint is returned immediately. A free non-hint register is kept, but Greedy then checks whether it can do better:
- If the interval has a simple hint (a copy to a physical register) that was not free, try to evict whatever sits in the hint cheaply (
canEvictHintInterference), or split around the hint in cold blocks (trySplitAroundHintReg). Otherwise record it as a broken hint for later repair. - If the free register has a non-zero
CostPerUse(TableGen field on registers), try evicting something from a cheaper register.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:532-584
tryEvict asks the eviction advisor for the best physical register to take over:
MCRegister BestPhys = EvictAdvisor->tryFindEvictionCandidate(
VirtReg, Order, CostPerUseLimit, FixedRegisters);
if (BestPhys.isValid())
evictInterference(VirtReg, BestPhys, NewVRegs);
return BestPhys;For each candidate register the default advisor (DefaultEvictionAdvisor) checks every interfering interval and computes an EvictionCost (number of broken hints, then the largest spill weight to be evicted). It picks the candidate with the lowest cost, and only if evicting is worth it: the evicted intervals must be cheaper than the current one (shouldEvict, canEvictInterferenceBasedOnCost).
evictInterference unassigns every interfering interval from the LiveRegMatrix and pushes it back into the queue. Evicted intervals get another chance: they may find a different free register, or be split.
Cascade numbers stop eviction from going round in circles. When an interval evicts others, it is given a cascade number (a new, larger one if it has none) and that number is stamped on every interval it evicts. The advisor then refuses to evict anything with the same or a newer cascade number; in the words of the source, "Only evict older cascades or live ranges without a cascade." So A cannot evict B, which evicts A, forever.
The advisor is pluggable (RegAllocEvictionAdvisorAnalysis): LLVM also has an ML-trained eviction advisor, which is why Register Allocation Pass Scoring appears in the pass list.
A related constant, Hysteresis = 2007 / 2048.0f (about 0.98), is used when comparing floating-point weights, for example in local splitting's gap comparison, so tiny differences do not flip decisions.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:617-727, llvm/lib/CodeGen/RegAllocEvictionAdvisor.cpp:211-338, llvm/include/llvm/CodeGen/RegAllocEvictionAdvisor.h:76-80, llvm/lib/CodeGen/RegAllocGreedy.cpp:329-331, llvm/lib/CodeGen/RegAllocGreedy.cpp:1891-1896
trySplit chooses a strategy by the shape of the interval:
// Local intervals are handled separately.
if (LIS->intervalIsInOneMBB(VirtReg)) {
...
MCRegister PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
if (PhysReg || !NewVRegs.empty())
return PhysReg;
return tryInstructionSplit(VirtReg, Order, NewVRegs);
}
...
// First try to split around a region spanning multiple blocks. RS_Split2
// ranges already made dubious progress with region splitting, so they go
// straight to single block splitting.
if (ExtraInfo->getStage(VirtReg) < RS_Split2) {
MCRegister PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
if (PhysReg || !NewVRegs.empty())
return PhysReg;
}
// Then isolate blocks.
return tryBlockSplit(VirtReg, Order, NewVRegs);| Strategy | Interval shape | Idea |
|---|---|---|
Region split (tryRegionSplit) |
Spans many blocks | For each candidate physical register, find the set of blocks where it is free, using SpillPlacement (a min-cost flow over edge bundles, weighted by block frequency) to decide where the value should be in a register and where in memory. Split so one piece lives in that register over that region |
Block split (tryBlockSplit) |
Spans many blocks | Give each block that uses the value its own small interval, connected by copies |
Local split (tryLocalSplit) |
Inside one block | Find a gap between uses where a register is free and cut the interval there (calcGapWeights) |
Instruction split (tryInstructionSplit) |
Inside one block, or a register that needs a smaller class at some uses | One tiny interval per use, so each can be constrained individually |
A split creates new virtual registers joined by COPYs at the cut points. The pieces are queued, each gets its own register (or is spilled), and copies between pieces that end up in the same register are later removed by the rewriter. The machinery (SplitAnalysis, SplitEditor) is on Live Range Splitting.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:1975-2010, llvm/lib/CodeGen/RegAllocGreedy.cpp:1206-1513, llvm/lib/CodeGen/RegAllocGreedy.cpp:1591-1744
Using a callee-saved register for the first time costs a store in the prologue and a load in the epilogue. If tryAssign picks a callee-saved register that nothing has used yet, tryAssignCSRFirstTime compares that cost (CSRCost, from TargetRegisterInfo::getCSRFirstUseCost, scaled by entry frequency) against splitting or spilling the interval instead. On a hot function it is worth it; on a function where the value is only live across a rarely executed call, splitting may be cheaper. Targets tune this through getCSRFirstUseCost.
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:2384-2470, llvm/include/llvm/CodeGen/TargetRegisterInfo.h:869
If an interval cannot be spilled (RS_Done, or marked unspillable) and still has no register, tryLastChanceRecoloring tries a small search: temporarily assign the interval to a register, unassign the intervals in the way, and try to recolor those recursively. It is limited in depth and in the number of interferences (-lcr-max-depth, -lcr-max-interf) because it is exponential. If it fails, the base class reports "ran out of registers".
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:2045-2328
RAGreedy::run does a few things after allocatePhysRegs:
| Step | What it does |
|---|---|
tryHintsRecoloring |
For each interval whose copy hint was broken, try to swap registers within its copy-related group so more copies become identity copies |
postOptimization |
Spiller hoists and merges spills (HoistSpillHelper::hoistAllSpills); dead rematerialised definitions are deleted |
reportStats |
Emits the regalloc optimisation remark with the number of spills, reloads and copies |
Example of the remark, from the 24-load test (-pass-remarks-missed=regalloc):
remark: <unknown>:0:0: 13 spills 1.300000e+01 total spills cost 13
reloads 1.300000e+01 total reloads cost generated in function
Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:2534-2654, llvm/lib/CodeGen/RegAllocGreedy.cpp:2757-2942
| Hook | Effect on Greedy |
|---|---|
AllocationPriority, GlobalPriority (TableGen class fields) |
Queue order |
TRI::regClassPriorityTrumpsGlobalness |
Swap bits 29 and 24–28 of the priority |
TRI::reverseLocalAssignment |
Allocate local intervals bottom-up instead |
TRI::getRegAllocationHints |
Preferred registers, tried first |
TRI::getCSRFirstUseCost |
When to use a fresh callee-saved register |
TRI::shouldRegionSplitForVirtReg |
Skip expensive region splitting for some registers |
CostPerUse (TableGen register field) |
Prefer cheap registers (e.g. ones with short encodings) |
TII::isReMaterializableImpl, reMaterialize
|
Cheaper "spilling" by recomputing |
TII::storeRegToStackSlot, loadRegFromStackSlot, foldMemoryOperandImpl
|
How spills are actually written |
See Writing Register Allocation Support for a Custom Backend for each one.
| Option | Effect |
|---|---|
-regalloc=greedy |
Force Greedy (e.g. at -O0, which also switches to the optimised pipeline) |
-split-spill-mode=default|size|speed |
How split pieces are spilled |
-lcr-max-depth=N, -lcr-max-interf=N
|
Limits for last-chance recoloring |
-exhaustive-register-search |
Remove recoloring limits (slow; for experiments) |
-greedy-reverse-local-assignment |
Allocate local intervals bottom-up |
-greedy-regclass-priority-trumps-globalness |
Use the alternative priority bit layout |
-regalloc-csr-first-time-cost=N |
Override the cost of using a callee-saved register for the first time |
-pass-remarks-missed=regalloc |
Report spills and reloads per function and loop |
- 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