Ejemplo n.º 1
0
 def read(self, fields):
     if fields[0] == 'device' and len(fields) == 4 \
             and len(fields[1]) >= 2 and fields[1][0] == '"' \
                                     and fields[1][-1] == '"' \
             and self.ic is None and self.device is None:
         self.device = fields[1][1:-1]
         if self.device == '1k':
             self.ic = icebox.iceconfig()
             self.ic.setup_empty_1k()
         elif self.device == '8k':
             self.ic = icebox.iceconfig()
             self.ic.setup_empty_8k()
         elif self.device == '384':
             self.ic = icebox.iceconfig()
             self.ic.setup_empty_384()
         else:
             raise ParseError
     #elif fields[0] == 'coldboot' and fields[1] == '=' \
     #        and self.coldboot is None:
     #    # parsed but ignored (can't be represented in IceStorm .asc format)
     #    self.coldboot = parse_bool(fields[2])
     elif fields[0] == 'warmboot' and fields[1] == '=' \
             and self.warmboot is None:
         # parsed but ignored (can't be represented in IceStorm .asc format)
         self.warmboot = parse_bool(fields[2])
     else:
         raise ParseError
Ejemplo n.º 2
0
 def read(self, fields):
     if fields[0] == 'device' and len(fields) == 4 \
             and len(fields[1]) >= 2 and fields[1][0] == '"' \
                                     and fields[1][-1] == '"' \
             and self.ic is None and self.device is None:
         self.device = fields[1][1:-1]
         if self.device == '1k':
             self.ic = icebox.iceconfig()
             self.ic.setup_empty_1k()
         elif self.device == '8k':
             self.ic = icebox.iceconfig()
             self.ic.setup_empty_8k()
         elif self.device == '384':
             self.ic = icebox.iceconfig()
             self.ic.setup_empty_384()
         else:
             raise ParseError
     #elif fields[0] == 'coldboot' and fields[1] == '=' \
     #        and self.coldboot is None:
     #    # parsed but ignored (can't be represented in IceStorm .asc format)
     #    self.coldboot = parse_bool(fields[2])
     elif fields[0] == 'warmboot' and fields[1] == '=' \
             and self.warmboot is None:
         # parsed but ignored (can't be represented in IceStorm .asc format)
         self.warmboot = parse_bool(fields[2])
     else:
         raise ParseError
Ejemplo n.º 3
0
    def read(self, fields):
        if fields[0] == 'device' and len(fields) == 4 \
                and len(fields[1]) >= 2 and fields[1][0] == '"' \
                                        and fields[1][-1] == '"' \
                and self.ic is None and self.device is None:
            self.device = fields[1][1:-1].lower()
            if self.device.startswith('lp') or self.device.startswith('hx'):
                self.device = self.device[2:]
            if self.device.startswith('1k'):
                self.ic = icebox.iceconfig()
                self.ic.setup_empty_1k()
            elif self.device.startswith('8k'):
                self.ic = icebox.iceconfig()
                self.ic.setup_empty_8k()
            elif self.device.startswith('384'):
                self.ic = icebox.iceconfig()
                self.ic.setup_empty_384()
            else:
                raise ParseError("Unknown device {}".format(self.device))

        #elif fields[0] == 'coldboot' and fields[1] == '=' \
        #        and self.coldboot is None:
        #    # parsed but ignored (can't be represented in IceStorm .asc format)
        #    self.coldboot = parse_bool(fields[2])
        elif fields[0] == 'warmboot' and fields[1] == '=' \
                and self.warmboot is None:
            # parsed but ignored (can't be represented in IceStorm .asc format)
            self.warmboot = parse_bool(fields[2])
        else:
            raise ParseError("Unknown preamble directive {}".format(fields[0]))
Ejemplo n.º 4
0
def main():
    ic = icebox.iceconfig()
    ic.setup_empty_384()
    test_netname_translation(ic)

    ic = icebox.iceconfig()
    ic.setup_empty_1k()
    test_netname_translation(ic)

    ic = icebox.iceconfig()
    ic.setup_empty_8k()
    test_netname_translation(ic)
Ejemplo n.º 5
0
def main():
    ic = icebox.iceconfig()
    ic.setup_empty_384()
    test_netname_translation(ic)

    ic = icebox.iceconfig()
    ic.setup_empty_1k()
    test_netname_translation(ic)

    ic = icebox.iceconfig()
    ic.setup_empty_8k()
    test_netname_translation(ic)
Ejemplo n.º 6
0
def asc_to_fasm(filename, outf=StringIO()):
    """Generate a fasm output from an asc"""

    ic = icebox.iceconfig()
    ic.read_file(filename)

    return iceconfig_to_fasm(ic, outf)
Ejemplo n.º 7
0
def generate_fasm_db(outf, device):
    """Generate FASM style DB for a ice40 device"""

    ic = icebox.iceconfig()
    init_method_name = "setup_empty_{}".format(device.lower()[2:])
    assert hasattr(ic,
                   init_method_name), "no icebox method to init empty device"
    getattr(ic, init_method_name)()

    return _iceboxdb_to_fasmdb(ic, outf)
Ejemplo n.º 8
0
def init(device_name, read_rr_graph):
    global ic
    ic = icebox.iceconfig()
    {
        #'t4':  ic.setup_empty_t4,
        '8k': ic.setup_empty_8k,
        '5k': ic.setup_empty_5k,
        '1k': ic.setup_empty_1k,
        '384': ic.setup_empty_384,
    }[device_name]()

    print('Loading rr_graph')
    g = graph.Graph(read_rr_graph, clear_fabric=True)
    g.set_tooling(name="icebox",
                  version="dev",
                  comment="Generated for iCE40 {} device".format(device_name))

    return ic, g
Ejemplo n.º 9
0
def init(device_name, read_rr_graph):
    ic = icebox.iceconfig()
    {
        #'t4':  ic.setup_empty_t4,
        '8k': ic.setup_empty_8k,
        '5k': ic.setup_empty_5k,
        '1k': ic.setup_empty_1k,
        '384': ic.setup_empty_384,
    }[device_name]()
    fn_dir = {
        't4': 'test4',
        '8k': 'HX8K',
        '5k': 'HX5K',
        '1k': 'HX1K',
        '384': 'LP384',
    }[device_name]
    if read_rr_graph:
        ref_rr_fn = read_rr_graph
    else:
        ref_rr_fn = '../../tests/build/ice40/{}/wire.rr_graph.xml'.format(
            fn_dir)

    # Load g stuff we care about
    # (basically omit rr_nodes)
    # clear_fabric reduces load time from about 11.1 => 2.8 sec on my machine
    # seems to be mostly from the edges?
    print('Loading rr_graph')
    g = graph.Graph(ref_rr_fn, clear_fabric=True)
    g.set_tooling(name="icebox",
                  version="dev",
                  comment="Generated for iCE40 {} device".format(device_name))

    print('Indexing icebox net names')
    nn = NetNames(ic)

    return ic, g, nn
Ejemplo n.º 10
0
        fixup_mode = True
    else:
        usage()

if len(args) == 0:
    args.append("/dev/stdin")

if len(args) not in [1, 2]:
    usage()

if check_mode == fixup_mode:
    print("Error: Use either -c or -f!")
    sys.exit(1)

print("Reading file '%s'.." % args[0])
ic = icebox.iceconfig()
ic.read_file(args[0])


def make_cache(stmt, raw_db):
    cache = list()
    for entry in raw_db:
        if entry[1] == stmt and entry[2].startswith("glb_netwk_"):
            cache_entry = [int(entry[2][-1]), []]
            for bit in entry[0]:
                value = "1"
                if bit.startswith("!"):
                    value = "0"
                    bit = bit[1:]
                match = re_match_cached("B([0-9]+)\[([0-9]+)\]", bit)
                cache_entry[1].append(
Ejemplo n.º 11
0
#  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
#  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

import icebox
import sys
import re

if len(sys.argv) != 3:
    print("""
Usage: icebox_diff bitmap1.txt bitmap2.txt
""")
    sys.exit(0)

print("Reading file '%s'.." % sys.argv[1])
ic1 = icebox.iceconfig()
ic1.read_file(sys.argv[1])

print("Reading file '%s'.." % sys.argv[2])
ic2 = icebox.iceconfig()
ic2.read_file(sys.argv[2])

def format_bits(line_nr, this_line, other_line):
    text = ""
    for i in range(len(this_line)):
        if this_line[i] != other_line[i]:
            if this_line[i] == "1":
                text += "%8s" % ("B%d[%d]" % (line_nr, i))
            else:
                text += "%8s" % ""
    return text
Ejemplo n.º 12
0
        tx = int(a)
    elif o == "-y":
        ty = int(a)
    elif o == "-d":
        outdir = a
    elif o == "-8":
        mode8k = True
        chipname = "iCE40 HX8K"
        chipdbfile = "chipdb-8k.txt"
    else:
        usage()

if len(args) != 0:
    usage()

ic = icebox.iceconfig()

mktiles = set()

if mode8k:
    ic.setup_empty_8k()

    for x in range(1, 3) + range(8-2, 8+3) + range(15, 19) + range(25-2, 25+3) + range(33-2, 33):
        mktiles.add((x, 0))
        mktiles.add((x, 33))

    for x in range(0, 3) + range(8-1, 8+2) + range(25-1, 25+2) + range(33-2, 34):
        mktiles.add((x, 1))
        mktiles.add((x, 32))

    for x in range(0, 2) + range(8-1, 8+2) + range(25-1, 25+2) + range(34-2, 34):
Ejemplo n.º 13
0
def main():
    program_short_name = os.path.basename(sys.argv[0])
    options = Options()

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'mA', ['help', 'version'])
    except getopt.GetoptError as e:
        sys.stderr.write("%s: %s\n" % (program_short_name, e.msg))
        sys.stderr.write("Try `%s --help' for more information.\n" %
                         program_short_name)
        sys.exit(1)

    for opt, arg in opts:
        if opt == '--help':
            sys.stderr.write("""\
Create a high-level representation from an ASCII bitstream.
Usage: %s [OPTION]... FILE

  -m                    print tile config bitmaps
  -A                    don't skip uninteresting tiles

      --help            display this help and exit
      --version         output version information and exit

If you have a bug report, please file an issue on github:
  https://github.com/rlutz/icestorm/issues
""" % program_short_name)
            sys.exit(0)

        if opt == '--version':
            sys.stderr.write("""\
icebox_asc2hlc - create a high-level representation from an ASCII bitstream
Copyright (C) 2017 Roland Lutz

This program is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
""")
            sys.exit(0)

        if opt == '-m':
            options.print_map = True
        elif opt == '-A':
            options.print_all = True

    if not args:
        sys.stderr.write("%s: missing argument\n" % (program_short_name))
        sys.stderr.write("Try `%s --help' for more information.\n" %
                         program_short_name)
        sys.exit(1)

    if len(args) != 1:
        sys.stderr.write("%s: too many arguments\n" % (program_short_name))
        sys.stderr.write("Try `%s --help' for more information.\n" %
                         program_short_name)
        sys.exit(1)

    ic = icebox.iceconfig()
    if args[0] == '-':
        ic.read_file('/dev/stdin')
    else:
        ic.read_file(args[0])

    fabric = Fabric(ic)
    fabric.printout(options)
Ejemplo n.º 14
0
def create_tracks(g, verbose=False):
    print("Block grid size: %s" % (g.block_grid.size, ))
    print("Channel grid size: %s" % (g.channels.size, ))

    import icebox
    ic = icebox.iceconfig()
    ic.setup_empty_384()

    #seg_timing = {'R_per_meter':420, 'C_per_meter':3.e-14}
    #segment = g.channels.create_segment('awesomesauce', timing=seg_timing)

    type_y = channel.Track.Type.Y
    type_x = channel.Track.Type.X
    bi_dir = channel.Track.Direction.BI

    short_xml = list(
        g._xml_graph.iterfind('//switches/switch/[@name="short"]'))[0]
    #short_xml.attrib['configurable'] = '0'
    #short_xml.attrib['buffered'] = '0'
    print("Rewrote short switch: ", ET.tostring(short_xml))

    #############################################################################
    # Internal Block wires
    #############################################################################
    segment_global = g.segments["global"]
    segment_dummy = g.segments["dummy"]
    segment_local = g.segments["local"]

    for block in g.block_grid:
        tname = block.block_type.name

        if tname == "EMPTY":
            continue

        print("=" * 75)
        begin, end = block.position, block.position

        # Locals
        for l_n in local_names:
            track, _track_node = g.create_xy_track(begin,
                                                   end,
                                                   segment_local,
                                                   typeh=type_y,
                                                   direction=bi_dir)

            print("{} - {}".format(block, l_n))

            g.routing.localnames.add(begin, l_n, _track_node)

        for g_n in global_names:
            track, _track_node = g.create_xy_track(begin,
                                                   end,
                                                   segment_global,
                                                   typeh=type_y,
                                                   direction=bi_dir)

            print("{} - {}".format(block, g_n))

            g.routing.localnames.add(begin, g_n, _track_node)

        # Padding ------------------------------------------------
        track, _track_node = g.create_xy_track(begin,
                                               end,
                                               segment_dummy,
                                               typeh=type_y,
                                               direction=bi_dir)
        print()
        # --------------------------------------------------------

        if tname == "BLK_TL-PLB":
            tracks = plb_tracks
        elif tname.startswith("BLK_TL-PIO"):
            tracks = io_tracks

        for d in tracks:
            s_type, d_type = segment_type(g, d)
            track, _track_node = g.create_xy_track(begin,
                                                   end,
                                                   s_type,
                                                   typeh=d_type,
                                                   direction=bi_dir)

            print("%s - Created track %s (%s)" % (block, d.aliases, track))

            g.routing.localnames.add(begin, d.name, _track_node)
            for alias in d.aliases:
                g.routing.localnames.add(begin, alias, _track_node)

    #############################################################################
    # Internal Block connections
    #############################################################################

    for src_block in g.block_grid:
        try:
            src_names = g.routing.localnames[src_block.position]
        except KeyError as e:
            print(src_block, e)
            continue

        print("=" * 75)

        pos = icepos(src_block.position)
        for entry in ic.tile_db(*pos):
            if not ic.tile_has_entry(*pos, entry):
                #print("{} - Skipping (tile_has_entry) {}".format(src_block, entry[1:]))
                continue
            if entry[1] not in ('buffer', 'routing'):
                #print("{} - Skipping (not buffer/routing) {}".format(src_block, entry[1:]))
                continue

            switch_type, src_name, dst_name = entry[1:]
            src_name = fix_name(src_name)
            dst_name = fix_name(dst_name)

            if src_name not in src_names:
                print("{} - Skipping (src not exist) **{}** -> {}".format(
                    src_block, src_name, dst_name))
                continue
            if dst_name not in src_names:
                print("{} - Skipping (dst not exist) {} -> **{}**".format(
                    src_block, src_name, dst_name))
                continue

            src_node = g.routing.localnames[(src_block.position, src_name)]
            dst_node = g.routing.localnames[(src_block.position, dst_name)]
            g.routing.create_edge_with_nodes(src_node, dst_node,
                                             g.switches[switch_type])

            xml_id = graph.RoutingGraph._get_xml_id

            if entry[1] == 'routing':
                g.routing.create_edge_with_nodes(dst_node, src_node,
                                                 g.switches[switch_type])

            dir_str = {
                'buffer': "->",
                'routing': "<->",
            }[entry[1]]

            print(
                src_block,
                src_name,
                xml_id(src_node),
                dir_str,
                dst_name,
                xml_id(dst_node),
            )

    #############################################################################
    # Block -> Block connections
    #############################################################################

    for src_block in g.block_grid:
        try:
            src_names = g.routing.localnames[src_block.position]
        except KeyError as e:
            print(src_block, e)
            continue

        for src_name, delta, dst_name in mappings:
            try:
                src_node = g.routing.localnames[(src_block.position, src_name)]
            except KeyError as e:
                print(src_name, "not found on", src_block, e)
                continue

            dst_pos = src_block.position + delta
            try:
                dst_node = g.routing.localnames[(dst_pos, dst_name)]
            except KeyError as e:
                print(dst_name, "not found on block", delta, "(which is",
                      dst_pos, ")", e)
                continue

            dst_block = g.block_grid[dst_pos]

            print("Found {}->{} on {} {} ({})".format(src_name, dst_name,
                                                      src_block, delta,
                                                      dst_block))
            g.routing.create_edge_with_nodes(src_node, dst_node,
                                             g.switches["short"])
Ejemplo n.º 15
0
def main():
    program_short_name = os.path.basename(sys.argv[0])
    options = Options()

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'mA', ['help', 'version'])
    except getopt.GetoptError as e:
        sys.stderr.write("%s: %s\n" % (program_short_name, e.msg))
        sys.stderr.write("Try `%s --help' for more information.\n"
                         % sys.argv[0])
        sys.exit(1)

    for opt, arg in opts:
        if opt == '--help':
            sys.stderr.write("""\
Create a high-level representation from an ASCII bitstream.
Usage: %s [OPTION]... FILE

  -m                    print tile config bitmaps
  -A                    don't skip uninteresting tiles

      --help            display this help and exit
      --version         output version information and exit

If you have a bug report, please file an issue on github:
  https://github.com/rlutz/icestorm/issues
""" % sys.argv[0])
            sys.exit(0)

        if opt == '--version':
            sys.stderr.write("""\
icebox_asc2hlc - create a high-level representation from an ASCII bitstream
Copyright (C) 2017 Roland Lutz

This program is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
""")
            sys.exit(0)

        if opt == '-m':
            options.print_map = True
        elif opt == '-A':
            options.print_all = True

    if not args:
        sys.stderr.write("%s: missing argument\n" % (program_short_name))
        sys.stderr.write("Try `%s --help' for more information.\n"
                         % sys.argv[0])
        sys.exit(1)

    if len(args) != 1:
        sys.stderr.write("%s: too many arguments\n" % (program_short_name))
        sys.stderr.write("Try `%s --help' for more information.\n"
                         % sys.argv[0])
        sys.exit(1)

    ic = icebox.iceconfig()
    if args[0] == '-':
        ic.read_file('/dev/stdin')
    else:
        ic.read_file(args[0])

    fabric = Fabric(ic)
    fabric.printout(options)
Ejemplo n.º 16
0
def fasm_to_asc(in_fasm, outf, device):
    """Convert an FASM input to an ASC file

    Set input enable defaults, RAM powerup, and enables all ColBufCtrl (until modeled in VPR see: #464)
    """

    ic = icebox.iceconfig()

    init_method_name = "setup_empty_{}".format(device.lower()[2:])
    assert hasattr(ic,
                   init_method_name), "no icebox method to init empty device"
    getattr(ic, init_method_name)()

    device_1k = ic.device == "1k"

    fasmdb = read_ice_db(ic)
    # TODO: upstream init "default" bitstream
    locs = [(x, y) for x in range(ic.max_x + 1) for y in range(ic.max_y + 1)]
    for tile_loc in locs:
        tile = ic.tile(*tile_loc)
        if tile is None:
            continue
        db = ic.tile_db(*tile_loc)
        tile_type = ic.tile_type(*tile_loc)
        for entry in db:
            if (device_1k and
                ((tile_type == "IO" and entry[-1] in ["IE_0", "IE_1"]) or
                 (tile_type == "RAMB" and entry[-1] == "PowerUp"))
                    or (entry[-2] == "ColBufCtrl")):
                tile_bits = _tile_to_array(tile)
                tile_type = ic.tile_type(*tile_loc)
                bm, bv = _get_iceconfig_bits(tile_bits, entry[0])
                tile_bits[bm] = bv[bm]
                _array_to_tile(tile_bits, tile)

    missing_features = []
    for line in fasm.parse_fasm_string(in_fasm.read()):
        if not line.set_feature:
            continue

        line_strs = tuple(fasm.fasm_line_to_string(line))
        assert len(line_strs) == 1

        feature = Feature.from_fasm_entry(
            FasmEntry(line.set_feature.feature, []))

        def find_ieren(ic, loc, iob):
            tmap = [
                xx[3:] for xx in ic.ieren_db()
                if xx[:3] == (tuple(loc) + (iob, ))
            ]
            assert len(tmap) < 2, "expected 1 IEREN_DB entry found {}".format(
                len(tmap))

            if len(tmap) == 0:
                print("no ieren found for {}".format((tile_loc + (iob, ))))
                return
            return tmap[0]

        # fix up for IO
        if feature.parts[-1] == "SimpleInput":
            iob = int(feature.parts[-2][-1])
            new_ieren = find_ieren(ic, feature.loc, iob)

            feature.parts[-1] = "PINTYPE_0"
            db_entry = fasmdb[feature.to_fasm_entry().feature]
            _set_feature_bits(ic, db_entry.loc, db_entry.bit_tuples)

            feature.loc = new_ieren[:2]
            feature.parts[-2] = "IoCtrl"
            feature.parts[-1] = "IE_{}".format(new_ieren[2])
            db_entry = fasmdb[feature.to_fasm_entry().feature]
            _set_feature_bits(ic, db_entry.loc, db_entry.bit_tuples)
            feature.parts[-1] = "REN_{}".format(new_ieren[2])
            db_entry = fasmdb[feature.to_fasm_entry().feature]
            _set_feature_bits(ic, db_entry.loc, db_entry.bit_tuples)
            continue

        if feature.parts[-1] == "SimpleOutput":
            iob = int(feature.parts[-2][-1])
            new_ieren = find_ieren(ic, feature.loc, iob)

            feature.parts[-1] = "PINTYPE_3"
            db_entry = fasmdb[feature.to_fasm_entry().feature]
            _set_feature_bits(ic, db_entry.loc, db_entry.bit_tuples)
            feature.parts[-1] = "PINTYPE_4"
            db_entry = fasmdb[feature.to_fasm_entry().feature]
            _set_feature_bits(ic, db_entry.loc, db_entry.bit_tuples)

            feature.loc = new_ieren[:2]
            feature.parts[-2] = "IoCtrl"
            feature.parts[-1] = "REN_{}".format(new_ieren[2])
            db_entry = fasmdb[feature.to_fasm_entry().feature]
            _set_feature_bits(ic, db_entry.loc, db_entry.bit_tuples)
            continue

        ## special case for RAM INIT values
        tile_type, loc = feature.tile_type, feature.loc
        if tile_type == "RAMB" and feature.parts[-1].startswith("INIT"):
            tloc = tuple(loc)
            if tloc not in ic.ram_data:
                ic.ram_data[tloc] = [64 * "0" for _ in range(16)]
            tile = ic.ram_data[tloc]
            tile_bits = _tile_to_array(tile, is_hex=True)
        elif tile_type == "RAMB" and feature.parts[-1].endswith("_MODE"):
            # hack to force modes to the RAMT
            tile = ic.tile(loc[0], loc[1] + 1)
            tile_bits = _tile_to_array(tile)
        else:
            tile = ic.tile(*loc)
            tile_bits = _tile_to_array(tile)

        # lookup feature and convert
        for canonical_feature in fasm.canonical_features(line.set_feature):
            key = fasm.set_feature_to_str(canonical_feature)
            feature = fasmdb[key]
            bm, bv = _get_feature_bits(tile_bits, feature.bit_tuples)

            tile_bits[bm] = bv[bm]

        if tile_type == "RAMB" and feature.parts[-1].startswith("INIT"):
            _array_to_tile(tile_bits, tile, is_hex=True)
        else:
            _array_to_tile(tile_bits, tile)

    # TODO: would be nice to upstream a way to write to non-files
    ic.write_file(outf.name)