目录
正在加载目录…
正在阅读专栏 Essentials of Compilation 专栏 第 4 篇 · 共 13 篇 · 31%

Essentials of Compilation:Register Allocation

发布于 2026-09-16 22:16 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 17,155 · 预计阅读 35 分钟 👁 10 次阅读

Essentials of Compilation:Register Allocation

本章把前一章暂时放在 stack 上的 variable 尽可能分配到 registers,并用 liveness analysis、interference graph 和 graph coloring 实现 register allocation。

TL;DR

  • Stack access 可能需要几十到几百个 CPU cycles,而 register access 通常只需一个 cycle;register allocation 的目标是把尽可能多的 variable 放进 registers。
  • 两个 variable 只要不会在同一时刻处于 live 状态,就可以共享同一个 register。
  • uncover_live 从 instruction sequence 的末尾向前计算 live-before / live-after set。
  • Interference graph 用 vertex 表示 location,用 edge 表示两个 location 同时 live,因而不能放入同一个 register。
  • Graph coloring 把颜色映射为 registers;颜色不足时,无法着色的 variable 会被 spill 到 stack。

名词解释

名词含义本章对应物
live某个 location 的当前 value 会在之后被使用L_before(k)、L_after(k)
call-live在 function call 期间仍处于 live 的 variable需要避开 caller-saved register
interfere两个 location 同时 live,不能共享 registerinterference graph 的 edge
spill把 variable 分配到 stack locationregister 不足时的 fallback
caller-savedcallee 可以覆盖的 registerrax rcx rdx rsi rdi r8-r11
callee-savedcallee 返回前必须恢复的 registerrsp rbp rbx r12-r15

目录

章节说明
Register Allocation从 stack allocation 改进到 register allocation
Registers and Calling ConventionsSystem V calling convention 与 call-live variable
Liveness Analysis从后向前计算 live set
Build the Interference Graph从 live set 建立 interference graph
Graph Coloring via Sudoku把 register allocation 建模为 graph coloring

Register Allocation

前一章把 LangVar 编译到 x86,并把 variable 存在 procedure call stack 上。CPU 访问 stack location 可能需要 10 到 100 个 cycles,而访问 register 通常只需一个 cycle。本章通过把部分 variable 存入 registers 来提高 generated code 的效率。

Register allocation 的目标是尽可能多地把 variable 放入 registers。某些 program 的 variable 数量多于 register 数量,因此不能总是把每个 variable 映射到不同 register。幸运的是,不同 variable 通常在 program execution 的不同时间段内使用;这种情况下,多个 variable 可以映射到同一个 register。

考虑下面这个 running example:

racket
(let ([v 1])
  (let ([w 42])
    (let ([x (+ v 7)])
      (let ([y x])
        (let ([z (+ x w)])
          (+ z (- y)))))))

instruction selection 后,program 几乎已经是 x86 assembly,但仍然使用 variables:

asm
locals-types:
    x : Integer, y : Integer,
    z : Integer, t : Integer,
    v : Integer, w : Integer
start:
    movq $1, v
    movq $42, w
    movq v, x
    addq $7, x
    movq x, y
    movq x, z
    addq w, z
    movq y, t
    negq t
    movq z, %rax
    addq t, %rax
    jmp conclusion

x 被 move 到 z 后就不再使用;而 z 只在此后使用,因此 x 和 z 可以共享一个 register。

Liveness analysis 用于计算 variable 在哪里处于 in-use 状态。得到这个信息后,我们计算哪些 variable 同时处于 in-use 状态,即哪些 variable 彼此 interfere,再用一个 undirected graph 表示这种关系:vertex 是 variable,edge 表示 interference。最后把 register allocation 建模为 graph coloring 问题。

如果 registers 不足,就像前一章一样把剩余 variable 放到 stack。把 variable 分配到 stack location 通常称为 spill;是否 spill 是 graph coloring 过程的一部分。

本章做一个简化假设:每个 variable 只分配到一个 location(register 或 stack address)。更复杂的方法允许同一个 variable 在 program 的不同区域使用不同 location。例如,一个 variable 在短 instruction sequence 中被频繁使用,之后很久才再次使用;可以在前一段把它放入 register,之后在剩余 lifetime 中移到 stack。

Registers and Calling Conventions

执行 register allocation 时,必须了解 x86 中规定 function call 如何进行的 calling convention。虽然 LangVar 不包含 programmer-defined function,但 generated code 包含 operating system 调用的 main,也包含对 read_int 的调用。

Function call 需要两个可能由不同 programmer 编写、或由不同 compiler 生成的 code 片段协调工作。本书遵循 Linux 和 MacOS 上 GNU C compiler 使用的 System V calling convention。

Calling convention 包含 function 如何共享 registers 的规则。特别是,caller 在 function call 之前负责释放一组供 callee 使用的 registers,这些是 caller-saved registers:

text
rax rcx rdx rsi rdi r8 r9 r10 r11

另一方面,callee 负责保存 callee-saved registers 的 value:

text
rsp rbp rbx r12 r13 r14 r15

可以从 caller 和 callee 两种视角理解这个 convention:

  • Caller 应假设所有 caller-saved registers 都可能被 callee 覆盖为任意 value;但可以安全地假设所有 callee-saved registers 保持原 value。
  • Callee 可以自由使用 caller-saved registers;如果要使用 callee-saved register,则必须在 return caller 前把原 value 放回去。可以在 function prelude 中把 value 保存到 stack,再在 conclusion 中恢复。

x86 还使用 registers 传递 function arguments 和 return value。前 6 个 arguments 按以下顺序放入 registers:

text
rdi rsi rdx rcx r8 r9

如果 arguments 超过 6 个,约定使用 caller frame 中的空间保存剩余 arguments;不过在后面的 Functions 章节中,我们会安排成不需要超过 6 个 arguments。rax 用于保存 function return value。

我们把 function call 期间仍在使用的 variable 称为 call-live variable。

考虑一个连续调用两次 read 的 program。若 variable x 在第二次 read 期间仍会使用,它就是 call-live;必须确保调用 read_int 时不会覆盖 x 的 value。一种直接方法是在每次 function call 前把 caller-saved registers 中的所有 value 保存到 stack,call 后再恢复。这样,即使 register allocator 把 x 分配到 caller-saved register,跨 call 也能保留它的 value。

但 stack save / restore 相对较慢。如果 x 使用次数不多,直接把它分配到 stack location 可能更好。更好的情况是把 x 放到 callee-saved register,这样 function call 期间无需保存和恢复。

对于 call-live variable,我们建议把它们分配到 callee-saved register,或者 spill 到 stack。对于非 call-live variable,按以下顺序尝试:1)找可用的 caller-saved register,为其他 variable 留出 callee-saved register;2)找 callee-saved register;3)spill 到 stack。

在 graph-coloring register allocator 中实现这个策略很直接。首先,我们本来就需要计算每条 instruction 处于 in-use 状态的 variable,因此可以知道哪些 variable 是 call-live。其次,建立 interference graph 时,可以为每个 call-live variable 与每个 caller-saved register 添加 edge;这样 graph coloring 就不会把它们分配到 caller-saved register。

从 callee 视角看,重点是 main 的 prelude 和 conclusion。Prelude 通常先把 rbp 保存到 stack,再把 rbp 设置为当前 stack pointer。现在可以看出保存 rbp 的原因:它是 callee-saved register。如果 variable x 被分配到 rbx,prelude 还需要 push rbx,因为 rbx 也是 callee-saved register;其他没有被使用的 callee-saved register 不需要保存。Prelude 再从 rsp 减去 8 bytes,使其保持 16-byte alignment。Conclusion 使用 popq 恢复 rbx。

原文的两次 read 示例中,x 被分配到 callee-saved %rbx,y 被分配到 caller-saved %rcx:

asm
start:
    callq read_int
    movq  %rax, %rbx       # x;之后仍然 live
    callq read_int
    movq  %rax, %rcx       # y;之后不跨 call live
    addq  %rcx, %rbx
    movq  %rbx, %rax
    addq  $42, %rax
    jmp   conclusion

main:
    pushq %rbp
    movq  %rsp, %rbp
    pushq %rbx             # 保存 callee-saved register
    subq  $8, %rsp         # 保持 16-byte alignment
    jmp   start

conclusion:
    addq  $8, %rsp
    popq  %rbx
    popq  %rbp
    retq

这个例子说明 register allocator 不需要在每个 call 前后显式保存所有 caller-saved values;只要把跨 call 仍 live 的 variable 排除在 caller-saved registers 之外,就能用 calling convention 保证其 value 不被破坏。没有跨 call live 的 y 则可以使用 %rcx,从而把 callee-saved registers 留给真正需要长期保存的 variables。

mermaid
flowchart LR
    A["call-live variable"] --> B{"是否放入 callee-saved register?"}
    B -->|可以| C["callee-saved register"]
    B -->|不行| D["spill 到 stack"]
    E["非 call-live variable"] --> F["caller-saved register"]
    F -->|无空闲 register| G["callee-saved register"]
    G -->|仍不足| D

Liveness Analysis

uncover_live pass 执行 liveness analysis,发现 program 的不同区域中哪些 variable 处于 in-use 状态。

如果某个 variable 或 register 的当前 value 会在 program 的后面某个位置使用,那么在当前 program point 它就是 live。我们把 variable、stack location 和 register 统称为 location。

考虑下面有两次写入 b 的 code fragment:a 和 b 是否同时 live?

asm
movq $5, a
movq $30, b
movq a, c
movq $10, b
addq b, c

答案是否定的:a 从第 1 行 live 到第 3 行,b 从第 4 行 live 到第 5 行。第 2 行写入 b 的 integer 从未被使用,因为在下一次 read(第 5 行)之前已经被第 4 行覆盖。

可以从后向前(也就是沿 execution order 反向)遍历 instruction sequence,计算每条 instruction 的 live location。设 instruction sequence 为 I₁, ..., Iₙ。用 L_after(k) 表示 instruction Iₖ 执行之后的 live location set,用 L_before(k) 表示执行之前的 live location set。

相邻 instruction 满足:

$$L_{after}(k) = L_{before}(k+1)$$

最后一条 instruction 执行后没有 live location:

$$L_{after}(n) = \emptyset$$

然后从后向前反复应用:

$$L_{before}(k) = (L_{after}(k) - W(k)) \cup R(k)$$

其中,W(k) 是 instruction Iₖ 写入的 locations,R(k) 是 instruction Iₖ 读取的 locations。

jmp 是特殊情况:jmp 之前 live 的 locations 应当是 jump target 处的 L_before。因此建议维护名为 label->live 的 alist,把每个 label 映射到其 block 第一条 instruction 的 L_before。当前 LangXVar program 中唯一的 jmp 是跳转到 conclusion;conclusion 读取 rax 和 rsp,所以应映射为 {rax, rsp}。

对上面的五条 instruction 从第 5 行开始计算:

text
instruction          live-before       live-after
movq $5, a            ∅                  {a}
movq $30, b           {a}                {a}
movq a, c             {a}                {b,c}
movq $10, b           {c}                {b,c}
addq b, c             {b,c}              ∅

例如最后的 addq b, c 是最后一条 instruction,因此 L_after(5)=∅;它写入 c,读取 b 和 c,所以:

$$L_{before}(5)=(\emptyset-{c})\cup{b,c}={b,c}$$

第 4 行 movq $10, b 的 L_after 等于第 5 行的 L_before,即 {b,c};它写入 b,不读取 variable,因此 L_before(4)={c}。

书中 running example 的完整 backward trace 如下。这里把 %rsp 也列入 live set,因为函数 epilogue 和 conclusion 仍然需要它;在跳转到 conclusion 的位置,%rax 是返回值所在的 register:

text
instruction             live-before          live-after
movq $1, v               {rsp}                {v,rsp}
movq $42, w              {v,rsp}              {v,w,rsp}
movq v, x                {v,w,rsp}            {w,x,rsp}
addq $7, x               {w,x,rsp}            {w,x,rsp}
movq x, y                {w,x,rsp}            {w,x,y,rsp}
movq x, z                {w,x,y,rsp}          {w,y,z,rsp}
addq w, z                {w,y,z,rsp}          {y,z,rsp}
movq y, t                {y,z,rsp}            {t,z,rsp}
negq t                   {t,z,rsp}            {t,z,rsp}
movq z, %rax             {t,z,rsp}            {rax,t,rsp}
addq t, %rax             {rax,t,rsp}          {rax,rsp}
jmp conclusion           {rax,rsp}            —

这个表也说明了为什么 movq x, y 之后 x 和 y 会同时 live,而 movq x, z 之后 x 不再 live:后者的 destination z 已经接替了 x 保存的 value。对 jmp conclusion,不能把普通的“顺序上的下一条 instruction”当作 successor,而必须使用目标 label 的 live set。

当 CFG 含有 loop 时,上面的单次 backward pass 不够用。以 mainstart → block5 → block7 → block5 为例,可以从所有 block 的 empty set 开始,逐轮得到:

text
m₀: mainstart: {}, block5: {}, block7: {}, block8: {}
m₁: mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
m₂: mainstart: {}, block5: {i, rsp, sum},
    block7: {i, sum}, block8: {rsp, sum}
m₃: mainstart: {rsp}, block5: {i, rsp, sum},
    block7: {i, rsp, sum}, block8: {rsp, sum}

m₃ 已经收敛:再次分析 block5 或 block7 不会增加任何 location。这里 block5 的 live-after 是 block7 与 block8 入口状态的 union;block7 的 live-after 则来自回边 block5。这正是后续通用 analyze_dataflow worklist algorithm 要计算的 fixed point。

练习

手工对 running example 做 liveness analysis,为每条 instruction 计算 live-before 和 live-after set,并与书中 solution 对比。然后实现 uncover_live pass:Racket 版把 live-after set sequence 存入 Block 的 info field。

建议实现三个辅助 function:1)计算 Arg 中出现的 locations;2)计算 instruction 的 read set R;3)计算 instruction 的 write set W。callq 的 write set 应包含所有 caller-saved register,因为 calling convention 允许 function call 改写这些 register;read set 应根据被调用 function 的 arity 包含相应 argument-passing registers。这也是 Callq AST node 包含 arity 的原因。

Build the Interference Graph

Liveness analysis 告诉我们每个 location 在哪里 live。但 register allocation 更具体的问题是:locations u 和 v 是否同时 live,从而不能分配到同一个 register?为了更高效地回答这个问题,我们创建显式 data structure:interference graph。

Interference graph 是一个 undirected graph:如果两个 locations 同时 live,也就是彼此 interfere,就在它们之间添加 edge。Racket 版可以使用 graph package 表示它。

最直接的构造方式是:对每条 instruction 之间的 live location set,给 set 中每一对 variable 添加 edge。这个方法有两个问题:对包含 n 个 live location 的 set,需要 O(n²) 时间考虑每一对;另外,如果两个 locations 保存相同 value(因为其中一个刚被 move 到另一个),它们可能同时 live,却不必 interfere。

更好的方法是关注 writes。Instruction 写入的 location 不能覆盖 live location 中仍需使用的 value。因此,对每条 instruction,把被写 locations 与 live locations 连接起来;location 不与自己 interfere。

对于 callq,把所有 caller-saved registers 看成被写入,因此每个 live variable 都与每个 caller-saved register 添加 edge。对于 movq,有一个特殊情况:如果 live variable v 与 move 的 source 相同,那么 source 和 destination 保存相同 value,不需要在 v 与 destination 之间添加 edge。

基本规则是:

  1. 如果 Iₖ 是 movq s, d,那么对于每个 v ∈ L_after(k),当 v ≠ d 且 v ≠ s 时,添加 edge (d,v)。
  2. 对其他 instruction,对于每个 v ∈ L_after(k),当 v ≠ d 时,添加 edge (d,v);对于 callq,把每个 caller-saved register 当作被写入的 location。
mermaid
flowchart TD
    I["instruction Iₖ"] --> W["写入 locations W(k)"]
    I --> L["L_after(k)"]
    W --> E["与 live locations 建 edge"]
    L --> E
    E --> G["interference graph"]

后续部分会把 interference graph 转换为 graph coloring 问题,并把颜色映射到具体 register;如果颜色数量不足,再选择 variable spill 到 stack。

Graph Coloring via Sudoku

原书在这里用 Sudoku 说明 graph coloring。Racket edition 的原图由 Sudoku board 和黑白 graph 并排组成;这里保留原图的左右位置与相对宽度:

Sudoku boardCorresponding graph
assets/sudokuassets/sudoku graph bw

现在进入本章的核心:把 variables 映射到 registers 和 stack locations。彼此 interfere 的 variable 必须映射到不同 location。换成 interference graph 的说法,就是相邻 vertex 必须拥有不同颜色;如果把 location 看作 color,register allocation 就变成了 graph coloring problem。

读者可能比自己意识到的更熟悉 graph coloring:流行的 Sudoku game 就是 graph coloring 的一个实例。可以按以下方式从初始 Sudoku board 构造 graph:

  1. 每个 Sudoku square 对应一个 vertex。
  2. 如果两个 square 位于同一 row、column 或 3×3 region,就在对应 vertex 之间添加 edge。
  3. 选择 9 种 colors,对应数字 1 到 9。
  4. 根据 board 中 square 的初始数字,为相应 vertex 指定 color。

如果能用这 9 种 colors 给剩余 vertex 着色,也就解出了对应的 Sudoku。Pencil Marks 技巧与 graph coloring algorithm 的 heuristic 相似:通过 elimination 确定一个 square 不再可用的数字,并把这些数字写在 square 中。如果一个 square 已经分配了数字 1,就在同 row、column 和 region 的 square 中写下 pencil mark 1。

Pencil Marks 对应由 Brélaz 提出的 saturation。在 Sudoku 术语中,vertex 的 saturation 是已经不可用的数字集合;在 graph 术语中:

$$ \mathrm{saturation}(u)={c\mid\exists v.\ v\in\mathrm{adjacent}(u)\land\mathrm{color}(v)=c} $$

其中 adjacent(u) 是与 u 共享 edge 的 vertex 集合。

如果一个 square 只剩一个可能的数字,就选择它。但如果没有 square 只剩一种可能呢?一种 brute-force 方法是全部尝试:先选第一个,如果最终得到 solution 就结束;否则 backtrack,再选择下一个可能性。Pencil Marks 可以减少 search tree 的 branching degree,但 backtracking 仍可能非常耗时。

减少 backtracking 的方法是 most-constrained-first heuristic,也称 minimum remaining values:选择 square 时,优先选择剩余可能性最少的 square,也就是 saturation 最高的 vertex。越早处理受限程度高的 square 越好,否则后面可能已经没有可用 possibility。

Register allocation 比 Sudoku 简单,因为 register 用完后可以 fallback 到 stack location。因此可以用 greedy search 替代 backtracking:每次做当下最好的选择,然后继续。为了尽量减少所需 colors,greedy search 仍使用 most-constrained-first heuristic。本章的算法大致等价于 DSATUR graph coloring algorithm:

text
Algorithm: DSATUR
Input:  graph G
Output: 每个 vertex v ∈ G 的 assignment color[v]

W ← vertices(G)
while W ≠ ∅ do
    从 W 中选择 saturation 最高的 vertex u;并列时随机打破
    找到不在 { color[v] : v ∈ adjacent(u) } 中的最小 color c
    color[u] ← c
    W ← W - {u}

算法用 integers 表示 colors。0 到 k-1 对应 register allocator 使用的 k 个 registers;k 及更大的 integer 对应 stack locations。没有用于 register allocation 的 register(例如 rax)被赋予 negative integer:rax 为 -1,rsp 为 -2。

从实现角度看,DSATUR 的核心循环可以直接写成下面这样;saturation(u) 应由当前已着色邻居的 color 集合重新计算或增量维护:

text
W ← vertices(G)
while W ≠ ∅ do
    u ← arg max { |saturation(v)| : v ∈ W }
    c ← 0
    while c ∈ { color(v) : v ∈ adjacent(u) 且 v 已着色 } do
        c ← c + 1
    color(u) ← c
    W ← W - {u}

完成 assign homes 后,一个含有 stack spill 的版本会把 color 映射为 memory operand。例如 running example 可以得到如下形态:

asm
movq $1, -8(%rbp)
movq $42, %rcx
movq -8(%rbp), -8(%rbp)
addq $7, -8(%rbp)
movq -8(%rbp), -16(%rbp)
movq -8(%rbp), -8(%rbp)
addq %rcx, -8(%rbp)
movq -16(%rbp), %rcx
negq %rcx
movq -8(%rbp), %rax
addq %rcx, %rax
movq %rax, %rdi
callq print_int

这里 -8(%rbp) 和 -16(%rbp) 是不同的 stack locations;某些看似冗余的 memory-to-memory 形式在真正的 x86-64 指令选择中还需要经过 patching,因为 x86-64 不允许大多数 arithmetic instruction 直接以两个 memory operand 工作。

一个可行的 running example coloring 是:

text
rax ↦ -1    rsp ↦ -2
t   ↦ 0     z   ↦ 1
x   ↦ 1     y   ↦ 2
w   ↦ 0     v   ↦ 1

如果只使用一个 register %rcx,则 color 到 location 的映射为:

$$ {0\mapsto%rcx,\ 1\mapsto-8(%rbp),\ 2\mapsto-16(%rbp)} $$

所以 x 与 z 可以共享 -8(%rbp),因为它们不会同时 live;w 与 t 也可以共享 %rcx。

建议创建 auxiliary function color_graph,接收 interference graph 和 program 中的 variable list,并返回 variable 到 color 的 mapping。为了优先处理 saturation 高的 node,可以使用 priority queue,并维护 variable 到 priority queue handle 的 mapping,以便 saturation 变化时通知 queue。

完成 coloring 后,把前 k 个 colors 映射到 k 个 registers,其余 colors 映射到 stack locations。实现 allocate_registers,并创建覆盖 register allocation、包括 spilling 的 5 个 tests。

DSATUR 的逐步着色示例

在实际 coloring 中,先给 register vertices 固定颜色:rax ↦ -1、rsp ↦ -2。这些负数颜色不会被普通 variable 选择。随后维护每个未着色 vertex 的 saturation set:它的相邻 vertex 已经使用过的颜色集合。

以 Racket 版 running example 为例,t 同时与 rax、rsp interfere,因此初始 saturation 为 { -1, -2 },比其他 variable 更高;把 t 着成 0 后,z、rax 与 rsp 的 saturation 中加入 0。接着把 z 着成 1,再把 saturation 最高的 w 着成 0,因为它的邻居还没有使用 0。y 与颜色为 0 的 w 和颜色为 1 的 z 都相邻,所以只能使用 2。最后 v 与 x 可以使用 1,得到一种合法 coloring:

text
rax ↦ -1    rsp ↦ -2
t   ↦ 0     z   ↦ 1
x   ↦ 1     y   ↦ 2
w   ↦ 0     v   ↦ 1

如果只有一个 register %rcx 可供 allocator 使用,则 0 映射到 %rcx,1 映射到 -8(%rbp),2 映射到 -16(%rbp)。因此 x 与 z 可以共享 -8(%rbp),w 与 t 可以共享 %rcx;它们虽然在程序中都出现过,但在相同 program point 不会同时 live。

逐轮记录这个 Racket 示例的 coloring 过程如下。先固定 rax=-1、rsp=-2;随后每次选择 saturation 最大的未着色 vertex,并取不出现在邻居颜色集合中的最小 nonnegative color:

轮次选择的 vertex选择依据新颜色受影响的邻居 saturation
0t初始 saturation 为 {−1,−2},最高0z、rax、rsp 加入 0
1zsaturation 最高;0 已被相邻 t 使用1t、y、w、rsp 加入 1
2w与 y 并列最高;0 可用0x、y、v、rsp 加入 0
3ysaturation 为 {0,1,−2}2w、z、rsp 加入 2
4v与 x 并列;1 是最小可用颜色1w、rsp 更新 saturation
5x只与 w、rsp 冲突,1 可用1coloring 完成

最后的 mapping 为 t↦0、z↦1、w↦0、y↦2、v↦1、x↦1。例如 y 不能选择 0 或 1,因为它分别与 w、z interfere;而 x 可以使用 1,因为它不与颜色为 1 的 z 或 v 相邻。

Python 版示例的变量集合为 tmp_0、tmp_1、z、x、y、w、v。若从 tmp_0 开始并赋予颜色 0,则 z 可使用 1,w 使用 0,y 使用 2,最后 v、tmp_1 和 x 可使用 1。这说明 greedy coloring 的结果会受 tie-breaking 影响,但只要每次选择的颜色不在邻接 saturation set 中,结果就是合法的。

Priority queue 与颜色到 location 的映射

建议让 color_graph 接收 interference graph 和 program 中的 variable list,并返回 variable 到 color 的 mapping。为了高效取得 saturation 最高的 node,可以使用 priority queue;同时维护 variable 到 queue handle 的 mapping。每当某个已着色 vertex 的颜色加入邻居 saturation set,就通过对应 handle 更新邻居的 priority。

完成 coloring 后,把前 k 个 nonnegative colors 映射到 allocator 可用的 k 个 registers,其余 colors 按顺序映射到 stack locations。这个映射与 coloring 组合后就是 assign_homes 所需的 location map。allocator 还需要在 X86Program 的 info 中记录 used_callee,供后面的 prelude/conclusion 保存和恢复 callee-saved registers。

Racket support code 中的 priority queue 提供以下操作:make-pqueue 接收比较 predicate 并创建空 queue;pqueue-count 返回 item 数量;pqueue-push! 插入 item 并返回其 handle;pqueue-pop! 取出优先级最高(min queue 中是数值最小)的 item;pqueue-decrease-key! 在 item 的 priority 变小后通知 queue。color_graph 应为每个 variable 保存一个 handle,这样某个邻居获得新颜色、导致 saturation 改变时,就能更新 queue,而不必线性扫描所有未着色 variables。

完成 color assignment 后,allocate_registers 还要统计使用过的 callee-saved registers 与 spilled variables 数量,并把这些信息写入 program info。普通 spill 使用 procedure-call stack;tuple 或可能包含 tuple pointer 的 value 则需要由后续章节改为 root stack。这个 info contract 会被 prelude_and_conclusion 用来计算 frame size 和保存/恢复 register。

Patch Instructions

register allocation 后,仍需确保每条 instruction 最多只有一个 memory-access argument。movq -8(%rbp), -16(%rbp) 不合法;修复方式是先把 source move 到 rax,再把 rax move 到 destination:

asm
movq -8(%rbp), %rax
movq %rax, -16(%rbp)

从 -8(%rbp) move 到 -8(%rbp) 的 instruction 是 trivial move,可以直接删除。一般来说,source 和 destination 是同一 location 的 trivial move 都应删除。running example 修复后的关键片段为:

asm
movq $1, -8(%rbp)
movq $42, %rcx
addq $7, -8(%rbp)
movq -8(%rbp), %rax
movq %rax, -16(%rbp)
addq %rcx, -8(%rbp)
movq -16(%rbp), %rcx
negq %rcx
movq -8(%rbp), %rax
addq %rcx, %rax
jmp conclusion

实现 patch_instructions 的更新版本,删除 trivial move,并运行 tests 验证。

原文提出的进一步优化称为 move biasing。如果两个 variable p、q 一起出现在 movq p, q 或 movq q, p 中,就称它们 move related。普通 DSATUR 只根据 saturation 选择下一个 vertex;move biasing 在 saturation 相同的情况下,优先选择能够与 move-related variable 使用相同 color 的 vertex。选择 color 时也优先复用 move-related variable 已使用的 color,但这一偏好不能压过“register 优先于 stack location”的基本策略,只能作为同类候选之间的 tie breaker。

可以额外维护一个 move graph,其中每条 edge 表示一对 move-related variables。对本章 running example,主要的 move edges 是:

text
v — x — y — t
    |
    z

如果 v 与 x 不 interfere,则把它们着成同一 color,就能把 movq v, x 变成 trivial move;同理,让 x、y、t 尽可能共享 color,可以在 register allocation 后消除更多 movq。该优化改变的是 tie-breaking,不改变 interference constraint:任何有 interference edge 的两个 locations 仍然绝不能使用同一 color。

Prelude and Conclusion

这个 pass 生成满足 x86 calling convention 的 prelude 和 conclusion。加入 register allocator 后,allocator 使用的 callee-saved register 必须在 prelude 中保存,并在 conclusion 中恢复。

在 allocate_registers pass 中,向 X86Program 的 info 增加 used_callee entry,保存被分配给 variable 的 callee-saved register 集合。prelude_and_conclusion 根据它决定哪些 register 需要 save / restore。

计算 prelude 中调整 rsp 的数量时,要计入保存 callee-saved register 的空间,并确保 frame 是 16 的倍数。设 S 是 spilled variable 数量,C 是分配给 variable 的 callee-saved register 数量,align 把数字向上取整到最近的 16 bytes,则从 rsp 中减去的数量 A 为:

$$ A=\mathrm{align}(8S+8C)-8C $$

减去 8C 的原因是:prelude 使用 pushq 保存每个 callee-saved register,而 pushq 本身会从 rsp 减去 8。

完整的 register allocation pipeline 是:

mermaid
flowchart LR
    L["LangVar"] --> U["uniquify"]
    U --> R["remove_complex_operands"]
    R --> E["explicate_control"]
    E --> S["select_instructions"]
    S --> L1["uncover_live"]
    L1 --> I["build_interference"]
    I --> A["allocate_registers"]
    A --> P["patch_instructions"]
    P --> PC["prelude_and_conclusion"]
    PC --> X["LangXInt"]

在 running example 中,只允许 allocator 使用 %rbx 和 %rcx,于是一个 variable 被 spill 到 -16(%rbp)。Prelude push %rbx,再从 rsp 减去 8 为 spilled variable 留空间;此时 rsp 仍按 16 bytes 对齐。Spilled variable 必须放在 saved callee-saved register 的更低地址,因此使用 -16(%rbp)。Conclusion 先把 stack pointer 向上移动 8 bytes,再 pop 旧的 %rbx 和 %rbp,最后用 retq 返回 operating system。

书中这个配置下的完整 Racket edition 输出如下:

asm
start:
    movq $1, %rbx
    movq $42, -16(%rbp)
    addq $7, %rbx
    movq %rbx, %rcx
    addq -16(%rbp), %rcx
    negq %rbx
    movq %rcx, %rax
    addq %rbx, %rax
    jmp conclusion

    .globl main
main:
    pushq %rbp
    movq %rsp, %rbp
    pushq %rbx
    subq $8, %rsp
    jmp start

conclusion:
    addq $8, %rsp
    popq %rbx
    popq %rbp
    retq

pushq %rbx 保存 callee-saved register,subq $8, %rsp 为一个 spilled variable 预留空间;两者组合后使调用期间的 stack alignment 满足 16-byte 要求。conclusion 按相反顺序释放 spill space、恢复 %rbx 和 %rbp,再用 retq 把控制权交还给 operating system。

Challenge:Move Biasing

Move biasing 是 register allocator 的 enhancement。它的动机是:如果能把 move-related variable 放到相同 register,就可以删除更多 movq instruction。

如果两个 variable p 和 q 共同参与 movq p, q 或 movq q, p,就称它们 move related。决定下一个要 coloring 的 variable 时,如果多个 variable saturation 相同,应优先选择能够与 move-related variable 使用相同 color 的 variable。为 variable 选择 color 时,也应优先选择 move-related variable 已使用的 color,前提是它们不 interfere。

这个偏好不能覆盖 register 优先于 stack location 的规则;它只能在 registers 之间或 stack locations 之间选择时作为 tie breaker。建议像表示 interference 一样用 graph 表示 move relationship,称为 move graph。running example 中的 move relationships 包含:

text
v — x
x — y
x — z
y — t

如果 y 与 t move-related 且不 interfere,就优先让 y 使用与 t 相同的 color;类似地,让 x 使用与 y 相同的 color,可以删除更多 trivial move。

使用全部 general-purpose registers 时,普通 coloring 可能在 running example 中产生如下代码:

asm
movq $1, %rdx
movq $42, %rcx
movq %rdx, %rdx
addq $7, %rdx
movq %rdx, %rsi
movq %rdx, %rdx
addq %rcx, %rdx
movq %rsi, %rcx
negq %rcx
movq %rdx, %rax
addq %rcx, %rax
jmp conclusion

其中两个 source 与 destination 相同的 movq 可以删除;如果把 t、v、x 和 y 更积极地放入同一个 register,则可以进一步删除三条 movq。这正是 move biasing 要利用的信息:它不放宽 interference constraint,而是改变相同 saturation 下的选择顺序与 color 偏好。

可以把 DSATUR 的选择规则扩展为下面的形式:

text
choose_vertex(W):
  先取 saturation 最高的 vertex
  若有多个候选:优先选择与已着色 vertex move-related 的候选

choose_color(u):
  forbidden = colors(adjacent(u))
  preferred = colors(move-neighbors(u)) - forbidden
  若 preferred 中存在 register color:选择其中一个
  否则选择最小的可用 register color
  若不存在可用 register color:在 stack colors 中优先复用 preferred

这里的 preferred 只能作为同一类 location 内的 tie breaker:即使 move-related variable 使用了 stack color,也不能因此放弃一个可用 register。只有在 register candidates 都不可用,或者多个 register candidates 同样可用时,才使用 move relationship 的偏好。

以源稿的 Racket running example 为例,y 与 t move-related 且不 interfere;若 t 已着为 color 0,则应优先把 y 着为 0。随后 x 又与 y move-related,因此也可以着为 0。原本的三条 move:x → y、y → t 以及相关的同色搬运,都可能在 patch 阶段被识别为 trivial move 并删除。

实现 move biasing,创建至少包含一个 move-biasing opportunity 的两个 tests,并检查生成的 x86 program,确保优化生效且所有 tests 仍通过。

本章练习

  1. 手工对 running example 做 liveness analysis,计算每条 instruction 的 live-before 与 live-after sets,并与书中结果比较。
  2. 实现 uncover_live,将每条 instruction 的 live-after set 存入 Block 的 info,并正确处理 callq 的 caller-saved registers 与 argument-passing registers。
  3. 按本章算法实现 build_interference,把 interference graph 存入 program info 的 conflicts 字段。
  4. 实现 allocate_registers,创建 5 个覆盖 register allocation 各方面(包括 spilling 到 stack)的 programs。
  5. 更新 patch_instructions 以删除 trivial moves,并在 allocate_registers 之后测试该 pass。
  6. 更新 prelude_and_conclusion 以支持 register allocation,运行完整 compiler tests。
  7. 修改 allocate_registers 以考虑 move biasing;创建至少 2 个包含 move-biasing opportunity 的 tests,检查生成的 x86 program,并确认全部 tests 仍通过。

Further Reading

早期 register allocation algorithm 在 1950 年代为 Fortran compiler 开发。Graph coloring 在 1970 年代末和 1980 年代初被用于优化 compiler。Chaitin 的 algorithm 基于 Kempe 的观察:如果 graph G 有一个 degree 小于 k 的 vertex v,并且移除 v 后得到的 subgraph 可以用 k 种 colors 着色,那么 G 也可以用 k 种 colors 着色。

原因是:subgraph 完成 k-coloring 后,v 的 neighbors 最多使用少于 k 种不同颜色,因此至少剩下一种 color 可以分配给 v。

Chaitin 的 algorithm 移除 degree 小于 k 的 vertex,递归 coloring 剩余 graph,返回时再为该 vertex 选择 available color。如果没有 degree 小于 k 的 vertex,就随机选择一个 vertex,spill 它,移除后递归 coloring。

在 coloring 之前,可以把 move-related 且不互相 interfere 的 variable merge,这个过程称为 coalescing。Coalescing 会减少 move 数量,但可能让 graph 更难 coloring。Conservative coalescing 只在两个 variable 的 high-degree neighbor 数量低于 k 时 merge;biased coloring 则尽可能让 variable 与另一个 move-related variable 使用相同 color。

另一种 greedy coloring 是 offline algorithm:在分配 colors 前就确定 vertex order;本章的 saturation-based algorithm 是 online algorithm,它使用当前 color assignment 影响剩余 vertex 的处理顺序。我们采用 saturation-based coloring,是因为可以通过 Sudoku 有趣地引入 graph coloring。

Register allocator 可以把每个 variable 只映射到一个 location,也可以通过 live range splitting 把 variable 替换为多个 variable,使每个 variable 负责 live range 的一部分。如果 compile time 极其重要,例如在 just-in-time compiler 中,graph coloring 可能过于昂贵,此时 linear scan algorithm 可能更合适。

参考资料

← 返回列表
← 上一篇 Essentials of Compilation:整数与变量 下一篇 → Essentials of Compilation:布尔值与条件分支

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论