diff python/instructionselector.py @ 269:5f8c04a8d26b

Towards better modularity
author Windel Bouwman
date Sun, 18 Aug 2013 17:43:18 +0200
parents
children ea93e0a7a31e
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/python/instructionselector.py	Sun Aug 18 17:43:18 2013 +0200
@@ -0,0 +1,60 @@
+
+import ir
+import irmach
+
+def genTemps():
+    n = 900
+    while True:
+        yield 't{}'.format(n)
+        n = n + 1
+
+class InstructionSelector:
+    """
+        Base instruction selector. This class must be overridden by
+        backends.
+    """
+    def newTmp(self):
+        return self.temps.__next__()
+
+    def getTempReg(self, tmp):
+        if tmp not in self.tempMap:
+            self.tempMap[tmp] = self.newTmp()
+        return self.tempMap[tmp]
+
+    def munchProgram(self, p):
+        # Entry point for instruction selection
+        self.temps = genTemps()
+        assert isinstance(p, ir.Module)
+        self.result = []
+        self.targets = {}
+        self.tempMap = {} # Mapping from temporaries to infinite register
+        for f in p.Functions:
+            # First define labels:
+            for bb in f.BasicBlocks:
+                itgt = self.makeIns('{}:'.format(bb.name))
+                self.targets[bb] = itgt
+            for bb in f.BasicBlocks:
+                self.emit2(self.targets[bb])
+                for i in bb.Instructions:
+                    self.munchStm(i)
+                bb.machIns = self.result
+        return self.result
+
+    def makeIns(self, *args, **kwargs):
+        return irmach.AbstractInstruction(*args, **kwargs)
+
+    def emit(self, *args, **kwargs):
+        """ Abstract instruction emitter """
+        i = self.makeIns(*args, **kwargs)
+        return self.emit2(i)
+
+    def emit2(self, i):
+        self.result.append(i)
+        return i
+
+    def munchStm(self, s):
+        raise NotImplementedError()
+
+    def munchExpr(self, e):
+        raise NotImplementedError()
+