17ec681f3Smrg#
27ec681f3Smrg# Copyright © 2020 Google, Inc.
37ec681f3Smrg#
47ec681f3Smrg# Permission is hereby granted, free of charge, to any person obtaining a
57ec681f3Smrg# copy of this software and associated documentation files (the "Software"),
67ec681f3Smrg# to deal in the Software without restriction, including without limitation
77ec681f3Smrg# the rights to use, copy, modify, merge, publish, distribute, sublicense,
87ec681f3Smrg# and/or sell copies of the Software, and to permit persons to whom the
97ec681f3Smrg# Software is furnished to do so, subject to the following conditions:
107ec681f3Smrg#
117ec681f3Smrg# The above copyright notice and this permission notice (including the next
127ec681f3Smrg# paragraph) shall be included in all copies or substantial portions of the
137ec681f3Smrg# Software.
147ec681f3Smrg#
157ec681f3Smrg# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
167ec681f3Smrg# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
177ec681f3Smrg# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
187ec681f3Smrg# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
197ec681f3Smrg# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
207ec681f3Smrg# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
217ec681f3Smrg# IN THE SOFTWARE.
227ec681f3Smrg
237ec681f3Smrgfrom xml.etree import ElementTree
247ec681f3Smrgimport os
257ec681f3Smrgimport re
267ec681f3Smrg
277ec681f3Smrgdef dbg(str):
287ec681f3Smrg    if False:
297ec681f3Smrg        print(str)
307ec681f3Smrg
317ec681f3Smrgclass BitSetPattern(object):
327ec681f3Smrg    """Class that encapsulated the pattern matching, ie.
337ec681f3Smrg       the match/dontcare/mask bitmasks.  The following
347ec681f3Smrg       rules should hold
357ec681f3Smrg
367ec681f3Smrg          (match ^ dontcare) == 0
377ec681f3Smrg          (match || dontcare) == mask
387ec681f3Smrg
397ec681f3Smrg       For a leaf node, the mask should be (1 << size) - 1
407ec681f3Smrg       (ie. all bits set)
417ec681f3Smrg    """
427ec681f3Smrg    def __init__(self, bitset):
437ec681f3Smrg        self.match      = bitset.match
447ec681f3Smrg        self.dontcare   = bitset.dontcare
457ec681f3Smrg        self.mask       = bitset.mask
467ec681f3Smrg        self.field_mask = bitset.field_mask;
477ec681f3Smrg
487ec681f3Smrg    def merge(self, pattern):
497ec681f3Smrg        p = BitSetPattern(pattern)
507ec681f3Smrg        p.match      = p.match      | self.match
517ec681f3Smrg        p.dontcare   = p.dontcare   | self.dontcare
527ec681f3Smrg        p.mask       = p.mask       | self.mask
537ec681f3Smrg        p.field_mask = p.field_mask | self.field_mask
547ec681f3Smrg        return p
557ec681f3Smrg
567ec681f3Smrg    def defined_bits(self):
577ec681f3Smrg        return self.match | self.dontcare | self.mask | self.field_mask
587ec681f3Smrg
597ec681f3Smrgdef get_bitrange(field):
607ec681f3Smrg    if 'pos' in field.attrib:
617ec681f3Smrg        assert('low' not in field.attrib)
627ec681f3Smrg        assert('high' not in field.attrib)
637ec681f3Smrg        low = int(field.attrib['pos'])
647ec681f3Smrg        high = low
657ec681f3Smrg    else:
667ec681f3Smrg        low = int(field.attrib['low'])
677ec681f3Smrg        high = int(field.attrib['high'])
687ec681f3Smrg    assert low <= high
697ec681f3Smrg    return low, high
707ec681f3Smrg
717ec681f3Smrgdef extract_pattern(xml, name, is_defined_bits=None):
727ec681f3Smrg    low, high = get_bitrange(xml)
737ec681f3Smrg    mask = ((1 << (1 + high - low)) - 1) << low
747ec681f3Smrg
757ec681f3Smrg    patstr = xml.text.strip()
767ec681f3Smrg
777ec681f3Smrg    assert (len(patstr) == (1 + high - low)), "Invalid {} length in {}: {}..{}".format(xml.tag, name, low, high)
787ec681f3Smrg    if is_defined_bits is not None:
797ec681f3Smrg        assert not is_defined_bits(mask), "Redefined bits in {} {}: {}..{}".format(xml.tag, name, low, high);
807ec681f3Smrg
817ec681f3Smrg    match = 0;
827ec681f3Smrg    dontcare = 0
837ec681f3Smrg
847ec681f3Smrg    for n in range(0, len(patstr)):
857ec681f3Smrg        match = match << 1
867ec681f3Smrg        dontcare = dontcare << 1
877ec681f3Smrg        if patstr[n] == '1':
887ec681f3Smrg            match |= 1
897ec681f3Smrg        elif patstr[n] == 'x':
907ec681f3Smrg            dontcare |= 1
917ec681f3Smrg        elif patstr[n] != '0':
927ec681f3Smrg            assert 0, "Invalid {} character in {}: {}".format(xml.tag, name, patstr[n])
937ec681f3Smrg
947ec681f3Smrg    dbg("{}: {}.{} => {:016x} / {:016x} / {:016x}".format(xml.tag, name, patstr, match << low, dontcare << low, mask))
957ec681f3Smrg
967ec681f3Smrg    return match << low, dontcare << low, mask
977ec681f3Smrg
987ec681f3Smrgdef get_c_name(name):
997ec681f3Smrg    return name.lower().replace('#', '__').replace('-', '_').replace('.', '_')
1007ec681f3Smrg
1017ec681f3Smrgclass BitSetField(object):
1027ec681f3Smrg    """Class that encapsulates a field defined in a bitset
1037ec681f3Smrg    """
1047ec681f3Smrg    def __init__(self, isa, xml):
1057ec681f3Smrg        self.isa = isa
1067ec681f3Smrg        self.low, self.high = get_bitrange(xml)
1077ec681f3Smrg        self.name = xml.attrib['name']
1087ec681f3Smrg        self.type = xml.attrib['type']
1097ec681f3Smrg        self.params = []
1107ec681f3Smrg        for param in xml.findall('param'):
1117ec681f3Smrg            aas = name = param.attrib['name']
1127ec681f3Smrg            if 'as' in param.attrib:
1137ec681f3Smrg                aas = param.attrib['as']
1147ec681f3Smrg            self.params.append([name, aas])
1157ec681f3Smrg        self.expr = None
1167ec681f3Smrg        self.display = None
1177ec681f3Smrg        if 'display' in xml.attrib:
1187ec681f3Smrg            self.display = xml.attrib['display'].strip()
1197ec681f3Smrg
1207ec681f3Smrg    def get_c_name(self):
1217ec681f3Smrg        return get_c_name(self.name)
1227ec681f3Smrg
1237ec681f3Smrg    def get_c_typename(self):
1247ec681f3Smrg        if self.type in self.isa.enums:
1257ec681f3Smrg            return 'TYPE_ENUM'
1267ec681f3Smrg        if self.type in self.isa.bitsets:
1277ec681f3Smrg            return 'TYPE_BITSET'
1287ec681f3Smrg        return 'TYPE_' + self.type.upper()
1297ec681f3Smrg
1307ec681f3Smrg    def mask(self):
1317ec681f3Smrg        return ((1 << self.get_size()) - 1) << self.low
1327ec681f3Smrg
1337ec681f3Smrg    def get_size(self):
1347ec681f3Smrg        return 1 + self.high - self.low
1357ec681f3Smrg
1367ec681f3Smrgclass BitSetAssertField(BitSetField):
1377ec681f3Smrg    """Similar to BitSetField, but for <assert/>s, which can be
1387ec681f3Smrg       used to specify that a certain bitpattern is expected in
1397ec681f3Smrg       place of (for example) unused bitfields
1407ec681f3Smrg    """
1417ec681f3Smrg    def __init__(self, case, xml):
1427ec681f3Smrg        self.isa = case.bitset.isa
1437ec681f3Smrg        self.low, self.high = get_bitrange(xml)
1447ec681f3Smrg        self.name = case.bitset.name + '#assert' + str(len(case.fields))
1457ec681f3Smrg        self.type = 'uint'
1467ec681f3Smrg        self.expr = None
1477ec681f3Smrg        self.display = None
1487ec681f3Smrg
1497ec681f3Smrg        match, dontcare, mask = extract_pattern(xml, case.bitset.name)
1507ec681f3Smrg        self.val = match >> self.low
1517ec681f3Smrg
1527ec681f3Smrg        assert dontcare == 0, "'x' (dontcare) is not valid in an assert"
1537ec681f3Smrg
1547ec681f3Smrg    def get_c_typename(self):
1557ec681f3Smrg        return 'TYPE_ASSERT'
1567ec681f3Smrg
1577ec681f3Smrgclass BitSetDerivedField(BitSetField):
1587ec681f3Smrg    """Similar to BitSetField, but for derived fields
1597ec681f3Smrg    """
1607ec681f3Smrg    def __init__(self, isa, xml):
1617ec681f3Smrg        self.isa = isa
1627ec681f3Smrg        self.low = 0
1637ec681f3Smrg        self.high = 0
1647ec681f3Smrg        # NOTE: a width should be provided for 'int' derived fields, ie.
1657ec681f3Smrg        # where sign extension is needed.  We just repurpose the 'high'
1667ec681f3Smrg        # field for that to make '1 + high - low' work out
1677ec681f3Smrg        if 'width' in xml.attrib:
1687ec681f3Smrg            self.high = xml.attrib['width'] + ' - 1'
1697ec681f3Smrg        self.name = xml.attrib['name']
1707ec681f3Smrg        self.type = xml.attrib['type']
1717ec681f3Smrg        if 'expr' in xml.attrib:
1727ec681f3Smrg            self.expr = xml.attrib['expr']
1737ec681f3Smrg        else:
1747ec681f3Smrg            e = isa.parse_one_expression(xml, self.name)
1757ec681f3Smrg            self.expr = e.name
1767ec681f3Smrg        self.display = None
1777ec681f3Smrg        if 'display' in xml.attrib:
1787ec681f3Smrg            self.display = xml.attrib['display'].strip()
1797ec681f3Smrg
1807ec681f3Smrgclass BitSetCase(object):
1817ec681f3Smrg    """Class that encapsulates a single bitset case
1827ec681f3Smrg    """
1837ec681f3Smrg    def __init__(self, bitset, xml, update_field_mask, expr=None):
1847ec681f3Smrg        self.bitset = bitset
1857ec681f3Smrg        if expr is not None:
1867ec681f3Smrg            self.name = bitset.name + '#case' + str(len(bitset.cases))
1877ec681f3Smrg        else:
1887ec681f3Smrg            self.name = bitset.name + "#default"
1897ec681f3Smrg        self.expr = expr
1907ec681f3Smrg        self.fields = {}
1917ec681f3Smrg
1927ec681f3Smrg        for derived in xml.findall('derived'):
1937ec681f3Smrg            f = BitSetDerivedField(bitset.isa, derived)
1947ec681f3Smrg            self.fields[f.name] = f
1957ec681f3Smrg
1967ec681f3Smrg        for assrt in xml.findall('assert'):
1977ec681f3Smrg            f = BitSetAssertField(self, assrt)
1987ec681f3Smrg            update_field_mask(self, f)
1997ec681f3Smrg            self.fields[f.name] = f
2007ec681f3Smrg
2017ec681f3Smrg        for field in xml.findall('field'):
2027ec681f3Smrg            dbg("{}.{}".format(self.name, field.attrib['name']))
2037ec681f3Smrg            f = BitSetField(bitset.isa, field)
2047ec681f3Smrg            update_field_mask(self, f)
2057ec681f3Smrg            self.fields[f.name] = f
2067ec681f3Smrg
2077ec681f3Smrg        self.display = None
2087ec681f3Smrg        for d in xml.findall('display'):
2097ec681f3Smrg            # Allow <display/> for empty display string:
2107ec681f3Smrg            if d.text is not None:
2117ec681f3Smrg                self.display = d.text.strip()
2127ec681f3Smrg            else:
2137ec681f3Smrg                self.display = ''
2147ec681f3Smrg            dbg("found display: '{}'".format(self.display))
2157ec681f3Smrg
2167ec681f3Smrg    def get_c_name(self):
2177ec681f3Smrg        return get_c_name(self.name)
2187ec681f3Smrg
2197ec681f3Smrgclass BitSetEncode(object):
2207ec681f3Smrg    """Additional data that may be associated with a root bitset node
2217ec681f3Smrg       to provide additional information needed to generate helpers
2227ec681f3Smrg       to encode the bitset, such as source data type and "opcode"
2237ec681f3Smrg       case prefix (ie. how to choose/enumerate which leaf node bitset
2247ec681f3Smrg       to use to encode the source data
2257ec681f3Smrg    """
2267ec681f3Smrg    def __init__(self, xml):
2277ec681f3Smrg        self.type = None
2287ec681f3Smrg        if 'type' in xml.attrib:
2297ec681f3Smrg            self.type = xml.attrib['type']
2307ec681f3Smrg        self.case_prefix = None
2317ec681f3Smrg        if 'case-prefix' in xml.attrib:
2327ec681f3Smrg            self.case_prefix = xml.attrib['case-prefix']
2337ec681f3Smrg        # The encode element may also contain mappings from encode src
2347ec681f3Smrg        # to individual field names:
2357ec681f3Smrg        self.maps = {}
2367ec681f3Smrg        self.forced = {}
2377ec681f3Smrg        for map in xml.findall('map'):
2387ec681f3Smrg            name = map.attrib['name']
2397ec681f3Smrg            self.maps[name] = map.text.strip()
2407ec681f3Smrg            if 'force' in map.attrib and map.attrib['force']  == 'true':
2417ec681f3Smrg                self.forced[name] = 'true'
2427ec681f3Smrg
2437ec681f3Smrgclass BitSet(object):
2447ec681f3Smrg    """Class that encapsulates a single bitset rule
2457ec681f3Smrg    """
2467ec681f3Smrg    def __init__(self, isa, xml):
2477ec681f3Smrg        self.isa = isa
2487ec681f3Smrg        self.xml = xml
2497ec681f3Smrg        self.name = xml.attrib['name']
2507ec681f3Smrg
2517ec681f3Smrg        # Used for generated encoder, to de-duplicate encoding for
2527ec681f3Smrg        # similar instructions:
2537ec681f3Smrg        self.snippets = {}
2547ec681f3Smrg
2557ec681f3Smrg        if 'size' in xml.attrib:
2567ec681f3Smrg            assert('extends' not in xml.attrib)
2577ec681f3Smrg            self.size = int(xml.attrib['size'])
2587ec681f3Smrg            self.extends = None
2597ec681f3Smrg        else:
2607ec681f3Smrg            self.size = None
2617ec681f3Smrg            self.extends = xml.attrib['extends']
2627ec681f3Smrg
2637ec681f3Smrg        self.encode = None
2647ec681f3Smrg        if xml.find('encode') is not None:
2657ec681f3Smrg            self.encode = BitSetEncode(xml.find('encode'))
2667ec681f3Smrg
2677ec681f3Smrg        self.gen_min = 0
2687ec681f3Smrg        self.gen_max = ~0
2697ec681f3Smrg
2707ec681f3Smrg        for gen in xml.findall('gen'):
2717ec681f3Smrg            if 'min' in gen.attrib:
2727ec681f3Smrg                self.gen_min = gen.attrib['min']
2737ec681f3Smrg            if 'max' in gen.attrib:
2747ec681f3Smrg                self.gen_max = gen.attrib['max']
2757ec681f3Smrg
2767ec681f3Smrg        # Collect up the match/dontcare/mask bitmasks for
2777ec681f3Smrg        # this bitset case:
2787ec681f3Smrg        self.match = 0
2797ec681f3Smrg        self.dontcare = 0
2807ec681f3Smrg        self.mask = 0
2817ec681f3Smrg        self.field_mask = 0
2827ec681f3Smrg
2837ec681f3Smrg        self.cases = []
2847ec681f3Smrg
2857ec681f3Smrg        # Helper to check for redefined bits:
2867ec681f3Smrg        def is_defined_bits(m):
2877ec681f3Smrg            return ((self.field_mask | self.mask | self.dontcare | self.match) & m) != 0
2887ec681f3Smrg
2897ec681f3Smrg        def update_default_bitmask_field(bs, field):
2907ec681f3Smrg            m = field.mask()
2917ec681f3Smrg            dbg("field: {}.{} => {:016x}".format(self.name, field.name, m))
2927ec681f3Smrg            # For default case, we don't expect any bits to be doubly defined:
2937ec681f3Smrg            assert not is_defined_bits(m), "Redefined bits in field {}.{}: {}..{}".format(
2947ec681f3Smrg                self.name, field.name, field.low, field.high);
2957ec681f3Smrg            self.field_mask |= m
2967ec681f3Smrg
2977ec681f3Smrg        def update_override_bitmask_field(bs, field):
2987ec681f3Smrg            m = field.mask()
2997ec681f3Smrg            dbg("field: {}.{} => {:016x}".format(self.name, field.name, m))
3007ec681f3Smrg            assert self.field_mask ^ ~m
3017ec681f3Smrg
3027ec681f3Smrg        dflt = BitSetCase(self, xml, update_default_bitmask_field)
3037ec681f3Smrg
3047ec681f3Smrg        for override in xml.findall('override'):
3057ec681f3Smrg            if 'expr' in override.attrib:
3067ec681f3Smrg                expr = override.attrib['expr']
3077ec681f3Smrg            else:
3087ec681f3Smrg                e = isa.parse_one_expression(override, self.name)
3097ec681f3Smrg                expr = e.name
3107ec681f3Smrg            c = BitSetCase(self, override, update_override_bitmask_field, expr)
3117ec681f3Smrg            self.cases.append(c)
3127ec681f3Smrg
3137ec681f3Smrg        # Default case is expected to be the last one:
3147ec681f3Smrg        self.cases.append(dflt)
3157ec681f3Smrg
3167ec681f3Smrg        for pattern in xml.findall('pattern'):
3177ec681f3Smrg            match, dontcare, mask = extract_pattern(pattern, self.name, is_defined_bits)
3187ec681f3Smrg
3197ec681f3Smrg            self.match    |= match
3207ec681f3Smrg            self.dontcare |= dontcare
3217ec681f3Smrg            self.mask     |= mask
3227ec681f3Smrg
3237ec681f3Smrg    def get_pattern(self):
3247ec681f3Smrg        if self.extends is not None:
3257ec681f3Smrg            parent = self.isa.bitsets[self.extends]
3267ec681f3Smrg            ppat = parent.get_pattern()
3277ec681f3Smrg            pat  = BitSetPattern(self)
3287ec681f3Smrg
3297ec681f3Smrg            assert ((ppat.defined_bits() & pat.defined_bits()) == 0), "bitset conflict in {}: {:x}".format(self.name, (ppat.defined_bits() & pat.defined_bits()))
3307ec681f3Smrg
3317ec681f3Smrg            return pat.merge(ppat)
3327ec681f3Smrg
3337ec681f3Smrg        return BitSetPattern(self)
3347ec681f3Smrg
3357ec681f3Smrg    def get_size(self):
3367ec681f3Smrg        if self.extends is not None:
3377ec681f3Smrg            parent = self.isa.bitsets[self.extends]
3387ec681f3Smrg            return parent.get_size()
3397ec681f3Smrg        return self.size
3407ec681f3Smrg
3417ec681f3Smrg    def get_c_name(self):
3427ec681f3Smrg        return get_c_name(self.name)
3437ec681f3Smrg
3447ec681f3Smrg    def get_root(self):
3457ec681f3Smrg        if self.extends is not None:
3467ec681f3Smrg            return self.isa.bitsets[self.extends].get_root()
3477ec681f3Smrg        return self
3487ec681f3Smrg
3497ec681f3Smrgclass BitSetEnum(object):
3507ec681f3Smrg    """Class that encapsulates an enum declaration
3517ec681f3Smrg    """
3527ec681f3Smrg    def __init__(self, isa, xml):
3537ec681f3Smrg        self.isa = isa
3547ec681f3Smrg        self.name = xml.attrib['name']
3557ec681f3Smrg        # Table mapping value to name
3567ec681f3Smrg        # TODO currently just mapping to 'display' name, but if we
3577ec681f3Smrg        # need more attributes then maybe need BitSetEnumValue?
3587ec681f3Smrg        self.values = {}
3597ec681f3Smrg        for value in xml.findall('value'):
3607ec681f3Smrg            self.values[value.attrib['val']] = value.attrib['display']
3617ec681f3Smrg
3627ec681f3Smrg    def get_c_name(self):
3637ec681f3Smrg        return 'enum_' + get_c_name(self.name)
3647ec681f3Smrg
3657ec681f3Smrgclass BitSetExpression(object):
3667ec681f3Smrg    """Class that encapsulates an <expr> declaration
3677ec681f3Smrg    """
3687ec681f3Smrg    def __init__(self, isa, xml):
3697ec681f3Smrg        self.isa = isa
3707ec681f3Smrg        if 'name' in xml.attrib:
3717ec681f3Smrg            self.name = xml.attrib['name']
3727ec681f3Smrg        else:
3737ec681f3Smrg            self.name = 'anon_' + str(isa.anon_expression_count)
3747ec681f3Smrg            isa.anon_expression_count = isa.anon_expression_count + 1
3757ec681f3Smrg        expr = xml.text.strip()
3767ec681f3Smrg        self.fieldnames = list(set(re.findall(r"{([a-zA-Z0-9_]+)}", expr)))
3777ec681f3Smrg        self.expr = re.sub(r"{([a-zA-Z0-9_]+)}", r"\1", expr)
3787ec681f3Smrg        dbg("'{}' -> '{}'".format(expr, self.expr))
3797ec681f3Smrg
3807ec681f3Smrg    def get_c_name(self):
3817ec681f3Smrg        return 'expr_' + get_c_name(self.name)
3827ec681f3Smrg
3837ec681f3Smrgclass ISA(object):
3847ec681f3Smrg    """Class that encapsulates all the parsed bitset rules
3857ec681f3Smrg    """
3867ec681f3Smrg    def __init__(self, xmlpath):
3877ec681f3Smrg        self.base_path = os.path.dirname(xmlpath)
3887ec681f3Smrg
3897ec681f3Smrg        # Counter used to name inline (anonymous) expressions:
3907ec681f3Smrg        self.anon_expression_count = 0
3917ec681f3Smrg
3927ec681f3Smrg        # Table of (globally defined) expressions:
3937ec681f3Smrg        self.expressions = {}
3947ec681f3Smrg
3957ec681f3Smrg        # Table of enums:
3967ec681f3Smrg        self.enums = {}
3977ec681f3Smrg
3987ec681f3Smrg        # Table of toplevel bitset hierarchies:
3997ec681f3Smrg        self.roots = {}
4007ec681f3Smrg
4017ec681f3Smrg        # Table of leaf nodes of bitset hierarchies:
4027ec681f3Smrg        self.leafs = {}
4037ec681f3Smrg
4047ec681f3Smrg        # Table of all bitsets:
4057ec681f3Smrg        self.bitsets = {}
4067ec681f3Smrg
4077ec681f3Smrg        # Max needed bitsize for one instruction
4087ec681f3Smrg        self.bitsize = 0
4097ec681f3Smrg
4107ec681f3Smrg        root = ElementTree.parse(xmlpath).getroot()
4117ec681f3Smrg        self.parse_file(root)
4127ec681f3Smrg        self.validate_isa()
4137ec681f3Smrg
4147ec681f3Smrg    def parse_expressions(self, root):
4157ec681f3Smrg        e = None
4167ec681f3Smrg        for expr in root.findall('expr'):
4177ec681f3Smrg            e = BitSetExpression(self, expr)
4187ec681f3Smrg            self.expressions[e.name] = e
4197ec681f3Smrg        return e
4207ec681f3Smrg
4217ec681f3Smrg    def parse_one_expression(self, root, name):
4227ec681f3Smrg        assert len(root.findall('expr')) == 1, "expected a single expression in: {}".format(name)
4237ec681f3Smrg        return self.parse_expressions(root)
4247ec681f3Smrg
4257ec681f3Smrg    def parse_file(self, root):
4267ec681f3Smrg        # Handle imports up-front:
4277ec681f3Smrg        for imprt in root.findall('import'):
4287ec681f3Smrg            p = os.path.join(self.base_path, imprt.attrib['file'])
4297ec681f3Smrg            self.parse_file(ElementTree.parse(p))
4307ec681f3Smrg
4317ec681f3Smrg        # Extract expressions:
4327ec681f3Smrg        self.parse_expressions(root)
4337ec681f3Smrg
4347ec681f3Smrg        # Extract enums:
4357ec681f3Smrg        for enum in root.findall('enum'):
4367ec681f3Smrg            e = BitSetEnum(self, enum)
4377ec681f3Smrg            self.enums[e.name] = e
4387ec681f3Smrg
4397ec681f3Smrg        # Extract bitsets:
4407ec681f3Smrg        for bitset in root.findall('bitset'):
4417ec681f3Smrg            b = BitSet(self, bitset)
4427ec681f3Smrg            if b.size is not None:
4437ec681f3Smrg                dbg("toplevel: " + b.name)
4447ec681f3Smrg                self.roots[b.name] = b
4457ec681f3Smrg                self.bitsize = max(self.bitsize, b.size)
4467ec681f3Smrg            else:
4477ec681f3Smrg                dbg("derived: " + b.name)
4487ec681f3Smrg            self.bitsets[b.name] = b
4497ec681f3Smrg            self.leafs[b.name]  = b
4507ec681f3Smrg
4517ec681f3Smrg        # Remove non-leaf nodes from the leafs table:
4527ec681f3Smrg        for name, bitset in self.bitsets.items():
4537ec681f3Smrg            if bitset.extends is not None:
4547ec681f3Smrg                if bitset.extends in self.leafs:
4557ec681f3Smrg                    del self.leafs[bitset.extends]
4567ec681f3Smrg
4577ec681f3Smrg    def validate_isa(self):
4587ec681f3Smrg        # Validate that all bitset fields have valid types, and in
4597ec681f3Smrg        # the case of bitset type, the sizes match:
4607ec681f3Smrg        builtin_types = ['branch', 'int', 'uint', 'hex', 'offset', 'uoffset', 'float', 'bool', 'enum']
4617ec681f3Smrg        for bitset_name, bitset in self.bitsets.items():
4627ec681f3Smrg            if bitset.extends is not None:
4637ec681f3Smrg                assert bitset.extends in self.bitsets, "{} extends invalid type: {}".format(
4647ec681f3Smrg                    bitset_name, bitset.extends)
4657ec681f3Smrg            for case in bitset.cases:
4667ec681f3Smrg                for field_name, field in case.fields.items():
4677ec681f3Smrg                    if field.type == 'float':
4687ec681f3Smrg                        assert field.get_size() == 32 or field.get_size() == 16
4697ec681f3Smrg
4707ec681f3Smrg                    if not isinstance(field, BitSetDerivedField):
4717ec681f3Smrg                        assert field.high < bitset.get_size(), \
4727ec681f3Smrg                            "{}.{}: invalid bit range: [{}, {}] is not in [{}, {}]".format(
4737ec681f3Smrg                            bitset_name, field_name, field.low, field.high, 0, bitset.get_size() - 1)
4747ec681f3Smrg
4757ec681f3Smrg                    if field.type in builtin_types:
4767ec681f3Smrg                        continue
4777ec681f3Smrg                    if field.type in self.enums:
4787ec681f3Smrg                        continue
4797ec681f3Smrg                    assert field.type in self.bitsets, "{}.{}: invalid type: {}".format(
4807ec681f3Smrg                        bitset_name, field_name, field.type)
4817ec681f3Smrg                    bs = self.bitsets[field.type]
4827ec681f3Smrg                    assert field.get_size() == bs.get_size(), "{}.{}: invalid size: {} vs {}".format(
4837ec681f3Smrg                        bitset_name, field_name, field.get_size(), bs.get_size())
4847ec681f3Smrg
4857ec681f3Smrg        # Validate that all the leaf node bitsets have no remaining
4867ec681f3Smrg        # undefined bits
4877ec681f3Smrg        for name, bitset in self.leafs.items():
4887ec681f3Smrg            pat = bitset.get_pattern()
4897ec681f3Smrg            sz  = bitset.get_size()
4907ec681f3Smrg            assert ((pat.mask | pat.field_mask) == (1 << sz) - 1), "leaf bitset {} has undefined bits: {:x}".format(
4917ec681f3Smrg                bitset.name, ~(pat.mask | pat.field_mask) & ((1 << sz) - 1))
4927ec681f3Smrg
4937ec681f3Smrg        # TODO somehow validating that only one bitset in a hierarchy
4947ec681f3Smrg        # matches any given bit pattern would be useful.
4957ec681f3Smrg
4967ec681f3Smrg        # TODO we should probably be able to look at the contexts where
4977ec681f3Smrg        # an expression is evaluated and verify that it doesn't have any
4987ec681f3Smrg        # {VARNAME} references that would be unresolved at evaluation time
4997ec681f3Smrg
5007ec681f3Smrg    def format(self):
5017ec681f3Smrg        ''' Generate format string used by printf(..) and friends '''
5027ec681f3Smrg        parts = []
5037ec681f3Smrg        words = self.bitsize / 32
5047ec681f3Smrg
5057ec681f3Smrg        for i in range(int(words)):
5067ec681f3Smrg            parts.append('%08x')
5077ec681f3Smrg
5087ec681f3Smrg        fmt = ''.join(parts)
5097ec681f3Smrg
5107ec681f3Smrg        return f"\"{fmt[1:]}\""
5117ec681f3Smrg
5127ec681f3Smrg    def value(self):
5137ec681f3Smrg        ''' Generate format values used by printf(..) and friends '''
5147ec681f3Smrg        parts = []
5157ec681f3Smrg        words = self.bitsize / 32
5167ec681f3Smrg
5177ec681f3Smrg        for i in range(int(words) - 1, -1, -1):
5187ec681f3Smrg            parts.append('v[' + str(i) + ']')
5197ec681f3Smrg
5207ec681f3Smrg        return ', '.join(parts)
5217ec681f3Smrg
5227ec681f3Smrg    def split_bits(self, value):
5237ec681f3Smrg        ''' Split `value` into a list of 32-bit integers '''
5247ec681f3Smrg        mask, parts = (1 << 32) - 1, []
5257ec681f3Smrg        words = self.bitsize / 32
5267ec681f3Smrg
5277ec681f3Smrg        while value:
5287ec681f3Smrg            parts.append(hex(value & mask))
5297ec681f3Smrg            value >>= 32
5307ec681f3Smrg
5317ec681f3Smrg        # Add 'missing' words
5327ec681f3Smrg        while len(parts) < words:
5337ec681f3Smrg            parts.append('0x0')
5347ec681f3Smrg
5357ec681f3Smrg        return parts
536