Mercurial > lcfOS
view python/transform.py @ 173:c1d2b6b9f9a7
Rework into passes
author | Windel Bouwman |
---|---|
date | Fri, 19 Apr 2013 12:42:21 +0200 |
parents | |
children | 3eb06f5fb987 |
line wrap: on
line source
from ir import * # Standard passes: class FunctionPass: def run(self, ir): """ Main entry point for the pass """ for f in ir.Functions: self.onFunction(f) def onFunction(self, f): """ Override this virtual method """ raise NotImplementedError() class BasicBlockPass(FunctionPass): def onFunction(self, f): for bb in f.BasicBlocks: self.onBasicBlock(bb) def onBasicBlock(self, bb): """ Override this virtual method """ raise NotImplementedError() class InstructionPass(BasicBlockPass): def onBasicBlock(self, bb): for ins in bb.Instructions: self.onInstruction(ins) def onInstruction(self, ins): """ Override this virtual method """ raise NotImplementedError() # Usefull transforms: class ConstantFolder(InstructionPass): def onInstruction(self, i): if type(i) is ImmLoad: i.target.constval = i.value print(type(i.value), i.value) elif type(i) is BinaryOperator: a = i.value1 b = i.value2 if hasattr(a, 'constval') and hasattr(b,'constval'): op = i.operation if op == '+': i2 = ImmLoad(i.result, a.constval + b.constval) print(i2) i.Parent.replaceInstruction(i, i2) elif op == '*': i2 = ImmLoad(i.result, a.constval * b.constval) print(i2) i.Parent.replaceInstruction(i, i2) elif op == '-': i2 = ImmLoad(i.result, a.constval - b.constval) print(i2) i.Parent.replaceInstruction(i, i2) class DeadCodeDeleter(InstructionPass): def onInstruction(self, ins): print(ins, ins.Users) if not ins.defs in ins.live_out: ins.Parent.removeInstruction(ins)