Essentials of Compilation:布尔值与条件分支
Essentials of Compilation:布尔值与条件分支
本章在
LangVar上加入 Boolean、logical operation 和if,并说明 type checking 与 conditional control flow 如何改变 compiler pipeline。
TL;DR
LangVar只有 integer;LangIf增加 Boolean、comparison、logical operation 和 conditional expression。and/or需要 short-circuit evaluation,不能简单当作普通 primitive operation 处理。- 两种 value type 要求 compiler 在编译期拒绝错误的 operator application,因此增加 type checker。
if让 control flow 不再是单一 depth-first sequence,explicate_control必须生成带条件跳转的 basic block graph。- 后续 pass 通过
shrink、explicate_control、select_instructions和 conditional jump 逐步把高层条件转换为 x86。
名词解释
| 名词 | 含义 | 本章对应物 |
|---|---|---|
| Boolean | 只有 true / false 的 value type | Racket #t、#f |
| short-circuit evaluation | 根据左 operand 直接决定结果时跳过右 operand | and、or |
| type checking | 预测 expression 的 type 并检查 operator 约束 | type-check-Lif |
| semantic analysis | 在 syntax 之后验证 program 的语义约束 | type checker 所属阶段 |
| conditional control flow | 根据 condition 选择不同执行路径 | if 与 conditional goto |
目录
| 章节 | 说明 |
|---|---|
| Booleans and Conditionals | 从 LangVar 扩展出 LangIf |
The LangIf Language | Boolean、comparison、logical operation 和 if |
| Interpreter | short-circuit 与条件求值 |
Type Checking LangIf Programs | 编译期预测 type 并拒绝错误 program |
| 后续 compiler pipeline | LangCIf、LangXIf 与 conditional compilation |
Booleans and Conditionals
LangVar 只有一种 value:integer。本章增加第二种 value——Boolean,从而创建 LangIf language。Boolean value true 和 false 在 Racket 中分别写作 #t 和 #f。
LangIf 包含多个涉及 Boolean 的 operation:and、or、not、eq?、< 等,以及 if expression。加入 if 后,program 可以拥有非平凡的 control flow,这会影响 explicate_control 和 liveness analysis。
由于现在有两种 value,还必须处理对错误 value kind 应用 operation 的情况,例如:
(not 1)
对于这种情况,language design 有两种选择:signal 一个 error,或者为 operation 提供更宽的 interpretation。Racket 根据 operation 和 value kind 混合使用两种选择。例如,(not 1) 的结果是 #f,因为 Racket 把非零 integer 当作 #t。另一方面,(car 1) 会产生 runtime error,因为 car 要求 argument 是 pair。
Typed Racket 也采用类似 Racket 的设计,只是许多 error detection 在 compile time 而不是 runtime 发生。Typed Racket 接受 (not 1);但对 (car 1) 会报告 compile-time error,因为 argument type 应为 (Listof T) 或 (Pairof T1 T2)。
LangIf 像 Typed Racket 一样在 compilation 期间进行 type checking。在后面的 Dynamic Typing 章节会研究另一种选择:像 Racket 一样的 dynamically typed language。LangIf 是 Typed Racket 的一个 subset,但对某些 operation 更 restrictive,例如拒绝 (not 1)。
本章先定义 LangIf 的 syntax 和 interpreter,再介绍 type checking 并定义 LangIf 的 type checker。之后将 LangCVar 扩展为 LangCIf,将 LangXInt 扩展为 LangXIf。剩余部分说明 Boolean 和 conditional control flow 如何改变已有 compiler pass,以及如何加入新的 pass。
The LangIf Language
LangIf 包含全部 LangVar、Boolean literals #t 和 #f,以及 if expression。Operator 集合扩展为:
- logical operator:
and、or、not; eq?,用于比较 integer 或 Boolean 是否相等;<=、>、>=等 integer comparison operation。
为了统一表示 primitive operation,我们把它们的 abstract syntax 组织为一条 grammar rule。这意味着 grammar 不再检查 operator arity 是否与 argument 数量匹配;这个责任移动到 LangIf 的 type checker。
LangIf concrete syntax
bool ::= #t | #f
cmp ::= eq? | < | <= | > | >=
Exp ::= bool
| (and Exp Exp) | (or Exp Exp) | (not Exp)
| (cmp Exp Exp) | (if Exp Exp Exp)
LangIf ::= Exp
LangIf abstract syntax
op ::= cmp | and | or | not
Exp ::= Bool(bool) | Prim(op, Exp...) | If(Exp, Exp, Exp)
LangIf ::= Program('(), Exp)
在前面的 grammar 中,LangVar 的 syntax 作为灰色基础被保留;LangIf 只增加 Boolean 和 conditional constructs。
Interpreter
LangIf 的 interpreter 继承 LangVar interpreter。Boolean literal 分别求值为对应的 Boolean value。Conditional expression If(e1, e2, e3) 先求值 e1,再根据 e1 产生 #t 还是 #f,选择求值 e2 或 e3。
Logical operation and、or 和 not 按 propositional logic 行为;此外,and 和 or 执行 short-circuit evaluation:对 (and e1 e2),如果 e1 求值为 #f,则不求值 e2;对 (or e1 e2),如果 e1 求值为 #t,则不求值 e2。
primitive operation 数量增加后,interpreter 如果逐一展开会变得重复。因此,把每个 operator 的差异提取到 interp_op method 中;and 和 or 因为具有 short-circuit behavior,仍然单独处理。
(define interp-Lif-class
(class interp-Lvar-class
(super-new)
(define/public (interp_op op) ...)
(define/override ((interp_exp env) e)
(define recur (interp_exp env))
(match e
[(Bool b) b]
[(If cnd thn els)
(match (recur cnd)
[#t (recur thn)]
[#f (recur els)])]
[(Prim 'and (list e1 e2))
(match (recur e1)
[#t (match (recur e2) [#t #t] [#f #f])]
[#f #f])]
[(Prim 'or (list e1 e2))
(define v1 (recur e1))
(match v1
[#t #t]
[#f (match (recur e2) [#t #t] [#f #f])])]
[(Prim op args)
(apply (interp_op op) (for/list ([e args]) (recur e)))]
[else ((super interp_exp env) e)]))
))
(define (interp_Lif p)
(send (new interp-Lif-class) interp_program p))
interp_op 中的 operator semantics 如下:
(define/public (interp_op op)
(match op
['+ fx+]
['- fx-]
['read read-fixnum]
['not (lambda (v) (match v [#t #f] [#f #t]))]
['eq? (lambda (v1 v2)
(cond [(or (and (fixnum? v1) (fixnum? v2))
(and (boolean? v1) (boolean? v2))
(and (vector? v1) (vector? v2)))
(eq? v1 v2)]))]
['< (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
['<= (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
['> (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
['>= (lambda (v1 v2)
(cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
[else (error 'interp_op "unknown operator")]))
Type Checking LangIf Programs
可以用两种互补方式理解 type checking。第一种是:type checker 预测 program 中每个 expression 将产生的 value type。LangIf 目前只有两种 type:Integer 和 Boolean。
例如,下面的 expression 应产生 Integer:
(+ 10 (- (+ 12 20)))
下面的 expression 应产生 Boolean:
(and (not #f) #t)
第二种理解是:type checking 强制规定哪些 operator 可以应用于哪些 value。例如,下面 expression 应被 type checker 拒绝:
(not (+ 10 (- (+ 12 20))))
因为 subexpression (+ 10 (- (+ 12 20))) 的 type 是 Integer,而 not 的 argument 必须是 Boolean。
我们使用 class 和 method 实现 type checker,因为它们提供了 open recursion,使后续扩展 type checker 时能够复用已有 code,这与 interpreter 使用 class / method 的理由相同。
LangVar subset 的 type checker 独立放在一个 class 中;LangIf 的 type checker 继承它。每个 type checker 都是对 AST 做 structural recursion 的 function。给定 input expression e,type checker 要么 signal error,要么返回 expression 及其 type。返回 expression 是因为某些情况下需要改变或更新 expression。
LangVar 中,integer constant 的 type 是 Integer;variable 的 type 从 environment 中查找。遇到 let 时,先 type check initializing expression 得到 type T,然后在用于 type check body 的 environment 中把 x 关联到 T。遇到 primitive operator 时,递归分析 arguments,再调用 type_check_op 检查 argument types 是否被允许。
(define type-check-Lvar-class
(class object%
(super-new)
(define/public (operator-types)
'((+ . ((Integer Integer) . Integer))
(- . ((Integer Integer) . Integer))
(read . (() . Integer))))
(define/public (type-equal? t1 t2) (equal? t1 t2))
(define/public (check-type-equal? t1 t2 e)
(unless (type-equal? t1 t2)
(error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
(define/public (type-check-op op arg-types e)
(match (dict-ref (operator-types) op)
[`(,param-types . ,return-type)
(for ([at arg-types] [pt param-types])
(check-type-equal? at pt e))
return-type]
[else (error 'type-check-op "unrecognized ~a" op)]))
(define/public (type-check-exp env)
(lambda (e)
(match e
[(Int n) (values (Int n) 'Integer)]
[(Var x) (values (Var x) (dict-ref env x))]
[(Let x e body)
(define-values (e^ Te) ((type-check-exp env) e))
(define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
(values (Let x e^ b) Tb)]
[(Prim op es)
(define-values (new-es ts)
(for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
(values (Prim op new-es) (type-check-op op ts e))]
[else (error 'type-check-exp "couldn't match" e)])))
(define/public (type-check-program e)
(match e
[(Program info body)
(define-values (body^ Tb) ((type-check-exp '()) body))
(check-type-equal? Tb 'Integer body)
(Program info body^)]))
))
LangIf 的 type checker 在 LangVar 的基础上增加 Boolean constant、eq? 和 if 的规则:Boolean constant 的 type 是 Boolean;eq? 要求两个 arguments type 相同,并返回 Boolean;if 的 condition 必须是 Boolean,两个 branch 必须拥有相同 type。
(define type-check-Lif-class
(class type-check-Lvar-class
(super-new)
(inherit check-type-equal?)
(define/override (operator-types)
(append '((and . ((Boolean Boolean) . Boolean))
(or . ((Boolean Boolean) . Boolean))
(< . ((Integer Integer) . Boolean))
(<= . ((Integer Integer) . Boolean))
(> . ((Integer Integer) . Boolean))
(>= . ((Integer Integer) . Boolean))
(not . ((Boolean) . Boolean)))
(super operator-types)))
(define/override (type-check-exp env)
(lambda (e)
(match e
[(Bool b) (values (Bool b) 'Boolean)]
[(Prim 'eq? (list e1 e2))
(define-values (e1^ T1) ((type-check-exp env) e1))
(define-values (e2^ T2) ((type-check-exp env) e2))
(check-type-equal? T1 T2 e)
(values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
[(If cnd thn els)
(define-values (cnd^ Tc) ((type-check-exp env) cnd))
(define-values (thn^ Tt) ((type-check-exp env) thn))
(define-values (els^ Te) ((type-check-exp env) els))
(check-type-equal? Tc 'Boolean e)
(check-type-equal? Tt Te e)
(values (If cnd^ thn^ els^) Te)]
[else ((super type-check-exp env) e)])))
))
(define (type-check-Lif p)
(send (new type-check-Lif-class) type-check-program p))
例如,下面的 program 会被接受:
(if (eq? 1 1) 42 (+ 1 2))
而下面的 program 会被拒绝,因为 not 的 argument 是 Integer:
(not (+ 10 32))
练习
创建 10 个新的 LangIf test program,其中一半包含 type error。预期产生 type error 的 test 旁边创建同名 .tyerr 空文件。其余 test 不应有 type error。将 tests 交给 type-check-Lif,运行脚本验证 type checker 的判断符合预期。
后续 compiler pipeline
接下来的章节会把 LangCVar 扩展为 LangCIf,在 Exp 中增加 logical / comparison operator,并在 Arg 中增加 #t、#f;同时把 LangXInt 扩展为 LangXIf,加入 condition code、jump label 和 conditional jump instruction。
Boolean 和 conditional control flow 会改变已有 compiler pass:shrink 把部分 operator 翻译成其他 operator,减少后续 pass 需要处理的 operator 数量;新的 explicate_control 负责把 if 翻译为 conditional goto,构造 basic block graph;liveness analysis 则需要处理 conditional goto 的多个 successor。
The LangCIf Intermediate Language
LangCIf 在 LangCVar 的基础上,把 logical 与 comparison operators 加入 Exp,把 #t、#f 加入 Arg,并在 Tail 中增加 goto 与受限的 if statement。if 的 condition 必须是 comparison,两个分支必须是 goto;这种限制使它可以直接翻译成 x86。CProgram 保存 label 到 Tail 的映射,goto 将控制转移到相应 label 的 basic block。
Atom ::= Boolean
cmp ::= eq? | < | <= | > | >=
Exp ::= (not Atom) | (cmp Atom Atom)
Tail ::= goto label;
| if (cmp Atom Atom) goto label; else goto label;
The LangXIf Language
LangXIf 是本书使用的 x86 子集,增加 logical operation、comparison 和 conditional jump。x86 没有直接的 logical negation instruction,但可以利用 xorq:对 Boolean 的单 bit 表示,xorq $1 会翻转该 bit。
not e ↦ movq e, dst
xorq $1, dst
comparison 使用 cmpq 设置特殊的 EFLAGS register,再用 setcc 将结果写入 single-byte register,最后用 movzbq 扩展到普通 64-bit register。注意 cmpq 的 operand 顺序是反的:要测试 x < y,写作 cmpq y, x。condition code 包括 e、ne、l、le、g、ge。
conditional jump jcc label 根据 EFLAGS 是否符合 condition code 跳转,否则 fall through 到下一条 instruction。通常它紧跟在 cmpq 后面。
Shrink the LangIf Language
shrink 把容易用其他构造表达的 features 在 compiler front-end 中消除:
(and e1 e2) ↦ (if e1 e2 #f)
(or e1 e2) ↦ (if e1 #t e2)
这样后续 pass 无需处理 and 与 or。但需要注意,某些等价改写会降低效率;例如把 subtraction 改写成 addition 加 negation,会从一条 subq 变成 negq 与 addq 两条 instruction。
Uniquify Variables
uniquify 将每个 variable binding 重命名为唯一名称。它维护从源变量名到新变量名的环境:遇到 Let 时为 binder 生成 fresh name,递归处理绑定表达式时使用旧环境,递归处理 body 时把新映射加入环境;遇到 Var 时从环境查找对应 fresh name。
该 pass 的重要性质是:两个不同 lexical binding 即使同名,也不会在后续 pass 中混淆;同一个 binding 的所有引用仍然使用同一个新名字。
Remove Complex Operands
remove_complex_operands 将 expression 转换为 A-normal form(ANF),使 primitive operation 的 operands 都是 atomic。它递归返回一对结果:一个保持语义的 expression,以及一个把该 expression 绑定到 fresh temporary 的 atomic expression。
例如:
(+ (read) (- 10 32))
会被改写为类似:
(let ([tmp1 (read)])
(let ([tmp2 (- 10 32)])
(+ tmp1 tmp2)))
需要保留 evaluation order,并避免为已经 atomic 的表达式无谓地增加 let。
对于 if,三个 subexpression 都可以是 complex expression,但 if 的 condition 不能被简单替换成一个 temporary 后再统一处理:condition 可能包含 effect,且必须只在真正到达该条件时执行。每个 branch 中为 ANF 生成的 temporary 也只能在对应 branch 内初始化,否则会把原本受 condition 控制的 effect 提前执行。Python edition 为此引入 Begin expression,用于先执行 branch 内的 statement list,再返回 branch result。
Explicate Control
explicate_control 把 LangIf 翻译为 LangCIf。难点在于 expression tree 中的 if 可能出现在 condition、then/else branch、binding value 或 primitive argument 中,而目标语言用 basic blocks 和 control transfer 表示控制流。
核心辅助函数是:
explicate_tail:把 expression 编译成最终返回值的Tail;explicate_assign:把 expression 编译为给某个 variable 赋值的 statement sequence;explicate_pred:把 Boolean condition 编译成两个 continuation(then 与 else);create_block:把可能被多次使用的 continuation 放入带 label 的 basic block,并返回goto。
一个 if expression 的两条分支通常分别生成 block,然后 condition block 根据 comparison 跳转:
if (eq? t 0) goto block_then; else goto block_else;
不能简单地把每个子树分别编译后拼接,因为 condition 的求值必须先于分支,且同一 continuation 可能被多个路径共享。explicate_pred 通过 continuation 参数表达“条件为真/假时接下来要做什么”,从而把 tree 变成 control-flow graph。
原文给出的关键例子是 condition 中再次嵌套 if:
(if (if (< x 1) (eq? x 0) (eq? x 2))
(+ y 2)
(+ y 10))
朴素做法会先把内层 comparison 的结果写进 temporary,再对 temporary 做第二次 cmpq,例如:
cmpq $1, x
setl %al
movzbq %al, tmp
cmpq $1, tmp
je then_branch_1
jmp else_branch_1
setl 和 movzbq 在这里是多余的;更好的结果是让 comparison 直接紧邻 conditional jump:
cmpq $1, x
jl then_branch_1
jmp else_branch_1
如果把 outer if 推入 inner if,虽然能得到这种形式,却会复制 (+ y 2) 和 (+ y 10) 两个 branch。compiler 不能依赖这种复制,因为 branch 可能很大。正确做法是把 control-flow tree 改成 graph:每个 branch 只生成一次 basic block,多个路径通过 label 和 goto 共享它们。例如该例的 CFG 可组织为:
start:
if (< x 1) goto block_4; else goto block_5;
block_4:
if (eq? x 0) goto block_2; else goto block_3;
block_5:
if (eq? x 2) goto block_2; else goto block_3;
block_2:
return (+ y 2);
block_3:
return (+ y 10);
因此 explicate_pred 不只是“把 Boolean expression 翻译成比较”:它接收 then/else continuations,并在遇到 nested if 时继续分析 condition;create_block 则把需要共享的 continuation 物化为带 label 的 block。
Racket 版 explicate_pred 的基本分派可以写成下面的形式:
(define (explicate_pred cnd thn els)
(match cnd
[(Var x)
(IfStmt (Prim 'eq? (list (Var x) (Bool #t)))
(create_block thn)
(create_block els))]
[(Let x rhs body)
(explicate_assign rhs x
(explicate_pred body thn els))]
[(Prim 'not (list e))
(explicate_pred e els thn)]
[(Prim op es)
#:when (or (eq? op 'eq?) (eq? op '<))
(IfStmt (Prim op es)
(create_block thn)
(create_block els))]
[(Bool b) (if b thn els)]
[(If cnd^ thn^ els^)
(define thn-block (delay (explicate_pred thn^ thn els)))
(define els-block (delay (explicate_pred els^ thn els)))
(explicate_pred cnd^ thn-block els-block)]
[else (error "explicate_pred unhandled case" cnd)]))
其中 thn 与 els 是 continuation,而不是需要立即执行的 expression。遇到 nested if 时,内层两个 branch 只通过 delay/create_block 在真正需要时生成;遇到 not 时交换两个 continuation;遇到 comparison 时才创建 IfStmt。例如 (and e1 e2) 经过 shrink 后,e1 为 false 直接进入 else,只有 e1 为 true 才继续分析 e2,因此 short-circuit behavior 不会丢失。
当 and/or 尚未 shrink 时,explicate_control 还必须保留 short-circuit evaluation;本书推荐先 shrink,使 logical operation 变成 if 后再进行控制流显式化。
Explicate Control 与 Shrink 的交互
shrink 对 and、or 的展开方式会直接影响 explicate_control 生成的 code quality。以如下 program 为例:
(if (and (eq? (read) 0) (eq? (read) 1))
0
42)
理想的 control-flow graph 应让第一个 comparison 成功后才执行第二次 read,并让两个失败路径共享同一个 else block:
start:
tmp1 = (read)
if (eq? tmp1 0) goto block40
else goto block39
block40:
tmp2 = (read)
if (eq? tmp2 1) goto block38
else goto block39
block38:
return 0
block39:
return 42
这段 output 同时体现两个约束:and 必须保持 short-circuit semantics,第二个 operand 不能提前求值;explicate_pred 应直接沿着 eq? comparison 生成 conditional jump,而不是把每个 Boolean 结果先写入 temporary 再重新比较。若 outer continuation 被多个路径使用,必须通过共享 label 表示 graph,而不能复制整棵 branch subtree。
Select Instructions
select_instructions 将 LangCIf 翻译为 pseudo-x86。整数用 0 与 1 表示 Boolean。comparison 的基本翻译是:
cmpq right, left
setcc %al
movzbq %al, dst
not 使用 movq 加 xorq $1。goto 翻译为 jmp,conditional goto 翻译为紧随 cmpq 的 jcc。因此,eq?、<、<=、>、>= 的 compiler code 主要差别在 condition code。
具体规则如下。not 的 operand 与 destination 相同时,可以直接原地翻转;否则先复制再翻转:
# x = (not x)
xorq $1, x
# x = (not y)
movq y, x
xorq $1, x
Comparison 的结果先写入 byte register,再用 movzbq 扩展为完整的 Boolean value:
# x = (eq? y z)
cmpq z, y
sete %al
movzbq %al, x
<、<=、>、>= 分别把 sete 换成 setl、setle、setg、setge。在 tail position 中,comparison 不必物化为 Boolean;可以直接比较并跳转:
# if (eq? y z) goto then; else goto els
cmpq z, y
je then
jmp els
由于 AT&T syntax 的 cmpq A, B 实际计算 B - A 并设置 flags,source expression 的 (eq? y z) 必须对应 cmpq z, y;交换两个 operands 时也必须同步调整 condition code。
Register Allocation for Conditional Control Flow
加入 basic blocks 后,liveness analysis 不能只沿 instruction list 的线性后继传播。每个 block 的最后一条 instruction 可能有一个或两个 successor:
jmp label的 successor 是目标 block;jcc label的 successors 是目标 block 和 fall-through block;- return 没有 successor。
因此需要先构造 block 的 successor 信息,再按合适的顺序反复处理 blocks,直到 live sets 达到 fixed point。block 末尾的 live-after set 是所有 successor 在入口处 live set 的 union。
Interference graph 的构造规则与前文相同,但必须考虑 conditional jump 的多个 successor。cmpq、setcc 和 movzbq 还带来特殊约束:setcc 的目标必须是 byte register,movzbq 的源必须是 byte register,cmpq 的 destination 不能是 immediate。
Patch Instructions 与 Prelude
patch_instructions 负责修复 x86 不允许的 operand 组合。例如不能把两个 memory locations 直接作为 cmpq 的 operands;需要引入 temporary register。对于 movzbq,若目标不是合法 64-bit register,也要先移动到 register 再继续。
prelude_and_conclusion 生成 main 的 function prelude 与 conclusion:建立 frame pointer、保存实际使用的 callee-saved registers、为 stack locations 分配空间、跳转到 start,最后恢复 registers 并 retq。
Challenge:Optimize Blocks and Remove Jumps
Optimize Blocks
朴素的 explicate_control 在 continuation 可能被使用多次时就创建 block,但某些 continuation 最终可能根本不会被使用。例如 if #t 会丢弃 else continuation,却可能已经为它建立了 block。
例如下面的 program 中,外层 if 的 condition 恒为 #t,所以 (read) 分支会被执行,而其余两个 else 分支实际上都不可达:
(let ([y (if #t
(read)
(if (eq? (read) 0)
777
(let ([x (read)])
(+ 1 x))))])
(+ y 2))
如果立即为 continuation 创建 basic block,生成结果会包含两个没有 predecessor 的 block。使用 lazy evaluation 后,只有被真正 force 的 continuation 才会物化;该例可缩减为:
start:
y = (read);
goto block_5;
block_5:
return (+ y 2);
可选优化是使用 lazy evaluation:用 promise 延迟创建 block,直到 continuation 确实被 force。如果 force 后发现结果已经是 goto,则直接复用已有 label;否则才创建新 block。这样可以减少未使用 block,也能消除只包含 goto 的 trivial block。
原文建议将 continuation 表示成 Racket racket/promise。delay 把 block 的生成推迟,force 第一次执行时计算并缓存结果,之后再次 force 直接返回缓存值;如果传入的值本来不是 promise,force 则原样返回。create_block 可以按下面的逻辑实现:
(define (create-block tail)
(delay
(define t (force tail))
(match t
[(Goto label) (Goto label)]
[else
(let ([label (gensym 'block)])
(set! basic-blocks
(cons (cons label tail) basic-blocks))
(Goto label))])))
create-block 自身也要返回一个 promise:force 它时先 force 原始 promise;如果得到的是 Goto,说明 block 已经加入 basic-blocks,于是直接复用该 Goto;否则才创建新 label 并把 continuation 加入 basic-blocks。Racket 的 promise 会缓存第一次 force 的结果,因此同一个 promise 多次 force 不会重复创建 block。
Remove Jumps
若一个 block 只有一个前驱,且前驱以 goto 跳到该 block,就可以把目标 block 合并到前驱末尾,移除运行时 jump。remove_jumps 需要识别这种情况,更新 block 内容,并继续处理可能形成的新合并机会。
例如,优化前 start 只有一个 successor block_5,且没有其他路径跳到 block_5:
start:
callq read_int
movq %rax, %rcx
jmp block_5
block_5:
movq %rcx, %rax
addq $2, %rax
jmp conclusion
可以把 block_5 合并到 start,得到:
start:
callq read_int
movq %rax, %rcx
movq %rcx, %rax
addq $2, %rax
jmp conclusion
对于条件分支,只有在目标 block 确实只有一个 predecessor 时才能做同样的合并;否则删除 goto 会改变另一路径的控制流。实现 remove_jumps 时,可以先计算每个 label 的 predecessor 集合,再只合并 singleton predecessor 的 trivial block;随后重新扫描新形成的 block,以处理连续的可合并跳转。
也可以分成两个阶段实现:先为每个 label 计算一个“改进后的目标 label”映射。若某个 block 只有一个 goto,就把它映射到该 goto 的目标,并沿着连续的 trivial block 继续追踪;若 block 含有真正的 statements,则映射到自身。第二阶段遍历所有 block,重写其中每个 goto 的目标,跳过中间的 trivial block。需要反复传播映射,直到一个 label 指向第一个 non-trivial block。
另一种局部实现是在已知 predecessor 唯一时直接合并:把目标 block 的 statements 追加到 predecessor,删除 predecessor 末尾的 goto,然后重新检查新形成的 block。只有当目标 block 确实只有一个 predecessor 时才能这样做;否则合并会改变其他路径的控制流。
实现时容易遗漏的约束
type-check-op 不能只检查 operator 是否存在,还必须检查 argument 数量和每个 argument 的 type。eq? 是一个例外:它要求两个 argument 的 type 相同,但返回 Boolean;两个 branch 的 type 也必须相同,不能因为 condition 已经是 Boolean 就跳过这一检查。
在 explicate_control 中,explicate_pred 的 continuation 是语义的一部分。若 condition 是 if 或包含 effect 的 expression,必须先执行 condition 的 effect,再进入 then/else continuation;不能把两个 continuation 提前求值。create_block 的 memoization 也很重要:相同 continuation 应复用同一个 label,否则会无谓地复制 CFG。
在 pseudo-x86 到真实 x86 的阶段,comparison 的 operand 顺序必须保持一致:源语言的 (< x y) 通常对应 cmpq y, x,然后使用 jl;如果交换 cmpq 的两个 operands,就必须同步改变 condition code。setcc 只接受 single-byte register,之后要用 movzbq 将结果扩展为完整的 64-bit Boolean value。
条件 control flow 还会影响 liveness 的边界条件。一个 jcc 的 live-after set 不是简单的下一条 instruction 的 live-before,而是目标 block 与 fall-through block 两个入口 live set 的 union;只有在所有 blocks 的数据流方程收敛后,才能安全构造 interference graph。
本章练习
- 创建 10 个新的 test programs,其中一半应有 type error;为它们创建同名
.tyerr文件,并验证type-check-Lif能正确区分两类程序。 - 实现
shrink,把and与or翻译成if;创建 4 个涉及这两个 operator 的 tests,并运行 compiler。 - 更新
uniquify_exp,处理 Boolean constants 和if,并测试输出。 - 为
rco_atom与rco_exp增加 Boolean constants 和if的 cases;创建 3 个 tests 覆盖该 pass。 - 实现
explicate_control中 Boolean constants、if和 predicate context 的处理;创建 tests 覆盖所有新增 cases。 - 扩展
select_instructions以处理本章新增 language features,并对全部 test programs 运行 pseudo-x86 interpreter。 - 更新
uncover_live,对 program 中的每个 basic block 做 liveness analysis,并检查 running example 的 live-after sets。 - 更新
build_interference与allocate_registers,检查生成的 interference graph 与书中图示一致。 - 更新
patch_instructions,对新增的 conditional instructions 做修补,并运行 tests。 - 改进
explicate_control,消除 trivial blocks,在多个示例程序上检查效果。 - 实现
remove_jumps,当目标 block 只有一个 predecessor 时,将其合并到前驱 block;在多个 test programs 上确认 basic blocks 被正确合并。
Further Reading
explicate_control 的算法与 Dybvig course notes 中的 expose-basic-blocks pass 有关,也与 continuation-passing style、short-cut Boolean evaluation 和 case-of-case transformation 存在联系。
参考资料
评论 (0)