view python/ir/builder.py @ 275:6f2423df0675

Fixed serve arm-as
author Windel Bouwman
date Sat, 14 Sep 2013 17:29:10 +0200
parents 5ec7580976d9
children
line wrap: on
line source

from . import Block, Function, Statement, Temp

class NamedClassGenerator:
   def __init__(self, prefix, cls):
      self.prefix = prefix
      self.cls = cls
      def NumGen():
         a = 0
         while True:
            yield a
            a = a + 1
      self.nums = NumGen()

   def gen(self, prefix=None):
      if not prefix:
         prefix = self.prefix
      return self.cls('{0}{1}'.format(prefix, self.nums.__next__()))


class Builder:
    """ Base class for ir code generators """
    def __init__(self):
        self.prepare()

    def prepare(self):
        self.newTemp = NamedClassGenerator('reg', Temp).gen
        self.newBlock = NamedClassGenerator('block', Block).gen
        self.bb = None
        self.m = None
        self.fn = None
        self.loc = None

    # Helpers:
    def setModule(self, m):
        self.m = m

    def newFunction(self, name):
      f = Function(name)
      self.m.addFunc(f)
      return f

    def setFunction(self, f):
        self.fn = f
        self.bb = f.entry if f else None

    def setBlock(self, b):
        self.bb = b

    def setLoc(self, l):
        self.loc = l

    def emit(self, i):
        assert isinstance(i, Statement)
        i.debugLoc = self.loc
        if not self.bb:
            raise Exception('No basic block')
        self.bb.addInstruction(i)