Repository navigation
Register Allocation 04.2 coalescer
Relevant source files
The following files were used as context for generating this wiki page:
This page explains when two registers can be joined, the order the coalescer works in, the special cases (physical registers, rematerialisation, sub-registers), and the hook a target can use to veto a join.
Given
%b = COPY %a
%a and %b can be merged if their live intervals do not interfere, where "interfere" means live at the same point with different values. Right after the copy both are live, but they hold the same value, so that overlap does not count. This is why value numbers (see Liveness) are essential: the coalescer compares value numbers, not just segments.
If the join succeeds:
- every operand that names
%bis rewritten to%a(or the other way round); - the two live intervals are merged into one, and their value numbers combined;
- the register class becomes the common sub-class of the two (for example
gpr64allandgpr64spjoin togpr64commonin the loop example); - the copy, now
%a = COPY %a, is erased.
If the two classes have no common sub-class, or the merged interval would have conflicting values somewhere, the join fails and the copy stays.
flowchart TD
A["RegisterCoalescer::run"] --> B["joinAllIntervals"]
B --> C["copyCoalesceInMBB for each block<br/>blocks ordered by loop depth, deepest first"]
C --> D["copyCoalesceWorkList"]
D --> E["joinCopy(copy)"]
E --> F{"Kind of copy"}
F -->|"vreg = COPY vreg"| G["joinIntervals: compare value numbers,<br/>resolve conflicts, merge"]
F -->|"vreg = COPY physreg<br/>or physreg = COPY vreg"| H["joinReservedPhysReg or<br/>physreg join (strict rules)"]
F -->|"source def is cheap"| I["reMaterializeDef:<br/>duplicate the def instead"]
E --> J["failed copies retried<br/>after other joins"]
In detail, joinAllIntervals:
- sorts the blocks by loop depth (
MBBPriorityInfo, usingMachineLoopInfo::getLoopDepth), so copies in deeper loops are tried first. Removing a copy that runs a million times matters more than one that runs once; - in each block, collects the copy-like instructions top-down, so that coalescing and rematerialisation propagate forward;
- keeps copies whose registers live only in one block (local copies) on a separate
LocalWorkList, joined when the walk moves to a shallower loop depth; - moves copies that match the terminal rule (
-terminal-rule) to the end of the list, so they do not block better joins; - finally re-runs
copyCoalesceWorkListon everything that failed, in a loop, until no more copies join. A later join can make an earlier one possible.
// Joining intervals can allow other intervals to be joined. Iteratively join
// until we make no progress.
while (copyCoalesceWorkList(WorkList))
/* empty */;Sources: llvm/lib/CodeGen/RegisterCoalescer.cpp:4196-4290, llvm/lib/CodeGen/RegisterCoalescer.cpp:4103, llvm/lib/CodeGen/RegisterCoalescer.cpp:2053
Joining a virtual register with a physical register (for example %4:gpr64common = COPY $x0) would pin the virtual register to that physical register for its whole life, before the allocator has seen anything. That is usually a bad idea, so the coalescer is very conservative:
- Copies to and from non-reserved physical registers are generally left alone. Instead, the copy becomes a hint: the allocator later prefers
$x0for%4, and if it gets it, the rewriter deletes the copy. This is what happened to everyCOPY $wNin the examples. - Copies involving reserved or constant registers (
$wzr,$xzr) are handled byjoinReservedPhysReg, under strict conditions.
That is why the coalesced loop still contains %15 = COPY $xzr and $w0 = COPY %16: they are not failures, they are hints waiting for the allocator.
If the source of a copy is defined by a cheap instruction with no inputs that might change (a constant move, for example), it can be cheaper to recompute the value directly into the destination than to keep both registers alive:
%a = MOVi32imm 42
... ; many instructions
%b = COPY %a
becomes
%a = MOVi32imm 42
...
%b = MOVi32imm 42
and %a may then die early. This is RegisterCoalescer::reMaterializeDef. It relies on the target marking such instructions rematerialisable (isReMaterializable = 1 in TableGen, and TargetInstrInfo::isReMaterializableImpl / reMaterialize; see TargetInstrInfo Hooks).
Sources: llvm/lib/CodeGen/RegisterCoalescer.cpp:1297
| Function | What it does |
|---|---|
adjustCopiesBackFrom |
When a value is copied back to where it came from (%b = COPY %a ... %a = COPY %b), extend %a's range so the second copy becomes an identity copy |
removeCopyByCommutingDef |
If commuting the instruction that defines the copy's source makes the copy redundant, commute it |
Sources: llvm/lib/CodeGen/RegisterCoalescer.cpp:628
A copy can read or write part of a register:
%13:gpr32 = COPY killed %12.sub_32
Joining %13 into %12 means rewriting every use of %13 as %12.sub_32. The coalescer does this when a register class exists that supports the sub-register index (TableGen generates getMatchingSuperRegClass for this). In the loop example that is exactly what produced SUBSWrr %15.sub_32, %5 after coalescing. With sub-register liveness enabled, these joins are done per lane, which allows more of them.
Merging makes one long live range out of two short ones. A long range interferes with more things and is harder to allocate. In extreme cases, aggressive coalescing turns a function that allocates without spills into one that spills. LLVM limits the damage in three ways:
- it does not join with non-reserved physical registers (it hints instead);
- a target can veto joins with
TargetRegisterInfo::shouldCoalesce; - Greedy can split a joined range again if it does not fit (see Live Range Splitting). Coalescing first and splitting later is the overall design.
virtual bool shouldCoalesce(MachineInstr *MI,
const TargetRegisterClass *SrcRC,
unsigned SubReg,
const TargetRegisterClass *DstRC,
unsigned DstSubReg,
const TargetRegisterClass *NewRC,
LiveIntervals &LIS) const;joinCopy calls this before joining two virtual registers (RegisterCoalescer.cpp:2079). SrcRC and DstRC are the classes of the two registers, and NewRC is the class the merged register would have. Returning false keeps the copy. Typical reasons a target overrides it:
- the merged class
NewRCis much smaller than the original classes (e.g. joining would force a value into a tiny class of registers that support some special instruction); - the merged register would be a very wide tuple of registers, which is hard to allocate.
The default returns true. Most targets never override it.
Sources: llvm/include/llvm/CodeGen/TargetRegisterInfo.h:1038-1046, llvm/lib/CodeGen/RegisterCoalescer.cpp:2079, llvm/lib/CodeGen/RegisterCoalescer.cpp:78
| Option | Effect |
|---|---|
-join-liveintervals=false |
Disable coalescing entirely; useful to check whether a problem comes from the coalescer |
-stop-before=register-coalescer, -stop-after=register-coalescer
|
Snapshot MIR on either side of the pass |
-run-pass=register-coalescer |
Run only this pass on a .mir file (write a test for a coalescing bug this way) |
- 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