view python/instructionselector.py @ 271:cf7d5fb7d9c8

Reorganization
author Windel Bouwman
date Tue, 20 Aug 2013 18:56:02 +0200
parents 5f8c04a8d26b
children ea93e0a7a31e
line wrap: on
line source


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()