utils/vlog: solved issues with combinational/sequential sinks

Signed-off-by: Alessandro Comodi <acomodi@antmicro.com>
diff --git a/vlog_to_model.py b/vlog_to_model.py
index 1be3efd..1ab0c91 100755
--- a/vlog_to_model.py
+++ b/vlog_to_model.py
@@ -16,7 +16,7 @@
     instance. A model will not be generated for the `lut`, `routing` or `flipflop`
     class.
 """
-import argparse, re
+import argparse, re, json
 import os, sys
 
 import lxml.etree as ET
@@ -25,6 +25,47 @@
 from yosys.json import YosysJSON
 import xmlinc
 
+def is_registered(tmod, bits, iodir, clk):
+    """Checks if a specific i/o port is registered
+
+    Returns a boolean value
+    -------
+    is_reg: bool
+    """
+    is_reg = False
+    for cell, ctype in tmod.all_cells:
+        if ctype != "$dff":
+            continue
+
+        # The clock is not related to the given port
+        if tmod.cell_clk_conn(cell) != tmod.port_conns(clk):
+            continue
+
+        if iodir == "input" and ((set(bits) & set(tmod.cell_conn_list(cell, "D"))) == set(bits)):
+            return True
+        elif iodir == "output" and ((set(bits) & set(tmod.cell_conn_list(cell, "Q"))) == set(bits)):
+            return True
+        else:
+            continue
+
+    return is_reg
+
+def is_registered_path(tmod, pin, pout):
+    """Checks if a i/o path is sequential. If that is the case
+    no combinational_sink_port is needed
+
+    Returns a boolean value
+    """
+
+    for cell, ctype in tmod.all_cells:
+        if ctype != "$dff":
+            continue
+
+        if tmod.port_conns(pin) == tmod.cell_conn_list(cell, "D") and tmod.port_conns(pout) == tmod.cell_conn_list(cell, "Q"):
+                return True
+
+    return False
+
 parser = argparse.ArgumentParser(description=__doc__.strip())
 parser.add_argument(
     'infiles',
@@ -130,6 +171,7 @@
     # Is a leaf model
     topname = tmod.attr("MODEL_NAME", top)
     modclass = tmod.attr("CLASS", "")
+
     if modclass not in ("lut", "routing", "flipflop"):
         model_xml = ET.SubElement(models_xml, "model", {'name': topname})
         ports = tmod.ports
@@ -138,24 +180,25 @@
         outports_xml = ET.SubElement(model_xml, "output_ports")
 
         clocks = yosys.run.list_clocks(args.infiles, top)
-        clk_sigs = dict()
-        for clk in clocks:
-            clk_sigs[clk] = yosys.run.get_clock_assoc_signals(
-                args.infiles, top, clk
-            )
 
-        for name, width, iodir in ports:
+        for name, width, bits, iodir in ports:
             attrs = dict(name=name)
             sinks = yosys.run.get_combinational_sinks(args.infiles, top, name)
+
+            # Removes comb sinks if path from in to out goes through a dff
+            for sink in sinks:
+                if is_registered_path(tmod, name, sink):
+                    sinks.remove(sink)
+
             # FIXME: Check if ignoring clock for "combination_sink_ports" is a
             # valid thing to do.
             if name in clocks:
                 attrs["is_clock"] = "1"
             else:
-                if len(sinks) > 0 and iodir == "input" and name not in clocks:
+                if len(sinks) > 0 and iodir == "input":
                     attrs["combinational_sink_ports"] = " ".join(sinks)
                 for clk in clocks:
-                    if name in clk_sigs[clk]:
+                    if is_registered(tmod, bits, iodir, clk):
                         attrs["clock"] = clk
             if iodir == "input":
                 ET.SubElement(inports_xml, "port", attrs)
diff --git a/vlog_to_pbtype.py b/vlog_to_pbtype.py
index 3db0126..2e69ca4 100755
--- a/vlog_to_pbtype.py
+++ b/vlog_to_pbtype.py
@@ -152,26 +152,34 @@
     """Build the pb_type content - child pb_types, timing and direct interconnect,
     but not IO. This may be put directly inside <pb_type>, or inside <mode>."""
 
-    def get_full_pin_name(pin):
+    def get_pin_name(pin):
         cname, cellpin = pin
         if cname != mod.name:
             cname = mod.cell_type(cname)
             cname = mod_pb_name(yj.module(cname))
         else:
             cname = mod_pname
-        return ("{}.{}".format(cname, cellpin))
+        return cname
+
+    def get_cellpin(pin):
+        cname, cellpin = pin
+        return cellpin
 
     def make_direct_conn(ic_xml, source, dest):
-        source_pin = get_full_pin_name(source)
-        dest_pin = get_full_pin_name(dest)
-        ic_name = dest_pin.replace(".", "_").replace("[", "_").replace("]", "")
-        dir_xml = ET.SubElement(
-            ic_xml, 'direct', {
-                'name': ic_name,
-                'input': source_pin,
-                'output': dest_pin
-            }
-        )
+        s_cellpin = get_cellpin(source)
+        d_cellpin = get_cellpin(dest)
+        d_cname = get_pin_name(dest)
+
+        dir_xml = ET.SubElement(ic_xml, 'direct')
+        in_port_xml = ET.SubElement(dir_xml, 'port', {
+            'name': s_cellpin,
+            'type': "input"
+        })
+        out_port_xml = ET.SubElement(dir_xml, 'port', {
+            'name': d_cellpin,
+            'type': "output",
+            'from': d_cname
+        })
 
     # Find out whether or not the module we are generating content for is a blackbox
     is_blackbox = (mod.attr("blackbox", 0) == 1) or not mod.cells
@@ -258,7 +266,7 @@
             ET.SubElement(xml_parent, xmltype, attrs)
 
     # Process timing
-    for name, width, iodir in mod.ports:
+    for name, width, bits, iodir in mod.ports:
         port = "{}.{}".format(mod_pname, name)
         # Clocked timing
         Tsetup = mod.net_attr(name, "SETUP")
@@ -344,7 +352,7 @@
 
     # Process IOs
     clocks = yosys.run.list_clocks(args.infiles, mod.name)
-    for name, width, iodir in mod.ports:
+    for name, width, bits, iodir in mod.ports:
         ioattrs = {"name": name, "num_pins": str(width)}
         pclass = mod.net_attr(name, "PORT_CLASS")
         if pclass is not None:
@@ -427,7 +435,6 @@
             sys.exit(1)
 
     tmod = yj.module(top)
-    print("cells", tmod.cells)
 
     pb_type_xml = make_pb_type(yj, tmod)
 
diff --git a/yosys/json.py b/yosys/json.py
index e2371f6..51bb445 100755
--- a/yosys/json.py
+++ b/yosys/json.py
@@ -34,7 +34,7 @@
         """
         plist = []
         for port, pdata in sorted(self.data["ports"].items()):
-            plist.append((port, len(pdata["bits"]), pdata["direction"]))
+            plist.append((port, len(pdata["bits"]), pdata["bits"], pdata["direction"]))
         return plist
 
     @property
@@ -45,19 +45,37 @@
         Returns a list of tuples:
         -------
         name : str
-        type: str
+        type : str
         """
         clist = []
         for cell, cdata in sorted(self.data["cells"].items()):
-            print(cell, cdata)
             if cell.startswith("$"):
                 continue
             clist.append((cell, cdata["type"]))
         return clist
 
     @property
+    def all_cells(self):
+        """List of cells of a module, including Yosis-internal cells
+
+        Returns a list of tuples:
+        -------
+        name : str
+        type : str
+        """
+        clist = []
+        for cell, cdata in sorted(self.data["cells"].items()):
+            clist.append((cell, cdata["type"]))
+        return clist
+
+    @property
+    def net_names(self):
+        """List the net names avilable in the design."""
+        return self.data["netnames"].keys()
+
+    @property
     def nets(self):
-        """List the net ids avaliable in the design."""
+        """List the net ids available in the design."""
         return list(sorted(set(n['bits'][0] for n in self.data["netnames"].values())))
 
     def cell_type(self, cell):
@@ -113,6 +131,17 @@
     # specifications are inconsistent in how they are represented in the JSON,
     # it's hard to make any nicer...
 
+    def port_conns(self, port):
+        """The connections of a port
+
+        Returns a list of connections:
+        -------
+        net : int
+        """
+        for pname, pdata in sorted(self.data["ports"].items()):
+            if pname == port:
+                return pdata["bits"]
+
     def cell_conns(self, cell, direction="input"):
         """The connections of a cell in a given direction as a 2-tuple
 
@@ -133,6 +162,38 @@
                         conns.append(("{}[{}]".format(port, i), condata[i]))
         return conns
 
+    def cell_conn_list(self, cell, port):
+        """The connections of a cell in a given port as a list
+
+        Returns a list of connections:
+        -------
+        net : list
+
+        """
+        data = self.data["cells"][cell]
+
+        conns = []
+
+        for cport, condata in sorted(data["connections"].items()):
+            if cport == port:
+                conns = condata
+
+        return conns
+
+    def cell_clk_conn(self, cell):
+        """The clock net related to a given cell
+
+        If exists returns the clock net
+
+        net : list
+        """
+        data = self.data["cells"][cell]
+
+        if "CLK" in data["connections"].keys():
+            return data["connections"]["CLK"]
+        else:
+            return None
+
     def conn_io(self, net, iodir):
         """Returns a list of top level IO matching a direction and connected net number