Merge branch 'fix-tests'
authorJacob Lifshay <programmerjake@gmail.com>
Mon, 6 Apr 2020 19:00:27 +0000 (12:00 -0700)
committerJacob Lifshay <programmerjake@gmail.com>
Mon, 6 Apr 2020 19:00:27 +0000 (12:00 -0700)
src/soc/decoder/isa/caller.py
src/soc/decoder/isa/test_caller.py
src/soc/decoder/power_fields.py
src/soc/decoder/pseudo/lexer.py
src/soc/decoder/pseudo/pagereader.py
src/soc/decoder/pseudo/pywriter.py
src/soc/simulator/program.py

index 2199d731348e0453f744e64c65b9492ceda2e047..2bf47d5b72a1d4e06d80c995d11bd29488ebdd69 100644 (file)
@@ -1,8 +1,13 @@
 from functools import wraps
 from soc.decoder.orderedset import OrderedSet
 from soc.decoder.selectable_int import SelectableInt, selectconcat
+from collections import namedtuple
 import math
 
+instruction_info = namedtuple('instruction_info',
+                              'func read_regs uninit_regs write_regs op_fields form asmregs')
+
+
 def create_args(reglist, extra=None):
     args = OrderedSet()
     for reg in reglist:
@@ -12,6 +17,7 @@ def create_args(reglist, extra=None):
         args = [extra] + args
     return args
 
+
 class Mem:
 
     def __init__(self, bytes_per_word=8):
@@ -107,6 +113,17 @@ class GPR(dict):
             s = ' '.join(s)
             print("reg", "%2d" % i, s)
 
+class PC:
+    def __init__(self, pc_init=0):
+        self.CIA = SelectableInt(pc_init, 64)
+        self.NIA = self.CIA + SelectableInt(4, 64)
+
+    def update(self, namespace):
+        self.CIA = self.NIA
+        self.NIA = self.CIA + SelectableInt(4, 64)
+        namespace['CIA'] = self.CIA
+        namespace['NIA'] = self.NIA
+
 
 class ISACaller:
     # decoder2 - an instance of power_decoder2
@@ -114,10 +131,14 @@ class ISACaller:
     def __init__(self, decoder2, regfile):
         self.gpr = GPR(decoder2, regfile)
         self.mem = Mem()
+        self.pc = PC()
         self.namespace = {'GPR': self.gpr,
                           'MEM': self.mem,
-                          'memassign': self.memassign
+                          'memassign': self.memassign,
+                          'NIA': self.pc.NIA,
+                          'CIA': self.pc.CIA,
                           }
+
         self.decoder = decoder2
 
     def memassign(self, ea, sz, val):
@@ -129,19 +150,20 @@ class ISACaller:
         # from spec
         # then "yield" fields only from op_fields rather than hard-coded
         # list, here.
-        for name in ['SI', 'UI', 'D', 'BD']:
-            signal = getattr(self.decoder, name)
-            val = yield signal
-            self.namespace[name] = SelectableInt(val, bits=signal.width)
+        fields = self.decoder.sigforms[formname]
+        for name in fields._fields:
+            if name not in ["RA", "RB", "RT"]:
+                sig = getattr(fields, name)
+                val = yield sig
+                self.namespace[name] = SelectableInt(val, sig.width)
 
     def call(self, name):
         # TODO, asmregs is from the spec, e.g. add RT,RA,RB
         # see http://bugs.libre-riscv.org/show_bug.cgi?id=282
-        fn, read_regs, uninit_regs, write_regs, op_fields, asmregs, form \
-            = self.instrs[name]
-        yield from self.prep_namespace(form, op_fields)
+        info = self.instrs[name]
+        yield from self.prep_namespace(info.form, info.op_fields)
 
-        input_names = create_args(read_regs | uninit_regs)
+        input_names = create_args(info.read_regs | info.uninit_regs)
         print(input_names)
 
         inputs = []
@@ -152,17 +174,18 @@ class ISACaller:
             print('reading reg %d' % regnum)
             inputs.append(self.gpr(regnum))
         print(inputs)
-        results = fn(self, *inputs)
+        results = info.func(self, *inputs)
         print(results)
 
-        if write_regs:
-            output_names = create_args(write_regs)
+        if info.write_regs:
+            output_names = create_args(info.write_regs)
             for name, output in zip(output_names, results):
                 regnum = yield getattr(self.decoder, name)
                 print('writing reg %d' % regnum)
                 if output.bits > 64:
                     output = SelectableInt(output.value, 64)
                 self.gpr[regnum] = output
+        self.pc.update(self.namespace)
 
 
 def inject():
index 55dcc673bf08189ee50d154583709958c77a38c3..0a26c8169883112d431b55828535038066e56633 100644 (file)
@@ -79,6 +79,16 @@ class DecoderTestCase(FHDLTestCase):
             print(sim.gpr(1))
             self.assertEqual(sim.gpr(3), SelectableInt(0x1234, 64))
 
+    def test_addpcis(self):
+        lst = ["addpcis 1, 0x1",
+               "addpcis 2, 0x1",
+               "addpcis 3, 0x1"]
+        with Program(lst) as program:
+            sim = self.run_tst_program(program)
+            self.assertEqual(sim.gpr(1), SelectableInt(0x10004, 64))
+            self.assertEqual(sim.gpr(2), SelectableInt(0x10008, 64))
+            self.assertEqual(sim.gpr(3), SelectableInt(0x1000c, 64))
+
     def run_tst_program(self, prog, initial_regs=[0] * 32):
         simulator = self.run_tst(prog, initial_regs)
         simulator.gpr.dump()
index 26b59d46863fcd313e6d952b8f5fab22129afef0..4e7bee0951ed6263265cb010a2935a72c75c18c6 100644 (file)
@@ -208,9 +208,18 @@ class DecodeFields:
         res = {}
         for field in fields:
             f, spec = field.strip().split(" ")
+            ss = spec[1:-1].split(",")
+            fs = f.split(",")
+            if len(fs) > 1:
+                individualfields = []
+                for f0, s0 in zip(fs, ss):
+                    txt = "%s (%s)" % (f0, s0)
+                    individualfields.append(txt)
+                if len(fs) > 1:
+                  res.update(self.decode_instruction_fields(individualfields))
             d = self.bitkls(*self.bitargs)
             idx = 0
-            for s in spec[1:-1].split(","):
+            for s in ss:
                 s = s.split(':')
                 if len(s) == 1:
                     d[idx] = int(s[0])
@@ -233,3 +242,7 @@ if __name__ == '__main__':
     dec = DecodeFields()
     dec.create_specs()
     forms, instrs = dec.forms, dec.instrs
+    for form, fields in instrs.items():
+        print ("Form", form)
+        for field, bits in fields.items():
+            print ("\tfield", field, bits)
index 85130696c7b6ed1b7d9d003b46513d6033fca0d6..d05e8845985617d964fb71f88a3c02a0d06f1ae5 100644 (file)
@@ -127,6 +127,48 @@ def DEDENT(lineno):
 def INDENT(lineno):
     return _new_token("INDENT", lineno)
 
+def count_spaces(l):
+    for i in range(len(l)):
+        if l[i] != ' ':
+            return i
+    return 0
+
+def annoying_case_hack_filter(code):
+    """add annoying "silent keyword" (fallthrough)
+
+    this which tricks the parser into taking the (silent) case statement
+    as a "small expression".  it can then be spotted and used to indicate
+    "fall through" to the next case (in the parser)
+
+    also skips blank lines
+
+    bugs: any function that starts with the letters "case" or "default"
+    will be detected erroneously.  fixing that involves doing a token
+    lexer which spots the fact that "case" and "default" are words,
+    separating them from space, colon, bracket etc.
+
+    http://bugs.libre-riscv.org/show_bug.cgi?id=280
+    """
+    res = []
+    prev_spc_count = None
+    for l in code.split("\n"):
+        spc_count = count_spaces(l)
+        nwhite = l[spc_count:]
+        if len(nwhite) == 0: # skip blank lines
+            continue
+        if nwhite.startswith("case") or nwhite.startswith("default"):
+            #print ("case/default", nwhite, spc_count, prev_spc_count)
+            if (prev_spc_count is not None and
+                prev_spc_count == spc_count and
+                (res[-1].endswith(":") or res[-1].endswith(": fallthrough"))):
+                res[-1] += " fallthrough" # add to previous line
+            prev_spc_count = spc_count
+        else:
+            #print ("notstarts", spc_count, nwhite)
+            prev_spc_count = None
+        res.append(l)
+    return '\n'.join(res)
+
 
 # Track the indentation level and emit the right INDENT / DEDENT events.
 def indentation_filter(tokens):
@@ -410,11 +452,16 @@ class PowerLexer:
 
 class IndentLexer(PowerLexer):
     def __init__(self, debug=0, optimize=0, lextab='lextab', reflags=0):
+        self.debug = debug
         self.build(debug=debug, optimize=optimize,
                                 lextab=lextab, reflags=reflags)
         self.token_stream = None
 
     def input(self, s, add_endmarker=True):
+        s = annoying_case_hack_filter(s)
+        if self.debug:
+            print (s)
+        s += "\n"
         self.lexer.paren_count = 0
         self.lexer.brack_count = 0
         self.lexer.input(s)
@@ -429,9 +476,13 @@ class IndentLexer(PowerLexer):
 switchtest = """
 switch (n)
     case(1): x <- 5
-    case(2): fallthrough
-    case(3):
+    case(3): x <- 2
+    case(2):
+
+    case(4):
         x <- 3
+    case(9):
+
     default:
         x <- 9
 print (5)
@@ -452,6 +503,7 @@ if __name__ == '__main__':
     # quick test/demo
     #code = cnttzd
     code = switchtest
+    print (code)
 
     lexer = IndentLexer(debug=1)
     # Give the lexer some input
index aa0557bc5f4cd3d00f9b529a6d88f9d9912fe536..f9e153491adb49e9d733063f74778d830200000f 100644 (file)
@@ -154,6 +154,7 @@ class ISA:
         opcode, regs = o[0], o[1:]
         op = copy(d)
         op['regs'] = regs
+        regs[0] = regs[0].split(",")
         op['opcode'] = opcode
         self.instr[opcode] = Ops(**op)
 
index a8f9bdabfd4eadc075c297b08d3347374662f687..4b6b03abbf800e957bb8cbc367174bff443e8280 100644 (file)
@@ -16,7 +16,7 @@ def get_isasrc_dir():
 header = """\
 # auto-generated by pywriter.py, do not edit or commit
 
-from soc.decoder.isa.caller import inject
+from soc.decoder.isa.caller import inject, instruction_info
 from soc.decoder.helpers import (EXTS, EXTS64, EXTZ64, ROTL64, ROTL32, MASK,)
 from soc.decoder.selectable_int import SelectableInt
 from soc.decoder.selectable_int import selectconcat as concat
@@ -26,10 +26,11 @@ class %s:
 
 """
 
-iinfo_template = """(%s, %s,
-                %s, %s,
-                %s, '%s',
-                %s)"""
+iinfo_template = """instruction_info(func=%s,
+                read_regs=%s,
+                uninit_regs=%s, write_regs=%s,
+                op_fields=%s, form='%s',
+                asmregs=%s)"""
 
 class PyISAWriter(ISA):
     def __init__(self):
@@ -72,8 +73,9 @@ class PyISAWriter(ISA):
                 # accumulate the instruction info
                 ops = repr(rused['op_fields'])
                 iinfo = iinfo_template % (op_fname, rused['read_regs'],
-                                rused['uninit_regs'], rused['write_regs'],
-                                ops, d.form, d.regs)
+                                          rused['uninit_regs'],
+                                          rused['write_regs'],
+                                          ops, d.form, d.regs)
                 iinf += "    %s_instrs['%s'] = %s\n" % (pagename, page, iinfo)
             # write out initialisation of info, for ISACaller to use
             f.write("    %s_instrs = {}\n" % pagename)
@@ -99,9 +101,6 @@ class PyISAWriter(ISA):
             f.write('        }\n')
 
 
-
-
-
 if __name__ == '__main__':
     isa = PyISAWriter()
     if len(sys.argv) == 1: # quick way to do it
index b3c1e87fc2fa2bc62ffa645dbc0710a021160fba..9857f037146ab2ab2d5fe7aec9f81f24c123ddb0 100644 (file)
@@ -45,6 +45,7 @@ class Program:
     def _assemble(self):
         with tempfile.NamedTemporaryFile(suffix=".o") as outfile:
             args = ["powerpc64-linux-gnu-as",
+                    '-mpower9',
                     obj_fmt,
                     "-o",
                     outfile.name]