Mercurial > lcfOS
comparison python/transform.py @ 279:2ccd57b1d78c
Fix register allocator to do burn2 OK
author | Windel Bouwman |
---|---|
date | Sat, 12 Oct 2013 09:56:23 +0200 |
parents | ea93e0a7a31e |
children | 02385f62f250 |
comparison
equal
deleted
inserted
replaced
278:9fca39eebe50 | 279:2ccd57b1d78c |
---|---|
1 """ | 1 """ |
2 Transformation to optimize IR-code | 2 Transformation to optimize IR-code |
3 """ | 3 """ |
4 | 4 |
5 import logging | 5 import logging |
6 from ir import * | 6 import ir |
7 # Standard passes: | 7 # Standard passes: |
8 | 8 |
9 class FunctionPass: | 9 class FunctionPass: |
10 def __init__(self): | 10 def __init__(self): |
11 self.logger = logging.getLogger('optimize') | 11 self.logger = logging.getLogger('optimize') |
44 | 44 |
45 def onInstruction(self, ins): | 45 def onInstruction(self, ins): |
46 """ Override this virtual method """ | 46 """ Override this virtual method """ |
47 raise NotImplementedError() | 47 raise NotImplementedError() |
48 | 48 |
49 class BasePass(BasicBlockPass): | |
50 def onBasicBlock(self, bb): | |
51 pass | |
52 | |
49 # Usefull transforms: | 53 # Usefull transforms: |
50 class ConstantFolder(BasicBlockPass): | 54 class ConstantFolder(BasePass): |
51 def onBasicBlock(self, bb): | 55 def __init__(self): |
52 constMap = {} | 56 super().__init__() |
53 ins = [i for i in bb.Instructions if type(i) in [ImmLoad, BinaryOperator]] | 57 self.ops = {} |
54 for i in ins: | 58 self.ops['+'] = lambda x, y: x + y |
55 if type(i) is ImmLoad: | 59 self.ops['-'] = lambda x, y: x - y |
56 constMap[i.target] = i.value | 60 self.ops['*'] = lambda x, y: x * y |
57 elif type(i) is BinaryOperator: | 61 self.ops['<<'] = lambda x, y: x << y |
58 if i.value1 in constMap and i.value2 in constMap and i.operation in ['+', '-', '*', '<<']: | 62 |
59 op = i.operation | 63 def postExpr(self, expr): |
60 va = constMap[i.value1] | 64 if type(i) is BinaryOperator and i.operation in self.ops.keys() and type(i.a) is Const and type(i.b) is Const: |
61 vb = constMap[i.value2] | 65 op = i.operation |
62 if op == '+': | 66 va = i.a.value |
63 vr = va + vb | 67 vb = i.b.value |
64 elif op == '*': | 68 vr = self.ops[i.operation](va, vb) |
65 vr = va * vb | 69 return Const(vr) |
66 elif op == '-': | 70 else: |
67 vr = va - vb | 71 return expr |
68 elif op == '<<': | |
69 vr = va << vb | |
70 else: | |
71 raise NotImplementedError() | |
72 constMap[i.result] = vr | |
73 i.removeDef(i.result) | |
74 i2 = ImmLoad(i.result, vr) | |
75 logging.debug('Replacing {} with {}'.format(i, i2)) | |
76 i.Parent.replaceInstruction(i, i2) | |
77 | 72 |
78 | 73 |
79 class DeadCodeDeleter(BasicBlockPass): | 74 class DeadCodeDeleter(BasicBlockPass): |
80 def onBasicBlock(self, bb): | 75 def onBasicBlock(self, bb): |
81 def instructionUsed(ins): | 76 def instructionUsed(ins): |