Skip to content

Register Allocation 04.2 coalescer

Mugundan edited this page Nov 27, 2026 · 1 revision

Register Coalescer

Relevant source files

The following files were used as context for generating this wiki page:

The register coalescer removes `COPY` instructions by merging ("joining") the source and destination registers into one register. After a successful join, the copy becomes an identity copy and is deleted. It is the pass that cleans up after [PHI elimination and two-address lowering](#phi-two-address).

Purpose and Scope

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.

The Basic Rule

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:

  1. every operand that names %b is rewritten to %a (or the other way round);
  2. the two live intervals are merged into one, and their value numbers combined;
  3. the register class becomes the common sub-class of the two (for example gpr64all and gpr64sp join to gpr64common in the loop example);
  4. 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.

Order of Work

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"]
Loading

In detail, joinAllIntervals:

  1. sorts the blocks by loop depth (MBBPriorityInfo, using MachineLoopInfo::getLoopDepth), so copies in deeper loops are tried first. Removing a copy that runs a million times matters more than one that runs once;
  2. in each block, collects the copy-like instructions top-down, so that coalescing and rematerialisation propagate forward;
  3. 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;
  4. moves copies that match the terminal rule (-terminal-rule) to the end of the list, so they do not block better joins;
  5. finally re-runs copyCoalesceWorkList on 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

Copies Involving Physical Registers

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 $x0 for %4, and if it gets it, the rewriter deletes the copy. This is what happened to every COPY $wN in the examples.
  • Copies involving reserved or constant registers ($wzr, $xzr) are handled by joinReservedPhysReg, 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.

Rematerialisation Instead of a Copy

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

Other Tricks

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

Sub-register Copies

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.

Why Joining Can Hurt

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:

  1. it does not join with non-reserved physical registers (it hints instead);
  2. a target can veto joins with TargetRegisterInfo::shouldCoalesce;
  3. 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.

Target Hook: shouldCoalesce

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 NewRC is 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

Useful Options

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)

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally