diff python/c3/codegenerator.py @ 174:3eb06f5fb987

Added memory alloc for locals
author Windel Bouwman
date Fri, 19 Apr 2013 19:22:52 +0200
parents 5a7d37d615ee
children a51b3c956386
line wrap: on
line diff
--- a/python/c3/codegenerator.py	Fri Apr 19 12:42:21 2013 +0200
+++ b/python/c3/codegenerator.py	Fri Apr 19 19:22:52 2013 +0200
@@ -6,6 +6,7 @@
    """ Generates intermediate code from a package """
    def gencode(self, pkg):
       assert type(pkg) is astnodes.Package
+      self.varMap = {} # Maps variables to storage locations.
       self.builder = ir.Builder()
       m = ir.Module(pkg.name)
       self.builder.setModule(m)
@@ -25,6 +26,13 @@
             bb = self.builder.newBB()
             f.entry = bb
             self.builder.setBB(bb)
+            # generate room for locals:
+
+            for sym in s.scope:
+               v = self.builder.newTmp(sym.name)
+               self.builder.addIns(ir.Alloc(v))
+               self.varMap[sym] = v
+
             self.genCode(s.body)
             # TODO handle return?
             self.builder.addIns(ir.Return())
@@ -38,7 +46,9 @@
             self.genCode(s)
       elif type(code) is astnodes.Assignment:
          re = self.genExprCode(code.rval)
-         self.builder.addIns(ir.Store(code.lval, re))
+         print(code.lval)
+         loc = self.varMap[code.lval.target]
+         self.builder.addIns(ir.Store(loc, re))
       elif type(code) is astnodes.IfStatement:
          bbtrue = self.builder.newBB()
          bbfalse = self.builder.newBB()
@@ -56,7 +66,11 @@
       elif type(code) is astnodes.EmptyStatement:
          pass
       elif type(code) is astnodes.ReturnStatement:
-         pass
+         if code.expr:
+            re = self.genExprCode(code.expr)
+            self.builder.addIns(ir.Return(re))
+         else:
+            self.builder.addIns(ir.Return())
       else:
          print('Unknown stmt:', code)
    def genCondCode(self, expr, bbtrue, bbfalse):
@@ -79,8 +93,7 @@
             i = ir.ConditionalBranch(ta, expr.op, tb, bbtrue, bbfalse)
             self.builder.addIns(i)
          else:
-            raise NotImlementedError()
-            print('Unknown cond', expr)
+            raise NotImlementedError('Unknown condition {0}'.format(expr))
       elif type(expr) is astnodes.Literal:
          if expr.val:
             self.builder.addIns(ir.BranchInstruction(bbtrue))
@@ -109,7 +122,8 @@
          return tmp
       elif type(expr) is astnodes.VariableUse:
          tmp = self.builder.newTmp()
-         i = ir.Load(expr, tmp)
+         loc = self.varMap[expr.target]
+         i = ir.Load(loc, tmp)
          self.builder.addIns(i)
          return tmp
       elif type(expr) is astnodes.Literal: