Essentials of Compilation:循环与数据流分析
Essentials of Compilation:循环与数据流分析
本章加入 imperative language 的 loops、mutable local variables 和 sequencing,并用 dataflow analysis 处理 loops 带来的 cyclic control flow。
TL;DR
while和set!引入 side effect;begin用于按顺序执行多个 expression。- mutable variable 的 read 不能随意移动,否则
remove_complex_operands可能改变 program behavior。 - loop 让 control-flow graph 出现 cycle,不能再依赖 reverse topological order 做 liveness analysis。
- Dataflow analysis 从 bottom approximation 开始,通过 worklist 迭代到 least fixed point。
uncover-get!将 mutable variable 的 read 标记为 effectful 的get!,保护 side-effect ordering。
名词解释
| 名词 | 含义 | 本章对应物 |
|---|---|---|
| mutable variable | value 可通过 assignment 改变的 variable | 出现在 set! 左侧的 variable |
| side effect | 改变 environment 或依赖执行顺序的效果 | set!、while、read |
| dataflow analysis | 沿 control-flow graph 传播 abstract state 的 static analysis | liveness 的 worklist 版本 |
| lattice | 带 partial order、bottom 和 join 的 abstract state 集合 | location set 与 label mapping |
| fixed point | analysis 迭代后不再变化的 state | f(m)=m |
目录
| 章节 | 说明 |
|---|---|
| Loops and Dataflow Analysis | imperative features 与 loop 示例 |
The LangLoop Language | while、set!、begin 和 void |
| Interpreter and Type Checker | box、assignment 与 Void type |
| Cyclic Control Flow and Dataflow Analysis | 从 cycle 到 least fixed point |
| Mutable Variables & Remove Complex Operands | 保持 read / write 顺序 |
Uncover get! | 标记 mutable read |
Loops and Dataflow Analysis
本章研究 imperative programming language 的两个 hallmark feature:loop 和对 local variable 的 assignment。下面的 Racket program 计算前 5 个正整数的和:
(let ([sum 0])
(let ([i 5])
(begin
(while (> i 0)
(begin
(set! sum (+ sum i))
(set! i (- i 1))))
sum)))
while loop 由 condition 和 body 组成。只要 condition 保持 true,body 就会重复求值。set! 由 variable 和 right-hand-side expression 组成,它把 variable 的 value 更新为 right-hand-side 的结果。
while 和 set! 的主要作用是产生 side effect,因此没有有意义的 result value;它们的 result 是 #<void>。(void) 是显式创建这个 value 的方式,其 type 是 Void。#<void> 可以像其他 value 一样在 LangLoop 中传递,也可以和另一个 #<void> 比较 equality;但 LangLoop 没有其他专门针对它的 operation。
加入 while 和 set! 后,加入用于按顺序执行 side effect 的 begin 很有帮助。begin 包含一个或多个 subexpression,并按从左到右的顺序求值。
The LangLoop Language
LangLoop 在 LangIf 的基础上增加:
Exp ::= SetBang(Var, Exp)
| Begin(Exp*, Exp)
| WhileLoop(Exp, Exp)
| Void()
LangLoop ::= Program('(), Exp)
concrete syntax 对应:
(set! var exp)
(begin exp ... exp)
(while exp exp)
(void)
LangLoop 的 definitional interpreter 增加 SetBang、WhileLoop、Begin 和 Void case,并修改 Var 与 Let case。为了支持 variable assignment,并使 variable lifetime 不受原先 lexical binding 的限制,Let 中绑定给 variable 的 value 使用 box 保存;Var case 对读取到的 box 做 unbox。
SetBang 在 environment 中找到 variable 对应的 box,再用 set-box! 把它改成 right-hand side 的结果;result value 是 #<void>。WhileLoop 重复执行:1)求值 condition;2)如果结果为 true,则求值 body。loop 的 result 同样是 #<void>。Begin(es, body) 先为 effects 求值 es,再求值并返回 body 的结果;Void 产生 #<void>。
(define interp-Lwhile-class
(class interp-Lif-class
(super-new)
(define/override ((interp-exp env) e)
(define recur (interp-exp env))
(match e
[(Let x e body)
(define new-env (dict-set env x (box (recur e))))
((interp-exp new-env) body)]
[(Var x) (unbox (dict-ref env x))]
[(SetBang x rhs)
(set-box! (dict-ref env x) (recur rhs))]
[(WhileLoop cnd body)
(define (loop)
(cond [(recur cnd) (recur body) (loop)]
[else (void)]))
(loop)]
[(Begin es body)
(for ([e es]) (recur e))
(recur body)]
[(Void) (void)]
[else ((super interp-exp env) e)]))))
(define (interp-Lwhile p)
(send (new interp-Lwhile-class) interp-program p))
Type checker 中,SetBang 要求 variable type 与 right-hand-side type 相同,结果 type 为 Void;while 的 condition 必须是 Boolean,结果 type 为 Void;begin 的结果 type 是最后一个 subexpression 的 type。
Interpreter and Type Checker
LangLoop type checker 的核心规则可以概括为:
SetBang(x, rhs) : Void 要求 type(rhs) = type(x)
WhileLoop(c, b) : Void 要求 type(c) = Boolean
Begin(es, body) : type(body)
Void() : Void
完成这些 language features 到 x86 的 translation,表面上似乎很直接,因为 LangCIf 已经支持 assignment、goto、conditional branch 和 sequencing。但 loop 会引入 cycle,接下来需要新的 analysis 方法。
Cyclic Control Flow and Dataflow Analysis
此前 explicate_control 产生的 program 都保证是 acyclic;每个 while loop 现在会引入 cycle。这会影响 register allocation:之前 liveness analysis 可以按 control-flow graph 的 reverse topological order 处理,但 topological order 只有对 acyclic graph 才定义良好。
考虑上面“求前 5 个正整数之和”的 program。instruction selection 后、register allocation 前,control flow 大致如下:
mainstart:
movq $0, sum
movq $5, i
jmp block5
block5:
movq i, tmp3
cmpq tmp3, $0
jl block7
jmp block8
block7:
addq i, sum
movq $1, tmp4
negq tmp4
addq tmp4, i
jmp block5
block8:
movq $27, %rax
addq sum, %rax
jmp mainconclusion
如果从 block8 开始反向分析,可以得到 rsp 和 sum;但接着分析 block5 或 block7 时会发现它们互相跳转,于是无法继续使用单次拓扑遍历。
解决方法是先从 empty live-after set 开始,计算每个 block 的 under-approximation。under-approximation 只包含某些 execution 中 live 的 variable,可能遗漏其他 live variable。然后重复两步:1)用其他 block 的 approximate live-before set 更新每个 block 的 live-after set;2)再次对每个 block 做 liveness analysis。反复迭代后,under-approximation 最终会变成正确 solution。
这种迭代分析 control-flow graph 的方法适用于许多 static analysis problem,称为 dataflow analysis。它由 Kildall 在博士论文中提出。
对上例,先把每个 block 的 live-before approximation 设为空:
m0: mainstart: {}, block5: {}, block7: {}, block8: {}
第一次分析得到:
m1: mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
第二轮中,block5 的 live-after 是 block7 和 block8 的 live-before union,因此得到 {i, rsp, sum};block7 的 live-before 保持 {i, sum}。结果为:
m2: mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
继续更新跳到 block5 的 block 后,得到:
m3: mainstart: {rsp}, block5: {i, rsp, sum},
block7: {i, rsp, sum}, block8: {rsp, sum}
此时 approximation 已 convergence;m3 就是 solution。
这个迭代过程由 Kleene Fixed-Point Theorem 保证会收敛。粗略来说,lattice 是带 partial ordering ⊑、least element ⊥(bottom)和 join operator ⊔ 的集合。若 m_i ⊑ m_j,表示 m_j 至少包含和 m_i 一样多的信息,因此是更好或相等的 approximation。Bottom 表示完全没有信息;join 把两个 lattice element 的信息合并为它们的 least upper bound。
对 liveness analysis,abstract state 是 location set。构造 lattice L:elements 是 location sets,ordering 是 set inclusion,bottom 是 empty set,join 是 set union。再构造 lattice M:elements 是从 block label 到 L 中 location set 的 mapping,并按 block label 对 L 的 ordering 逐点排序。
把整个 program 的一次 liveness iteration 看成 lattice M 上的 function f:
$$f(m_i)=m_{i+1}$$
最终 solution m_s 满足 fixed point:
$$f(m_s)=m_s$$
而且它应是 least fixed point。Kleene chain 从 bottom 开始:
$$\bot\sqsubseteq f(\bot)\sqsubseteq f(f(\bot))\sqsubseteq\cdots$$
由于 program 中只有有限数量的 variable 和 block,lattice 只有有限长度的 ascending chain,因此迭代最终一定停止。
Generic worklist algorithm
通用 dataflow analysis 有 4 个参数:control-flow graph G、对一个 block 应用 analysis 的 transfer function、lattice 的 bottom 和 join operator。算法把所有 graph node 放入 worklist;每次取出一个 node,用其 predecessor 的 abstract state 做 join,调用 transfer 得到 output。如果 output 与旧 state 不同,就更新 mapping,并把 successor 放回 worklist。
(define (analyze_dataflow G transfer bottom join)
(define mapping (make-hash))
(for ([v (in-vertices G)])
(dict-set! mapping v bottom))
(define worklist (make-queue))
(for ([v (in-vertices G)])
(enqueue! worklist v))
(define trans-G (transpose G))
(while (not (queue-empty? worklist))
(define node (dequeue! worklist))
(define input (for/fold ([state bottom])
([pred (in-neighbors trans-G node)])
(join state (dict-ref mapping pred))))
(define output (transfer node input))
(cond [(not (equal? output (dict-ref mapping node)))
(dict-set! mapping node output)
(for ([v (in-neighbors G node)])
(enqueue! worklist v))]))
mapping)
这个 algorithm 写成 forward dataflow analysis:transfer 的 input 来自 control-flow graph 的 predecessor。Liveness 是 backward dataflow analysis,因此需要把 control-flow graph transpose 后传给 analyze_dataflow。
Mutable Variables & Remove Complex Operands
remove_complex_operands、set! 和 Racket 从左到右求值之间存在 subtle interaction。考虑:
(let ([x 2])
(+ x (begin (set! x 40) x)))
结果是 42:第一次 read x 得到 2,第二次得到 40。但如果 naive 地应用 remove_complex_operands:
(let ([x 2])
(let ([tmp (begin (set! x 40) x)])
(+ x tmp)))
结果会变成 80。问题在于 mutable variable 的 read / write 顺序很重要,而这个 pass 把 set! 移到了第一次 read x 之前。
解决办法是特殊处理 mutable variable 的 read:把每个 mutable variable 的 read 标记为 get!(abstract syntax 中为 GetBang),表示这是 effectful read,可能在不同时间产生不同结果。
例如发现 x mutable、y immutable 后,将:
(let ([x 2])
(let ([y 0])
(+ y (+ x (begin (set! x 40) x)))))
变为:
(let ([x 2])
(let ([y 0])
(+ y (+ (get! x) (begin (set! x 40) (get! x))))))
再次执行 remove_complex_operands 后:
(let ([x 2])
(let ([y 0])
(+ y (let ([t1 (get! x)])
(let ([t2 (begin (set! x 40) (get! x))])
(+ t1 t2))))))
t1 在 set! 之前取得 x 的 value 2,t2 在 set! 之后取得 40,结果保持 42。y 是 immutable,因此不需要额外 temporary;避免不必要的 temporary 可以减少 variable 数量,从而降低 spill 可能性。
这里的顺序问题是 Racket 特有的:Racket 规定 operator 或 function call 的 arguments 按从左到右求值,因此上面的程序必须得到 42。它的前身 Scheme 并不规定 arguments 的求值顺序,所以 Scheme compiler 可以自由选择顺序;在 Scheme 中,42 和 80 都可能是允许的结果。Racket 建立在 Chez Scheme compiler 之上,但 Racket 到 Scheme 的 translation 会使用额外的 let binding 显式固定求值顺序。
这种方案只需小幅修改 remove_complex_operands,但需要新的 uncover-get! pass。
Uncover get!
这个 pass 的目标是标记 mutable variable 的 use,使 remove_complex_operands 把它们当作 complex expression,从而保留它们与其他 operand side effect 之间的顺序。
第一步是收集所有 mutable variable。创建辅助 function collect-set!,递归遍历 expression,返回所有出现在 set! 左侧的 variable set:
(define (collect-set! e)
(match e
[(Var x) (set)]
[(Int n) (set)]
[(Let x rhs body)
(set-union (collect-set! rhs) (collect-set! body))]
[(SetBang var rhs)
(set-union (set var) (collect-set! rhs))]
...))
把这个 pass 放在 uniquify 之后,就不用担心 variable shadowing,Let 的逻辑可以保持简单。第二步是用新的 GetBang AST node 标记 mutable variable 的 occurrence;后续 compiler pass 将把 get! 作为 effectful read 处理。
标记阶段的核心 helper 接收 mutable-variable set 和待处理 expression:
(define ((uncover-get!-exp set!-vars) e)
(match e
[(Var x)
(if (set-member? set!-vars x)
(GetBang x)
(Var x))]
[(Int n) (Int n)]
[(Let x rhs body)
(Let x
((uncover-get!-exp set!-vars) rhs)
((uncover-get!-exp set!-vars) body))]
[(SetBang x rhs)
(SetBang x ((uncover-get!-exp set!-vars) rhs))]
[(Prim op es)
(Prim op (for/list ([e es])
((uncover-get!-exp set!-vars) e)))]
[else e]))
整个 pass 先用 collect-set! 得到 set,再对 program body 调用这个 helper:
(define (uncover-get! p)
(match p
[(Program info body)
(define set!-vars (collect-set! body))
(Program info ((uncover-get!-exp set!-vars) body))]))
因此 GetBang 只改变“这个 read 可能观察到 mutation”的 compiler classification,不改变 source-level 的 value;SetBang 左侧仍然是普通 variable name,避免把写入 operation 本身误判为一次 read。
Remove Complex Operands
在 LangLoop 中,get!、set!、begin 和 while 都是 complex expressions;set!、begin 与 while 的子表达式也可以继续是 complex expression。因此 remove_complex_operands 的新工作是把这些构造纳入 ANF translation。
当 complex expression 出现在要求 atomic operand 的位置时,必须用 fresh temporary 绑定它。例如,两个 begin 出现在 + 的参数位置时,可以变成:
(let ([tmp4 (begin
(set! y3 (read))
(get! x2))])
(let ([tmp5 (begin
(set! x2 (read))
(get! y3))])
(let ([tmp6 (+ tmp4 tmp5)])
(let ([tmp7 (get! x2)])
(+ tmp6 tmp7)))))
LangLoopANF 允许 let 的 right-hand side 是任意 expression,所以 begin 可以安全地放在 temporary 的绑定处。转换必须保持左到右的 evaluation order,不能把 effectful expression 重排。
Explicate Control 与 LangCLoop
explicate_control 在 LangIf 的 tail、assignment、predicate positions 之外,还要增加 effect position。begin 中除了最后一个 expression 之外的子表达式只为 side effect 求值,结果会被丢弃;如果某个 expression 显然是 pure 的,可以直接删除。
输出语言 LangCLoop 几乎与 LangCIf 相同,只增加 Void 和可以作为 statement 出现的 read。最重要的差别是 control-flow graph 现在可能有 cycle。
while 的显式化步骤如下:
- 为 loop 顶部生成 fresh label
loop。 - 以
goto loop作为 continuation,把 body 在 effect position 中翻译为body'。 - 在 predicate position 中翻译 condition:true 分支进入
body',false 分支进入原循环之后的 continuation。 - 用
looplabel 保存生成的 condition block,整个 while expression 变成goto loop。
flowchart TD
A[goto loop] --> B[loop: evaluate condition]
B -->|then| C[body effects]
C --> A
B -->|else| D[continuation]
新的辅助函数 explicate_effect 接受一个 effect-position expression 和 continuation,返回先执行该 expression 再执行 continuation 的 Tail。while、set!、begin 可以出现在 assignment 与 tail positions;只有 begin 能出现在 predicate position,因为另外两个构造的结果是 Void。
按原文的递归构造,处理:
(while cnd body)
时应先生成一个 fresh label loop,并把 goto loop 作为 body 的 continuation。于是,body 在 effect position 中得到 body';再调用 explicate_pred 处理 cnd,令 condition 为 true 时进入 body',为 false 时进入 while 之后的 continuation cont。最后把得到的 condition tail 存入 basic-blocks[loop],当前 while 本身只返回:
goto loop
伪代码可以写成:
loop = fresh-label("loop")
body' = explicate_effect(body, goto loop, basic_blocks)
loop' = explicate_pred(cnd, body', cont, basic_blocks)
basic_blocks[loop] = loop'
return goto loop
这里必须把 body 的 continuation 设为回到 loop,而不是直接把 body 的 instructions 拼在 condition 后面;否则下一轮迭代不会重新求值 condition。与此同时,begin 的前面部分要通过 explicate_effect 处理,最后一个 expression 则根据所在 context 分别交给 explicate_tail、explicate_assign 或 explicate_pred,以保持 side effect 和返回值的区别。
Select Instructions
处理 LangCLoop 只需要两项小改动:Void 翻译为 0;当 read 作为独立 statement 出现时,生成与 assignment 中相同的 callq read_int,但不再把结果移动到 left-hand side。
对“计算前五个正整数之和”的 running example,select_instructions、但尚未 register allocation 的结果如下。block5 是 loop condition,block7 是 loop body,block8 是退出后的 continuation;block7 回到 block5 的 jmp 正是后续 dataflow analysis 必须处理的回边:
mainstart:
movq $0, sum
movq $5, i
jmp block5
block5:
movq i, tmp3
cmpq tmp3, $0
jl block7
jmp block8
block7:
addq i, sum
movq $1, tmp4
negq tmp4
addq tmp4, i
jmp block5
block8:
movq $27, %rax
addq sum, %rax
jmp mainconclusion
从 control-flow graph 看,mainstart → block5,block5 分别通向 block7 与 block8,而 block7 → block5 形成 cycle。也正因为这个 cycle,不能再使用一次性的 reverse topological order 计算 live-before;需要让 block5 与 block7 反复交换状态,直到 fixed point。
Register Allocation
循环使 control-flow graph 出现 cycle,不能再像无环 CFG 那样按 topological order 做一次 liveness analysis。应改用通用的 analyze_dataflow fixed-point algorithm,并把 uncover_live 中按 topological order 处理 basic block 的代码替换掉。
analyze_dataflow 接受四个参数:
- CFG 的 transpose graph;
transfer函数,接受 block label 和该 block 的 live-after set,返回 live-before set,并更新每条 instruction 的 liveness information;- lattice 的
bottom,本例是 empty set; - lattice 的
join,本例是 set union。
由于存在回边,算法不断重新加入受影响的 block,直到所有 abstract states 都不再变化。这是 liveness analysis 在 cyclic CFG 上正确收敛的关键。
对 liveness 而言,transfer 的方向仍然是 block 内从后向前;它接收该 block 末尾由 successor union 得到的 live-after set,并返回 block 入口的 live-before set:
transfer(block, live-after-block):
live = live-after-block
从 block 的最后一条 instruction 到第一条 instruction 反向遍历:
记录当前 instruction 的 live-after = live
live = (live - writes(instruction)) ∪ reads(instruction)
记录当前 instruction 的 live-before = live
返回 live
因此,在 analyze_dataflow 中应把 CFG 的 transpose 传入,使原图中的 successor 成为 worklist transfer 所看到的 predecessor;当某个 block 的入口 state 发生变化时,把原 CFG 中从该 block 可达的 successor 重新加入 worklist。对循环 block5 → block7 → block5,这会持续传播 i、sum 与 rsp,直到整个 mapping 达到 fixed point,而不是在 cycle 上停止。
uncover_live 可以按下面的结构接入通用算法;uncover-live-tail 复用无环版本的 instruction transfer,并把每条 instruction 的 liveness 写回 block 的 info:
(define (uncover_live p)
(match p
[(CProgram info blocks)
(define G (build-cfg blocks))
(define live-before
(analyze_dataflow (transpose G)
(lambda (label live-after)
(define tail (dict-ref blocks label))
(define-values (tail^ live-before-block)
(uncover-live-tail tail live-after))
(set! blocks (dict-set blocks label tail^))
live-before-block)
(set) set-union))
(CProgram (dict-set info 'live-before live-before) blocks)]))
这里 block 的 live-after 不再由单一的下一 block 决定,而是由所有 CFG successor 的入口 state 做 set-union。transfer 的更新保持单调:每轮只增加由新路径发现的 locations,直到 fixed point。
参考资料
评论 (0)