v2x: handle multiple instances of the same cell

Signed-off-by: Karol Gugala <kgugala@antmicro.com>
Signed-off-by: Tim 'mithro' Ansell <me@mith.ro>
diff --git a/vlog_to_pbtype.py b/vlog_to_pbtype.py
index 79f6c2e..6b33abc 100755
--- a/vlog_to_pbtype.py
+++ b/vlog_to_pbtype.py
@@ -115,6 +115,8 @@
 
 tmod = yj.module(top)
 
+INVALID_INSTANCE = -1
+
 
 def mod_pb_name(mod):
     """Convert a Verilog module to a pb_type name in the format documented here:
@@ -151,15 +153,20 @@
     """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_module_name(pin):
+    def get_module_name(pin, instance=INVALID_INSTANCE):
         """Returns the name of the module relative to the pin and a boolean that indicates whether
         the module is a cell (True) or the top one (False)"""
+        if instance <= INVALID_INSTANCE:
+            instance = ""
+        else:
+            instance = "[" + str(instance) + "]"
         cname, cellpin = pin
         if cname.startswith("$"):
             return cname, True
         elif cname != mod.name:
             cname = mod.cell_type(cname)
-            return mod_pb_name(yj.module(cname)), True
+            modname = mod_pb_name(yj.module(cname)) + instance
+            return modname, True
         else:
             return mod_pname, False
 
@@ -179,11 +186,17 @@
 
         return port
 
-    def make_direct_conn(ic_xml, src, dst):
+    def make_direct_conn(
+            ic_xml,
+            src,
+            dst,
+            source_instance=INVALID_INSTANCE,
+            dest_instance=INVALID_INSTANCE
+    ):
         s_cellpin = get_cellpin(src)
         d_cellpin = get_cellpin(dst)
-        s_cname, s_is_cell = get_module_name(src)
-        d_cname, d_is_cell = get_module_name(dst)
+        s_cname, s_is_cell = get_module_name(src, source_instance)
+        d_cname, d_is_cell = get_module_name(dst, dest_instance)
 
         s_port = create_port(s_cellpin, s_cname, s_is_cell, "input")
         d_port = create_port(d_cellpin, d_cname, d_is_cell, "output")
@@ -199,26 +212,55 @@
     # List of entries in format ((from_cell, from_pin), (to_cell, to_pin))
     interconn = []
 
+    # Determine multiple instances of the same cell:
+    cells = dict()
+    for cname, i_of in mod.cells:
+        if i_of in cells:
+            cells[i_of]['count'] += 1
+            cells[i_of]['is_multi_instance'] = True
+            # assign unique instance number
+            cells[i_of][cname] = cells[i_of]['count']
+        else:
+            cells[i_of] = dict()
+            cells[i_of]['is_multi_instance'] = False
+            cells[i_of]['count'] = 0
+            cells[i_of][cname] = 0
+
     # Blackbox modules don't have inner cells or interconnect (but do still have timing)
     if (not is_blackbox) or is_submode:
         # Process cells. First build the list of cnames.
+        processed_cells = list()
         for cname, i_of in mod.cells:
             pb_name = strip_name(i_of)
+            do_not_include = False
+            if i_of in processed_cells:
+                # do not emit xml include for every instance of multi instace cell
+                do_not_include = True
+            else:
+                processed_cells.append(i_of)
+            instance = INVALID_INSTANCE
+
+            # If currently considered cell is a multi instance one, pass it's unique
+            # instance number to connection creator. If not, pass INVALID_INSTANCE
+            # constant
+            if cells[i_of]['is_multi_instance']:
+                instance = cells[i_of][cname]
             module_file = yj.get_module_file(i_of)
             module_path = os.path.dirname(module_file)
             module_basename = os.path.basename(module_file)
             # Heuristic for autogenerated files from w.py
-            wm = re.match(r"([A-Za-z0-9_]+)\.sim\.v", module_basename)
-            if wm:
-                pb_type_path = "{}/{}.pb_type.xml".format(
-                    module_path,
-                    wm.group(1).lower()
+            if not do_not_include:
+                wm = re.match(r"([A-Za-z0-9_]+)\.sim\.v", module_basename)
+                if wm:
+                    pb_type_path = "{}/{}.pb_type.xml".format(
+                        module_path,
+                        wm.group(1).lower()
+                    )
+                else:
+                    pb_type_path = "{}/pb_type.xml".format(module_path)
+                xmlinc.include_xml(
+                    parent=xml_parent, href=pb_type_path, outfile=outfile
                 )
-            else:
-                pb_type_path = "{}/pb_type.xml".format(module_path)
-            xmlinc.include_xml(
-                parent=xml_parent, href=pb_type_path, outfile=outfile
-            )
             # In order to avoid overspecifying interconnect, there are two directions we currently
             # consider. All interconnect going INTO a cell, and interconnect going out of a cell
             # into a top level output - or all outputs if "mode" is used.
@@ -234,7 +276,22 @@
                     .format(pb_name, pin)
                 )
                 for drv_cell, drv_pin in drvs:
-                    interconn.append(((drv_cell, drv_pin), (cname, pin)))
+                    # check if we're driven by multi instance cell
+                    drive_instance = INVALID_INSTANCE
+                    drv_cell_type = [
+                        c[1] for c in mod.cells if c[0] == drv_cell
+                    ]
+                    if len(drv_cell_type) != 0:
+                        drv_cell_type = drv_cell_type[0]
+                        if cells[drv_cell_type]['is_multi_instance']:
+                            # get drv_cell unique instance number
+                            drive_instance = cells[drv_cell_type][drv_cell]
+                    interconn.append(
+                        (
+                            (drv_cell, drv_pin), (cname, pin), drive_instance,
+                            instance
+                        )
+                    )
 
             out_cons = mod.cell_conns(cname, "output")
             for pin, net in out_cons:
@@ -243,7 +300,12 @@
                     if sink_cell == mod.name:
                         #Only consider outputs from cell to top level IO. Inputs to other cells will be dealt with
                         #in those cells.
-                        interconn.append(((cname, pin), (sink_cell, sink_pin)))
+                        interconn.append(
+                            (
+                                (cname, pin), (sink_cell, sink_pin), instance,
+                                INVALID_INSTANCE
+                            )
+                        )
 
         # Direct pin->pin connections
         for net in mod.nets:
@@ -260,8 +322,8 @@
 
         ic_xml = ET.SubElement(xml_parent, "interconnect")
         # Process interconnect
-        for source, dest in interconn:
-            make_direct_conn(ic_xml, source, dest)
+        for source, dest, src_instance, dst_instance in interconn:
+            make_direct_conn(ic_xml, source, dest, src_instance, dst_instance)
 
     def process_clocked_tmg(tmgspec, port, xmltype, xml_parent):
         """Add a suitable timing spec if necessary to the pb_type"""