utils: Move mux generation into a library.

(So it can be used by the Artix-7 generators.)

Signed-off-by: Tim 'mithro' Ansell <me@mith.ro>
diff --git a/v2x/lib/mux.py b/v2x/lib/mux.py
new file mode 100644
index 0000000..797eca9
--- /dev/null
+++ b/v2x/lib/mux.py
@@ -0,0 +1,154 @@
+import lxml.etree as ET
+from enum import Enum
+
+
+def clog2(x):
+    """Ceiling log 2 of x.
+
+    >>> clog2(0), clog2(1), clog2(2), clog2(3), clog2(4)
+    (0, 0, 1, 2, 2)
+    >>> clog2(5), clog2(6), clog2(7), clog2(8), clog2(9)
+    (3, 3, 3, 3, 4)
+    >>> clog2(1 << 31)
+    31
+    >>> clog2(1 << 63)
+    63
+    >>> clog2(1 << 11)
+    11
+    """
+    x -= 1
+    i = 0
+    while True:
+        if x <= 0:
+            break
+        x = x >> 1
+        i += 1
+    return i
+
+
+class MuxType(Enum):
+    LOGIC   = 'BEL_MX'
+    ROUTING = 'BEL_RX'
+
+
+class MuxPinType(Enum):
+    INPUT = 'i'
+    SELECT = 's'
+    OUTPUT = 'o'
+
+    def verilog(self):
+        if self in (self.INPUT, self.SELECT):
+            return "input wire"
+        elif self == self.OUTPUT:
+            return "output wire"
+        else:
+            raise TypeError("Can't convert {} into verilog definition.".format(self))
+
+    def direction(self):
+        if self in (self.INPUT, self.SELECT):
+            return "input"
+        elif self == self.OUTPUT:
+            return "output"
+        else:
+            raise TypeError("Can't convert {} into verilog definition.".format(self))
+
+    def __str__(self):
+        return self.value
+
+
+def pb_type_xml(mux_type, mux_name, pins, subckt=None, num_pb=1, comment=""):
+    """Generate <pb_type> XML for a mux.
+
+    Parameters
+    ----------
+    mux_type: MuxType
+        Type of mux to create.
+
+    mux_name: str
+        Name of the mux.
+
+    pins: [(MuxPinType, str, int, int),]
+        List of tuples which contain (pin type, pin name, port width, index)
+
+    subckt: str
+        Name of the blif_model for the mux. Only valid when mux_type ==
+        MuxType.LOGIC.
+
+    num_pb: int
+        Value for the num_pb value. Defaults to 1.
+
+    comment: str
+        Optional comment for the mux.
+
+    Returns
+    -------
+    xml.etree.ElementTree
+        pb_type.xml for requested mux
+    """
+
+    assert mux_name, "No mux_name provided!"
+
+    pb_type_xml = ET.Element(
+        'pb_type', {
+            'name': mux_name,
+            'num_pb': str(num_pb),
+        })
+
+    if mux_type == MuxType.LOGIC:
+        pb_type_xml.attrib['blif_model'] = '.subckt %s' % subckt
+    else:
+        assert not subckt, "Provided subckt={} for non-logic mux!".format(subckt)
+
+    if comment:
+        pb_type_xml.append(ET.Comment(comment))
+
+    for pin_type, pin_name, pin_width, pin_index in pins:
+        #assert pin_index < pin_width, (
+        #    "Pin index {} >= width {} for pin {} {}".format(pin_index, pin_width, pin_name, pin_type))
+        if mux_type == MuxType.ROUTING and pin_type == MuxPinType.SELECT:
+            continue
+        ET.SubElement(
+            pb_type_xml,
+            pin_type.direction(),
+            {'name': pin_name, 'num_pins': str(pin_width)},
+        )
+
+    if mux_type == MuxType.LOGIC:
+        for ipin_type, ipin_name, ipin_width, ipin_index in pins:
+            if ipin_type not in (MuxPinType.INPUT, MuxPinType.SELECT):
+                continue
+
+            for opin_type, opin_name, opin_width, opin_index in pins:
+                if opin_type not in (MuxPinType.OUTPUT,):
+                    continue
+
+                ET.SubElement(
+                    pb_type_xml,
+                    'delay_constant', {
+                        'max': "10e-12",
+                        'in_port': "%s.%s" % (mux_name, ipin_name),
+                        'out_port': "%s.%s" % (mux_name, opin_name),
+                    },
+                )
+    elif mux_type == MuxType.ROUTING:
+        interconnect = ET.SubElement(pb_type_xml, 'interconnect')
+
+        inputs  = ["{}.{}".format(mux_name, n) for t, n, _, _ in pins if t in (MuxPinType.INPUT,)]
+        outputs = ["{}.{}".format(mux_name, n) for t, n, _, _ in pins if t in (MuxPinType.OUTPUT,)]
+        assert len(outputs) == 1
+
+        ET.SubElement(
+            interconnect,
+            'mux', {
+                'name': '%s' % (mux_name,),
+                'input': " ".join(inputs),
+                'output': outputs[0],
+            },
+        )
+
+    return pb_type_xml
+
+
+if __name__ == "__main__":
+    import doctest
+    doctest.testmod()
diff --git a/v2x/mux_gen.py b/v2x/mux_gen.py
index ea8ece3..ca8ae43 100755
--- a/v2x/mux_gen.py
+++ b/v2x/mux_gen.py
@@ -14,6 +14,8 @@
 import os
 import sys
 
+from lib import mux as mux_lib
+
 def str2bool(v):
     if v.lower() in ('yes', 'true', 't', 'y', '1'):
         return True
@@ -99,39 +101,10 @@
         print()
     print('-'*75)
 
-
-def clog2(x):
-    """Ceiling log 2 of x.
-
-    >>> clog2(0), clog2(1), clog2(2), clog2(3), clog2(4)
-    (0, 0, 1, 2, 2)
-    >>> clog2(5), clog2(6), clog2(7), clog2(8), clog2(9)
-    (3, 3, 3, 3, 4)
-    >>> clog2(1 << 31)
-    31
-    >>> clog2(1 << 63)
-    63
-    >>> clog2(1 << 11)
-    11
-    """
-    x -= 1
-    i = 0
-    while True:
-        if x <= 0:
-            break
-        x = x >> 1
-        i += 1
-    return i
-
-import doctest
-doctest.testmod()
-
 call_args = list(sys.argv)
 
 args = parser.parse_args()
-args.width_bits = clog2(args.width)
-if not args.subckt:
-    args.subckt = args.name_mux
+args.width_bits = mux_lib.clog2(args.width)
 
 mypath = __file__
 mydir = os.path.dirname(mypath)
@@ -263,16 +236,16 @@
 for i in args.order:
     if i == 'i':
         if args.split_inputs:
-            port_names.extend(('i', args.name_inputs[j], 1, '[%i]' % j) for j in range(args.width))
+            port_names.extend((mux_lib.MuxPinType.INPUT, args.name_inputs[j], 1, '[%i]' % j) for j in range(args.width))
         else:
-            port_names.append(('i', args.name_input, args.width, '[%i:0]' % args.width))
+            port_names.append((mux_lib.MuxPinType.INPUT, args.name_input, args.width, '[%i:0]' % args.width))
     elif i == 's':
         if args.split_selects and args.width_bits > 1:
-            port_names.extend(('s', args.name_selects[j], 1, '[%i]' % j) for j in range(args.width_bits))
+            port_names.extend((mux_lib.MuxPinType.SELECT, args.name_selects[j], 1, '[%i]' % j) for j in range(args.width_bits))
         else:
-            port_names.append(('s', args.name_select, args.width_bits, '[%i:0]' % args.width_bits))
+            port_names.append((mux_lib.MuxPinType.SELECT, args.name_select, args.width_bits, '[%i:0]' % args.width_bits))
     elif i == 'o':
-        port_names.append(('o', args.name_output, 1, ''))
+        port_names.append((mux_lib.MuxPinType.OUTPUT, args.name_output, 1, ''))
 
 # ------------------------------------------------------------------------
 # Generate the sim.v Verilog module
@@ -284,7 +257,7 @@
 with open(sim_file, "w") as f:
     module_args = []
     for type, name, _, _ in port_names:
-        if args.type == 'routing' and type == 's':
+        if args.type == 'routing' and type == mux_lib.MuxPinType.SELECT:
             continue
         module_args.append(name)
 
@@ -301,7 +274,7 @@
         if previous_type != type:
             f.write("\n")
             previous_type = type
-        if args.type == 'routing' and type == 's':
+        if args.type == 'routing' and type == mux_lib.MuxPinType.SELECT:
             if width == 1:
                 f.write('\tparameter [0:0] %s = 0;\n' % (name))
             else:
@@ -309,16 +282,16 @@
             continue
 
         if width == 1:
-            f.write('\t%s %s;\n' % (defs[type], name))
+            f.write('\t%s %s;\n' % (type.verilog(), name))
         else:
-            f.write('\t%s %s %s;\n' % (defs[type], index, name))
+            f.write('\t%s %s %s;\n' % (type.verilog(), index, name))
 
     f.write("\n")
     f.write('\tMUX%s mux (\n' % args.width)
     for i in range(0, args.width):
         j = 0
         for type, name, width, index in port_names:
-            if type != 'i':
+            if type != mux_lib.MuxPinType.INPUT:
                 continue
             if j+width <= i:
                 j += width
@@ -335,7 +308,7 @@
     for i in range(0, args.width_bits):
         j = 0
         for type, name, width, index in port_names:
-            if type != 's':
+            if type != mux_lib.MuxPinType.SELECT:
                 continue
             if j+width < i:
                 j += width
@@ -348,7 +321,7 @@
             f.write('\t\t.S%i(%s[%i]),\n' % (i, name, i-j))
 
     for type, name, width, index in port_names:
-        if type != 'o':
+        if type != mux_lib.MuxPinType.OUTPUT:
             continue
         break
     assert width == 1
@@ -365,18 +338,18 @@
     models_xml = ET.Element('models')
     models_xml.append(ET.Comment(xml_comment))
 
-    model_xml = ET.SubElement(models_xml, 'model', {'name': args.subckt})
+    model_xml = ET.SubElement(models_xml, 'model', {'name': args.subckt or args.name_mux})
 
     input_ports = ET.SubElement(model_xml, 'input_ports')
     output_ports = ET.SubElement(model_xml, 'output_ports')
     for type, name, width, index in port_names:
-        if type in ('i', 's'):
+        if type in (mux_lib.MuxPinType.INPUT, mux_lib.MuxPinType.SELECT):
             ET.SubElement(
                 input_ports, 'port', {
                     'name': name,
-                    'combinational_sink_ports': ','.join(n for t, n, w, i in port_names if t in ('o',)),
+                    'combinational_sink_ports': ','.join(n for t, n, w, i in port_names if t in (mux_lib.MuxPinType.OUTPUT,)),
                 })
-        elif type in ('o',):
+        elif type in (mux_lib.MuxPinType.OUTPUT,):
             ET.SubElement(output_ports, 'port', {'name': args.name_output})
 
     models_str = ET.tostring(models_xml, pretty_print=True).decode('utf-8')
@@ -390,73 +363,13 @@
 # Generate the pb_type XML form.
 # ------------------------------------------------------------------------
 
-xi_url = "http://www.w3.org/2001/XInclude"
-ET.register_namespace('xi', xi_url)
-xi_include = "{%s}include" % xi_url
-
-mn = args.name_mux
-pb_type_xml = ET.Element(
-    'pb_type', {
-        'name': mn,
-        'num_pb': str(args.num_pb),
-    },
-   nsmap = {'xi': xi_url})
-
-if args.type == 'logic':
-    pb_type_xml.attrib['blif_model'] = '.subckt %s' % args.subckt
-
-pb_type_xml.append(ET.Comment(xml_comment))
-
-for type, name, width, index in port_names:
-    if args.type == 'routing' and type == 's':
-        continue
-    ET.SubElement(
-        pb_type_xml,
-        {'i': 'input',
-         's': 'input',
-         'o': 'output'}[type],
-        {'name': name, 'num_pins': str(width)},
-    )
-
-if args.type == 'logic':
-    for itype, iname, iwidth, iindex in port_names:
-        if itype not in ('i', 's'):
-            continue
-
-        for otype, oname, owidth, oindex in port_names:
-            if otype not in ('o',):
-                continue
-
-            ET.SubElement(
-                pb_type_xml,
-                'delay_constant', {
-                    'max': "10e-12",
-                    'in_port': "%s.%s" % (args.name_mux, iname),
-                    'out_port': "%s.%s" % (args.name_mux, oname),
-                },
-            )
-elif args.type == "routing":
-    buf_model = os.path.join(buf_dir, "model.xml")
-    buf_pbtype = os.path.join(buf_dir, "pb_type.xml")
-    ET.SubElement(pb_type_xml, xi_include, {'href': buf_pbtype})
-
-    interconnect = ET.SubElement(pb_type_xml, 'interconnect')
-    ET.SubElement(
-        interconnect,
-        'mux', {
-            'name': '%s_IN' % (args.name_mux,),
-            'input': ' '.join("%s.%s" % (mn,n) for t, n, _, _ in port_names if t in ('i',)),
-            'output': "BUF.I", #"%s.%s" % (mn,args.name_output),
-        },
-    )
-    ET.SubElement(
-        interconnect,
-        'direct', {
-            'name': '%s_OUT' % (args.name_mux,),
-            'input': "BUF.O",
-            'output': "%s.%s" % (mn,args.name_output),
-        },
-    )
+pb_type_xml = mux_lib.pb_type_xml(
+    mux_lib.MuxType[args.type.upper()],
+    args.name_mux,
+    port_names,
+    subckt=args.subckt,
+    num_pb=args.num_pb,
+    comment=xml_comment)
 
 pb_type_str = ET.tostring(pb_type_xml, pretty_print=True).decode('utf-8')
 output_block("pb_type.xml", pb_type_str)