attempting to add overflow setting in ISACaller
[soc.git] / src / soc / decoder / pseudo / parser.py
index 8613d2a460fed4d954e3b7775d611369b711fb62..ddd49fabeeb9c4fff5edb6623d37a4c664d0d965 100644 (file)
@@ -23,7 +23,7 @@ import ast
 # Helper function
 
 
-def Assign(left, right):
+def Assign(autoassign, assignname, left, right, iea_mode):
     names = []
     print("Assign", left, right)
     if isinstance(left, ast.Name):
@@ -43,7 +43,31 @@ def Assign(left, right):
         ass_list = [ast.AssName(name, 'OP_ASSIGN') for name in names]
         return ast.Assign([ast.AssTuple(ass_list)], right)
     elif isinstance(left, ast.Subscript):
-        return ast.Assign([left], right)
+        ls = left.slice
+        if (isinstance(ls, ast.Slice) and isinstance(right, ast.Name) and
+            right.id == 'undefined'):
+            # undefined needs to be copied the exact same slice
+            right =  ast.Subscript(right, ls, ast.Load())
+            return ast.Assign([left], right)
+        res = ast.Assign([left], right)
+        if autoassign and isinstance(ls, ast.Slice):
+            # hack to create a variable pre-declared based on a slice.
+            # dividend[0:32] = (RA)[0:32] will create
+            #       dividend = [0] * 32
+            #       dividend[0:32] = (RA)[0:32]
+            # the declaration makes the slice-assignment "work"
+            lower, upper, step = ls.lower, ls.upper, ls.step
+            print ("lower, upper, step", repr(lower), repr(upper), step)
+            if not isinstance(lower, ast.Constant) or \
+               not isinstance(upper, ast.Constant):
+                return res
+            qty = ast.Num(upper.value-lower.value)
+            keywords = [ast.keyword(arg='repeat', value=qty)]
+            l = [ast.Num(0)]
+            right = ast.Call(ast.Name("concat", ast.Load()), l, keywords)
+            declare = ast.Assign([ast.Name(assignname, ast.Store())], right)
+            return [declare, res]
+        return res
         # XXX HMMM probably not needed...
         ls = left.slice
         if isinstance(ls, ast.Slice):
@@ -54,7 +78,7 @@ def Assign(left, right):
             else:
                 ls = (lower, upper, step)
             ls = ast.Tuple(ls)
-        return ast.Call(ast.Name("selectassign"),
+        return ast.Call(ast.Name("selectassign", ast.Load()),
                         [left.value, ls, right], [])
     else:
         print("Assign fail")
@@ -83,27 +107,32 @@ def Assign(left, right):
 
 def make_le_compare(arg):
     (left, right) = arg
-    return ast.Compare(left, [ast.LtE()], [right])
+    return ast.Call(ast.Name("le", ast.Load()), (left, right), [])
 
 
 def make_ge_compare(arg):
     (left, right) = arg
-    return ast.Compare(left, [ast.GtE()], [right])
+    return ast.Call(ast.Name("ge", ast.Load()), (left, right), [])
 
 
 def make_lt_compare(arg):
     (left, right) = arg
-    return ast.Compare(left, [ast.Lt()], [right])
+    return ast.Call(ast.Name("lt", ast.Load()), (left, right), [])
 
 
 def make_gt_compare(arg):
     (left, right) = arg
-    return ast.Compare(left, [ast.Gt()], [right])
+    return ast.Call(ast.Name("gt", ast.Load()), (left, right), [])
 
 
 def make_eq_compare(arg):
     (left, right) = arg
-    return ast.Compare(left, [ast.Eq()], [right])
+    return ast.Call(ast.Name("eq", ast.Load()), (left, right), [])
+
+
+def make_ne_compare(arg):
+    (left, right) = arg
+    return ast.Call(ast.Name("ne", ast.Load()), (left, right), [])
 
 
 binary_ops = {
@@ -113,13 +142,14 @@ binary_ops = {
     "+": ast.Add(),
     "-": ast.Sub(),
     "*": ast.Mult(),
-    "/": ast.Div(),
+    "/": ast.FloorDiv(),
     "%": ast.Mod(),
     "<=": make_le_compare,
     ">=": make_ge_compare,
     "<": make_lt_compare,
     ">": make_gt_compare,
     "=": make_eq_compare,
+    "!=": make_ne_compare,
 }
 unary_ops = {
     "+": ast.UAdd(),
@@ -135,22 +165,25 @@ def check_concat(node):  # checks if the comparison is already a concat
     print("func", node.func.id)
     if node.func.id != 'concat':
         return [node]
-    if node.keywords: # a repeated list-constant, don't optimise
+    if node.keywords:  # a repeated list-constant, don't optimise
         return [node]
     return node.args
 
 
-# identify SelectableInt pattern
+# identify SelectableInt pattern [something] * N
+# must return concat(something, repeat=N)
 def identify_sint_mul_pattern(p):
-    if not isinstance(p[3], ast.Constant):
+    if p[2] != '*':  # multiply
+        return False
+    if not isinstance(p[3], ast.Constant):  # rhs = Num
         return False
-    if not isinstance(p[1], ast.List):
+    if not isinstance(p[1], ast.List):  # lhs is a list
         return False
     l = p[1].elts
-    if len(l) != 1:
+    if len(l) != 1:  # lhs is a list of length 1
         return False
-    elt = l[0]
-    return isinstance(elt, ast.Constant)
+    return True  # yippee!
+
 
 def apply_trailer(atom, trailer):
     if trailer[0] == "TLIST":
@@ -205,10 +238,11 @@ def apply_trailer(atom, trailer):
 # or                                                     Boolean OR
 # lambda                                                 Lambda expression
 
+
 class PowerParser:
 
     precedence = (
-        ("left", "EQ", "GT", "LT", "LE", "GE", "LTU", "GTU"),
+        ("left", "EQ", "NE", "GT", "LT", "LE", "GE", "LTU", "GTU"),
         ("left", "BITOR"),
         ("left", "BITXOR"),
         ("left", "BITAND"),
@@ -217,13 +251,27 @@ class PowerParser:
         ("left", "INVERT"),
     )
 
-    def __init__(self):
+    def __init__(self, form, include_carry_in_write=False):
+        self.include_ca_in_write = include_carry_in_write
         self.gprs = {}
+        form = self.sd.sigforms[form]
+        print(form)
+        formkeys = form._asdict().keys()
+        self.declared_vars = set()
         for rname in ['RA', 'RB', 'RC', 'RT', 'RS']:
             self.gprs[rname] = None
+            self.declared_vars.add(rname)
+        self.available_op_fields = set()
+        for k in formkeys:
+            if k not in self.gprs:
+                if k == 'SPR':  # sigh, lower-case to not conflict
+                    k = k.lower()
+                self.available_op_fields.add(k)
+        self.op_fields = OrderedSet()
         self.read_regs = OrderedSet()
         self.uninit_regs = OrderedSet()
         self.write_regs = OrderedSet()
+        self.special_regs = OrderedSet() # see p_atom_name
 
     # The grammar comments come from Python's Grammar/Grammar file
 
@@ -301,6 +349,8 @@ class PowerParser:
                        | small_stmt"""
         if len(p) == 4:
             p[0] = p[1] + [p[3]]
+        elif isinstance(p[1], list):
+            p[0] = p[1]
         else:
             p[0] = [p[1]]
 
@@ -312,6 +362,11 @@ class PowerParser:
                       | expr_stmt"""
         if isinstance(p[1], ast.Call):
             p[0] = ast.Expr(p[1])
+        elif isinstance(p[1], ast.Name) and p[1].id == 'TRAP':
+            # TRAP needs to actually be a function
+            name = ast.Name("self", ast.Load())
+            name = ast.Attribute(name, "TRAP", ast.Load())
+            p[0] = ast.Call(name, [], [])
         else:
             p[0] = p[1]
 
@@ -320,7 +375,8 @@ class PowerParser:
     # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
     #             '<<=' | '>>=' | '**=' | '//=')
     def p_expr_stmt(self, p):
-        """expr_stmt : testlist ASSIGN testlist
+        """expr_stmt : testlist ASSIGNEA testlist
+                     | testlist ASSIGN testlist
                      | testlist """
         print("expr_stmt", p)
         if len(p) == 2:
@@ -328,35 +384,41 @@ class PowerParser:
             #p[0] = ast.Discard(p[1])
             p[0] = p[1]
         else:
+            iea_mode = p[2] == '<-iea'
             name = None
+            autoassign = False
             if isinstance(p[1], ast.Name):
                 name = p[1].id
             elif isinstance(p[1], ast.Subscript):
-                name = p[1].value.id
-                if name in self.gprs:
-                    # add to list of uninitialised
-                    self.uninit_regs.add(name)
-            elif isinstance(p[1], ast.Call) and p[1].func.id == 'GPR':
+                if isinstance(p[1].value, ast.Name):
+                    name = p[1].value.id
+                    if name in self.gprs:
+                        # add to list of uninitialised
+                        self.uninit_regs.add(name)
+                    autoassign = name not in self.declared_vars
+            elif isinstance(p[1], ast.Call) and p[1].func.id in ['GPR', 'SPR']:
                 print(astor.dump_tree(p[1]))
                 # replace GPR(x) with GPR[x]
                 idx = p[1].args[0]
-                p[1] = ast.Subscript(p[1].func, idx)
+                p[1] = ast.Subscript(p[1].func, idx, ast.Load())
             elif isinstance(p[1], ast.Call) and p[1].func.id == 'MEM':
-                print ("mem assign")
+                print("mem assign")
                 print(astor.dump_tree(p[1]))
-                p[1].func.id = "memassign" # change function name to set
+                p[1].func.id = "memassign"  # change function name to set
                 p[1].args.append(p[3])
                 p[0] = p[1]
-                print ("mem rewrite")
+                print("mem rewrite")
                 print(astor.dump_tree(p[0]))
                 return
             else:
-                print ("help, help")
+                print("help, help")
                 print(astor.dump_tree(p[1]))
             print("expr assign", name, p[1])
             if name and name in self.gprs:
                 self.write_regs.add(name)  # add to list of regs to write
-            p[0] = Assign(p[1], p[3])
+            p[0] = Assign(autoassign, name, p[1], p[3], iea_mode)
+            if name:
+                self.declared_vars.add(name)
 
     def p_flow_stmt(self, p):
         "flow_stmt : return_stmt"
@@ -370,6 +432,7 @@ class PowerParser:
     def p_compound_stmt(self, p):
         """compound_stmt : if_stmt
                          | while_stmt
+                         | switch_stmt
                          | for_stmt
                          | funcdef
         """
@@ -387,7 +450,7 @@ class PowerParser:
         # auto-add-one (sigh) due to python range
         start = p[4]
         end = ast.BinOp(p[6], ast.Add(), ast.Constant(1))
-        it = ast.Call(ast.Name("range"), [start, end], [])
+        it = ast.Call(ast.Name("range", ast.Load()), [start, end], [])
         p[0] = ast.For(p[2], it, p[8], [])
 
     def p_while_stmt(self, p):
@@ -399,6 +462,93 @@ class PowerParser:
         else:
             p[0] = ast.While(p[3], p[5], p[8])
 
+    def p_switch_smt(self, p):
+        """switch_stmt : SWITCH LPAR atom RPAR COLON NEWLINE INDENT switches DEDENT
+        """
+        switchon = p[3]
+        print("switch stmt")
+        print(astor.dump_tree(p[1]))
+
+        cases = []
+        current_cases = []  # for deferral
+        for (case, suite) in p[8]:
+            print("for", case, suite)
+            if suite is None:
+                for c in case:
+                    current_cases.append(ast.Num(c))
+                continue
+            if case == 'default':  # last
+                break
+            for c in case:
+                current_cases.append(ast.Num(c))
+            print("cases", current_cases)
+            compare = ast.Compare(switchon, [ast.In()],
+                                  [ast.List(current_cases, ast.Load())])
+            current_cases = []
+            cases.append((compare, suite))
+
+        print("ended", case, current_cases)
+        if case == 'default':
+            if current_cases:
+                compare = ast.Compare(switchon, [ast.In()],
+                                      [ast.List(current_cases, ast.Load())])
+                cases.append((compare, suite))
+            cases.append((None, suite))
+
+        cases.reverse()
+        res = []
+        for compare, suite in cases:
+            print("after rev", compare, suite)
+            if compare is None:
+                assert len(res) == 0, "last case should be default"
+                res = suite
+            else:
+                if not isinstance(res, list):
+                    res = [res]
+                res = ast.If(compare, suite, res)
+        p[0] = res
+
+    def p_switches(self, p):
+        """switches : switch_list switch_default
+                    | switch_default
+        """
+        if len(p) == 3:
+            p[0] = p[1] + [p[2]]
+        else:
+            p[0] = [p[1]]
+
+    def p_switch_list(self, p):
+        """switch_list : switch_case switch_list
+                       | switch_case
+        """
+        if len(p) == 3:
+            p[0] = [p[1]] + p[2]
+        else:
+            p[0] = [p[1]]
+
+    def p_switch_case(self, p):
+        """switch_case : CASE LPAR atomlist RPAR COLON suite
+        """
+        # XXX bad hack
+        if isinstance(p[6][0], ast.Name) and p[6][0].id == 'fallthrough':
+            p[6] = None
+        p[0] = (p[3], p[6])
+
+    def p_switch_default(self, p):
+        """switch_default : DEFAULT COLON suite
+        """
+        p[0] = ('default', p[3])
+
+    def p_atomlist(self, p):
+        """atomlist : atom COMMA atomlist
+                    | atom
+        """
+        assert isinstance(p[1], ast.Constant), "case must be numbers"
+        if len(p) == 4:
+            p[0] = [p[1].value] + p[3]
+        else:
+            p[0] = [p[1].value]
+
     def p_if_stmt(self, p):
         """if_stmt : IF test COLON suite ELSE COLON if_stmt
                    | IF test COLON suite ELSE COLON suite
@@ -434,6 +584,7 @@ class PowerParser:
                       | comparison DIV comparison
                       | comparison MOD comparison
                       | comparison EQ comparison
+                      | comparison NE comparison
                       | comparison LE comparison
                       | comparison GE comparison
                       | comparison LTU comparison
@@ -451,18 +602,35 @@ class PowerParser:
         if len(p) == 4:
             print(list(p))
             if p[2] == '<u':
-                p[0] = ast.Call(ast.Name("ltu"), (p[1], p[3]), [])
+                p[0] = ast.Call(ast.Name("ltu", ast.Load()), (p[1], p[3]), [])
             elif p[2] == '>u':
-                p[0] = ast.Call(ast.Name("gtu"), (p[1], p[3]), [])
+                p[0] = ast.Call(ast.Name("gtu", ast.Load()), (p[1], p[3]), [])
             elif p[2] == '||':
                 l = check_concat(p[1]) + check_concat(p[3])
-                p[0] = ast.Call(ast.Name("concat"), l, [])
-            elif p[2] in ['<', '>', '=', '<=', '>=']:
+                p[0] = ast.Call(ast.Name("concat", ast.Load()), l, [])
+            elif p[2] in ['/', '%']:
+                # bad hack: if % or / used anywhere other than div/mod ops,
+                # do % or /.  however if the argument names are "dividend"
+                # we must call the special trunc_div and trunc_rem functions
+                l, r = p[1], p[3]
+                # actual call will be "dividend / divisor" - just check
+                # LHS name
+                if isinstance(l, ast.Name) and l.id == 'dividend':
+                    if p[2] == '/':
+                        fn = 'trunc_div'
+                    else:
+                        fn = 'trunc_rem'
+                    # return "function trunc_xxx(l, r)"
+                    p[0] =  ast.Call(ast.Name(fn, ast.Load()), (l, r), [])
+                else:
+                    # return "l {binop} r"
+                    p[0] = ast.BinOp(p[1], binary_ops[p[2]], p[3])
+            elif p[2] in ['<', '>', '=', '<=', '>=', '!=']:
                 p[0] = binary_ops[p[2]]((p[1], p[3]))
             elif identify_sint_mul_pattern(p):
-                keywords=[ast.keyword(arg='repeat', value=p[3])]
+                keywords = [ast.keyword(arg='repeat', value=p[3])]
                 l = p[1].elts
-                p[0] = ast.Call(ast.Name("concat"), l, keywords)
+                p[0] = ast.Call(ast.Name("concat", ast.Load()), l, keywords)
             else:
                 p[0] = ast.BinOp(p[1], binary_ops[p[2]], p[3])
         elif len(p) == 3:
@@ -490,11 +658,23 @@ class PowerParser:
 
     def p_atom_name(self, p):
         """atom : NAME"""
-        p[0] = ast.Name(id=p[1], ctx=ast.Load())
+        name = p[1]
+        if name in self.available_op_fields:
+            self.op_fields.add(name)
+        if name == 'overflow':
+            self.write_regs.add(name)
+        if self.include_ca_in_write:
+            if name in ['CA', 'CA32']:
+                self.write_regs.add(name)
+        if name in ['CR', 'LR', 'CTR', 'TAR', 'FPSCR', 'MSR']:
+            self.special_regs.add(name)
+            self.write_regs.add(name) # and add to list to write
+        p[0] = ast.Name(id=name, ctx=ast.Load())
 
     def p_atom_number(self, p):
         """atom : BINARY
                 | NUMBER
+                | HEX
                 | STRING"""
         p[0] = ast.Constant(p[1])
 
@@ -509,9 +689,9 @@ class PowerParser:
                      | test
         """
         if len(p) == 2:
-            p[0] = ast.List([p[1]])
+            p[0] = ast.List([p[1]], ast.Load())
         else:
-            p[0] = ast.List([p[1]] + p[3].nodes)
+            p[0] = ast.List([p[1]] + p[3].nodes, ast.Load())
 
     def p_atom_tuple(self, p):
         """atom : LPAR testlist RPAR"""
@@ -520,26 +700,28 @@ class PowerParser:
         print(astor.dump_tree(p[2]))
 
         if isinstance(p[2], ast.Name):
-            print("tuple name", p[2].id)
-            if p[2].id in self.gprs:
-                self.read_regs.add(p[2].id)  # add to list of regs to read
-                #p[0] = ast.Subscript(ast.Name("GPR"), ast.Str(p[2].id))
+            name = p[2].id
+            print("tuple name", name)
+            if name in self.gprs:
+                self.read_regs.add(name)  # add to list of regs to read
+                #p[0] = ast.Subscript(ast.Name("GPR", ast.Load()), ast.Str(p[2].id))
                 # return
             p[0] = p[2]
         elif isinstance(p[2], ast.BinOp):
             if isinstance(p[2].left, ast.Name) and \
                isinstance(p[2].right, ast.Constant) and \
-                p[2].right.value == 0 and \
-                p[2].left.id in self.gprs:
-                    rid = p[2].left.id
-                    self.read_regs.add(rid)  # add to list of regs to read
-                    # create special call to GPR.getz
-                    gprz = ast.Name("GPR")
-                    gprz = ast.Attribute(gprz, "getz")   # get testzero function
-                    # *sigh* see class GPR.  we need index itself not reg value
-                    ridx = ast.Name("_%s" % rid)
-                    p[0] = ast.Call(gprz, [ridx], [])
-                    print("tree", astor.dump_tree(p[0]))
+                    p[2].right.value == 0 and \
+                    p[2].left.id in self.gprs:
+                rid = p[2].left.id
+                self.read_regs.add(rid)  # add to list of regs to read
+                # create special call to GPR.getz
+                gprz = ast.Name("GPR", ast.Load())
+                # get testzero function
+                gprz = ast.Attribute(gprz, "getz", ast.Load())
+                # *sigh* see class GPR.  we need index itself not reg value
+                ridx = ast.Name("_%s" % rid, ast.Load())
+                p[0] = ast.Call(gprz, [ridx], [])
+                print("tree", astor.dump_tree(p[0]))
             else:
                 p[0] = p[2]
         else:
@@ -646,8 +828,9 @@ class PowerParser:
 
 
 class GardenSnakeParser(PowerParser):
-    def __init__(self, lexer=None, debug=False):
-        PowerParser.__init__(self)
+    def __init__(self, lexer=None, debug=False, form=None, incl_carry=False):
+        self.sd = create_pdecode()
+        PowerParser.__init__(self, form, incl_carry)
         self.debug = debug
         if lexer is None:
             lexer = IndentLexer(debug=0)
@@ -656,8 +839,6 @@ class GardenSnakeParser(PowerParser):
         self.parser = yacc.yacc(module=self, start="file_input_end",
                                 debug=debug, write_tables=False)
 
-        self.sd = create_pdecode()
-
     def parse(self, code):
         # self.lexer.input(code)
         result = self.parser.parse(code, lexer=self.lexer, debug=self.debug)
@@ -669,8 +850,9 @@ class GardenSnakeParser(PowerParser):
 #from compiler import misc, syntax, pycodegen
 
 class GardenSnakeCompiler(object):
-    def __init__(self, debug=False):
-        self.parser = GardenSnakeParser(debug=debug)
+    def __init__(self, debug=False, form=None, incl_carry=False):
+        self.parser = GardenSnakeParser(debug=debug, form=form,
+                                        incl_carry=incl_carry)
 
     def compile(self, code, mode="exec", filename="<string>"):
         tree = self.parser.parse(code)