我一直在阅读本地优化编译器技术,但我一直没有得到它们的实现方式.我们的想法是,优化器每次都会查看代码的"窗口",并以某种方式检测模式并用更优化的版本替换它们.
我的问题是,如何发现这些模式?(假设您的平台是一个虚拟机,可以输出组装计算机的汇编代码,如Schocken的Hack).
人们实际上是手动检查代码(使用控制流图或DAG或其他),然后收集所有识别的模式并将它们编码到优化器中?或者是否有自动方式.
例如,您在分析器中提供要优化的代码,并且它会喷出所述模式.如果是这样,怎么开始写一个呢?
compiler-construction design-patterns control-flow-graph vm-implementation peephole-optimization
所以我试图实现窥视孔优化,我从 a 开始Vec<LLStackInstruction> -> Vec<LLStackInstruction>,返回的列表被优化。(LL对于低级)我们的编译器被建模为抽象堆栈机,对于 init/assign,我们将 RHS 压入堆栈,将 LHS 的 addr 压入堆栈,然后弹出和 STR,但尝试将其减少为压入 RHS,然后存储到直接通过地址说明符来寻址,但我得到了一个非常丑陋的匹配,如下所示:(并且具有可变性)
pub fn peephole_optimiser(instrs: Vec<LLStackInstruction>) -> Vec<LLStackInstruction> {
let mut optimized_instructions: Vec<LLStackInstruction> = Vec::new();
let mut iter = instrs.iter().peekable();
while let Some(instruction) = iter.next() {
let window_iter = iter.clone();
let window: Vec<_> = [vec![instruction], window_iter.take(10).collect()].concat();
if let Some(LLStackInstruction::Push(Register::FP)) = window.get(0) {
if let Some(LLStackInstruction::Mov(Condition::None, r1, ArgType::Imm(n))) = window.get(1) {
if let Some(LLStackInstruction::Push(r2)) = window.get(2) {
if let Some(LLStackInstruction::Pop(_)) = window.get(3) {
if let …Run Code Online (Sandbox Code Playgroud) compiler-construction assembly compiler-optimization rust peephole-optimization