Skip to content

Register Allocation 06.3 regalloc greedy

Mugundan edited this page Nov 27, 2026 · 1 revision

Greedy Register Allocator

Relevant source files

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

Greedy is LLVM's default allocator whenever optimisation is on. It uses the same priority-queue loop as [Basic](#regalloc-basic), but when a register is not free it has more options than spilling: it can **evict** a less important interval (which goes back in the queue), **split** the interval into pieces that each fit somewhere, and only as a last resort **spill**. Each interval moves through a fixed sequence of *stages* so the process always terminates.

Purpose and Scope

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.

The Main Idea in One Paragraph

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.

Stages

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
Loading

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

Priority

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 distance

In 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

The Decision Order

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

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

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:

  1. 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.
  2. 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

Eviction

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

Splitting Strategies

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

Callee-saved Registers

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

Last-chance Recoloring

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

After the Loop

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

Target Hooks Greedy Consults

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.

Useful Options

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

Sources: llvm/lib/CodeGen/RegAllocGreedy.cpp:86-145

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