Register Allocation: Fitting into a Few Slots

An IR has unlimited variables, a CPU has a few dozen registers. Register allocation closes that gap.

Codegen2 min read
Codegen

In an IR we can use as many virtual registers as we like. A real CPU has a fixed number; x86-64 has 16 general-purpose registers. Register allocation maps virtual registers onto those few physical ones.

The Interference Graph

Two values that are live at the same time cannot share a register. This is drawn as a graph: each value is a node, and values live at the same time are connected by an edge.

IRIR
%a = load i32, %p ; a live%b = load i32, %q ; a and b live%c = add i32 %a, %b ; a and b die, c live%d = mul i32 %c, 2 ; c dies, d liveret i32 %d

Here a and b interfere, but c and a do not, so c can reuse the register of a. Two registers are enough for this function.

When Colors Run Out

If the graph cannot be colored with as many colors as there are registers, some values are moved to memory. This is called a spill. Which value gets spilled matters: pushing a value that is used often inside a loop out to memory slows the program noticeably.

Between Fast and Good

  • Graph coloring gives good results but can get slow on large functions.
  • Linear scan is faster and is a common choice in just-in-time compilers.
  • LLVM, for example, uses its Fast allocator for debug builds and the more thorough Greedy allocator by default.

Function calls affect allocation too: the calling convention says which registers survive a call and which may be clobbered.

Sources

  1. G. J. Chaitin. “Register allocation & spilling via graph coloring.” ACM SIGPLAN Notices 17(6), 1982, 98–101. doi:10.1145/872726.806984
  2. M. Poletto, V. Sarkar. “Linear scan register allocation.” ACM TOPLAS 21(5), 1999, 895–913. doi:10.1145/330249.330250
  3. The LLVM Target-Independent Code Generator, “Built in register allocators”. llvm.org/docs/CodeGenerator
  4. System V Application Binary Interface, AMD64 Architecture Processor Supplement. gitlab.com/x86-psABIs