17ec681f3Smrg#encoding=utf-8
27ec681f3Smrg
37ec681f3Smrg# Copyright (C) 2016 Intel Corporation
47ec681f3Smrg# Copyright (C) 2016 Broadcom
57ec681f3Smrg# Copyright (C) 2020 Collabora, Ltd.
67ec681f3Smrg#
77ec681f3Smrg# Permission is hereby granted, free of charge, to any person obtaining a
87ec681f3Smrg# copy of this software and associated documentation files (the "Software"),
97ec681f3Smrg# to deal in the Software without restriction, including without limitation
107ec681f3Smrg# the rights to use, copy, modify, merge, publish, distribute, sublicense,
117ec681f3Smrg# and/or sell copies of the Software, and to permit persons to whom the
127ec681f3Smrg# Software is furnished to do so, subject to the following conditions:
137ec681f3Smrg#
147ec681f3Smrg# The above copyright notice and this permission notice (including the next
157ec681f3Smrg# paragraph) shall be included in all copies or substantial portions of the
167ec681f3Smrg# Software.
177ec681f3Smrg#
187ec681f3Smrg# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
197ec681f3Smrg# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
207ec681f3Smrg# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
217ec681f3Smrg# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
227ec681f3Smrg# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
237ec681f3Smrg# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
247ec681f3Smrg# IN THE SOFTWARE.
257ec681f3Smrg
267ec681f3Smrgimport xml.parsers.expat
277ec681f3Smrgimport sys
287ec681f3Smrgimport operator
297ec681f3Smrgfrom functools import reduce
307ec681f3Smrg
317ec681f3Smrgglobal_prefix = "agx"
327ec681f3Smrg
337ec681f3Smrgpack_header = """
347ec681f3Smrg/* Generated code, see midgard.xml and gen_pack_header.py
357ec681f3Smrg *
367ec681f3Smrg * Packets, enums and structures for Panfrost.
377ec681f3Smrg *
387ec681f3Smrg * This file has been generated, do not hand edit.
397ec681f3Smrg */
407ec681f3Smrg
417ec681f3Smrg#ifndef AGX_PACK_H
427ec681f3Smrg#define AGX_PACK_H
437ec681f3Smrg
447ec681f3Smrg#include <stdio.h>
457ec681f3Smrg#include <stdint.h>
467ec681f3Smrg#include <stdbool.h>
477ec681f3Smrg#include <assert.h>
487ec681f3Smrg#include <math.h>
497ec681f3Smrg#include <inttypes.h>
507ec681f3Smrg#include "util/macros.h"
517ec681f3Smrg#include "util/u_math.h"
527ec681f3Smrg
537ec681f3Smrg#define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
547ec681f3Smrg
557ec681f3Smrgstatic inline uint64_t
567ec681f3Smrg__gen_uint(uint64_t v, uint32_t start, uint32_t end)
577ec681f3Smrg{
587ec681f3Smrg#ifndef NDEBUG
597ec681f3Smrg   const int width = end - start + 1;
607ec681f3Smrg   if (width < 64) {
617ec681f3Smrg      const uint64_t max = (1ull << width) - 1;
627ec681f3Smrg      assert(v <= max);
637ec681f3Smrg   }
647ec681f3Smrg#endif
657ec681f3Smrg
667ec681f3Smrg   return v << start;
677ec681f3Smrg}
687ec681f3Smrg
697ec681f3Smrgstatic inline uint32_t
707ec681f3Smrg__gen_sint(int32_t v, uint32_t start, uint32_t end)
717ec681f3Smrg{
727ec681f3Smrg#ifndef NDEBUG
737ec681f3Smrg   const int width = end - start + 1;
747ec681f3Smrg   if (width < 64) {
757ec681f3Smrg      const int64_t max = (1ll << (width - 1)) - 1;
767ec681f3Smrg      const int64_t min = -(1ll << (width - 1));
777ec681f3Smrg      assert(min <= v && v <= max);
787ec681f3Smrg   }
797ec681f3Smrg#endif
807ec681f3Smrg
817ec681f3Smrg   return (((uint32_t) v) << start) & ((2ll << end) - 1);
827ec681f3Smrg}
837ec681f3Smrg
847ec681f3Smrgstatic inline uint64_t
857ec681f3Smrg__gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
867ec681f3Smrg{
877ec681f3Smrg   uint64_t val = 0;
887ec681f3Smrg   const int width = end - start + 1;
897ec681f3Smrg   const uint64_t mask = (width == 64 ? ~0 : (1ull << width) - 1 );
907ec681f3Smrg
917ec681f3Smrg   for (unsigned byte = start / 8; byte <= end / 8; byte++) {
927ec681f3Smrg      val |= ((uint64_t) cl[byte]) << ((byte - start / 8) * 8);
937ec681f3Smrg   }
947ec681f3Smrg
957ec681f3Smrg   return (val >> (start % 8)) & mask;
967ec681f3Smrg}
977ec681f3Smrg
987ec681f3Smrgstatic inline uint64_t
997ec681f3Smrg__gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
1007ec681f3Smrg{
1017ec681f3Smrg   int size = end - start + 1;
1027ec681f3Smrg   int64_t val = __gen_unpack_uint(cl, start, end);
1037ec681f3Smrg
1047ec681f3Smrg   /* Get the sign bit extended. */
1057ec681f3Smrg   return (val << (64 - size)) >> (64 - size);
1067ec681f3Smrg}
1077ec681f3Smrg
1087ec681f3Smrg#define agx_prepare(dst, T)                                 \\
1097ec681f3Smrg   *(dst) = (struct AGX_ ## T){ AGX_ ## T ## _header }
1107ec681f3Smrg
1117ec681f3Smrg#define agx_pack(dst, T, name)                              \\
1127ec681f3Smrg   for (struct AGX_ ## T name = { AGX_ ## T ## _header }, \\
1137ec681f3Smrg        *_loop_terminate = (void *) (dst);                  \\
1147ec681f3Smrg        __builtin_expect(_loop_terminate != NULL, 1);       \\
1157ec681f3Smrg        ({ AGX_ ## T ## _pack((uint32_t *) (dst), &name);  \\
1167ec681f3Smrg           _loop_terminate = NULL; }))
1177ec681f3Smrg
1187ec681f3Smrg#define agx_unpack(fp, src, T, name)                        \\
1197ec681f3Smrg        struct AGX_ ## T name;                         \\
1207ec681f3Smrg        AGX_ ## T ## _unpack(fp, (uint8_t *)(src), &name)
1217ec681f3Smrg
1227ec681f3Smrg#define agx_print(fp, T, var, indent)                   \\
1237ec681f3Smrg        AGX_ ## T ## _print(fp, &(var), indent)
1247ec681f3Smrg
1257ec681f3Smrg#define agx_pixel_format_print(fp, format) do {\\
1267ec681f3Smrg   fprintf(fp, "%*sFormat: ", indent, ""); \\
1277ec681f3Smrg   \\
1287ec681f3Smrg   if (agx_channels_as_str((enum agx_channels)(format & 0x7F))) \\
1297ec681f3Smrg      fputs(agx_channels_as_str((enum agx_channels)(format & 0x7F)), fp); \\
1307ec681f3Smrg   else \\
1317ec681f3Smrg      fprintf(fp, "unknown channels %02X", format & 0x7F); \\
1327ec681f3Smrg   \\
1337ec681f3Smrg   fputs(" ", fp); \\
1347ec681f3Smrg   \\
1357ec681f3Smrg   if (agx_texture_type_as_str((enum agx_texture_type)(format >> 7))) \\
1367ec681f3Smrg      fputs(agx_texture_type_as_str((enum agx_texture_type)(format >> 7)), fp); \\
1377ec681f3Smrg   else \\
1387ec681f3Smrg      fprintf(fp, "unknown type %02X", format >> 7); \\
1397ec681f3Smrg   \\
1407ec681f3Smrg   fputs("\\n", fp); \\
1417ec681f3Smrg} while(0) \\
1427ec681f3Smrg
1437ec681f3Smrg"""
1447ec681f3Smrg
1457ec681f3Smrgdef to_alphanum(name):
1467ec681f3Smrg    substitutions = {
1477ec681f3Smrg        ' ': '_',
1487ec681f3Smrg        '/': '_',
1497ec681f3Smrg        '[': '',
1507ec681f3Smrg        ']': '',
1517ec681f3Smrg        '(': '',
1527ec681f3Smrg        ')': '',
1537ec681f3Smrg        '-': '_',
1547ec681f3Smrg        ':': '',
1557ec681f3Smrg        '.': '',
1567ec681f3Smrg        ',': '',
1577ec681f3Smrg        '=': '',
1587ec681f3Smrg        '>': '',
1597ec681f3Smrg        '#': '',
1607ec681f3Smrg        '&': '',
1617ec681f3Smrg        '*': '',
1627ec681f3Smrg        '"': '',
1637ec681f3Smrg        '+': '',
1647ec681f3Smrg        '\'': '',
1657ec681f3Smrg    }
1667ec681f3Smrg
1677ec681f3Smrg    for i, j in substitutions.items():
1687ec681f3Smrg        name = name.replace(i, j)
1697ec681f3Smrg
1707ec681f3Smrg    return name
1717ec681f3Smrg
1727ec681f3Smrgdef safe_name(name):
1737ec681f3Smrg    name = to_alphanum(name)
1747ec681f3Smrg    if not name[0].isalpha():
1757ec681f3Smrg        name = '_' + name
1767ec681f3Smrg
1777ec681f3Smrg    return name
1787ec681f3Smrg
1797ec681f3Smrgdef prefixed_upper_name(prefix, name):
1807ec681f3Smrg    if prefix:
1817ec681f3Smrg        name = prefix + "_" + name
1827ec681f3Smrg    return safe_name(name).upper()
1837ec681f3Smrg
1847ec681f3Smrgdef enum_name(name):
1857ec681f3Smrg    return "{}_{}".format(global_prefix, safe_name(name)).lower()
1867ec681f3Smrg
1877ec681f3Smrgdef num_from_str(num_str):
1887ec681f3Smrg    if num_str.lower().startswith('0x'):
1897ec681f3Smrg        return int(num_str, base=16)
1907ec681f3Smrg    else:
1917ec681f3Smrg        assert(not num_str.startswith('0') and 'octals numbers not allowed')
1927ec681f3Smrg        return int(num_str)
1937ec681f3Smrg
1947ec681f3SmrgMODIFIERS = ["shr", "minus", "align", "log2"]
1957ec681f3Smrg
1967ec681f3Smrgdef parse_modifier(modifier):
1977ec681f3Smrg    if modifier is None:
1987ec681f3Smrg        return None
1997ec681f3Smrg
2007ec681f3Smrg    for mod in MODIFIERS:
2017ec681f3Smrg        if modifier[0:len(mod)] == mod:
2027ec681f3Smrg            if mod == "log2":
2037ec681f3Smrg                assert(len(mod) == len(modifier))
2047ec681f3Smrg                return [mod]
2057ec681f3Smrg
2067ec681f3Smrg            if modifier[len(mod)] == '(' and modifier[-1] == ')':
2077ec681f3Smrg                ret = [mod, int(modifier[(len(mod) + 1):-1])]
2087ec681f3Smrg                if ret[0] == 'align':
2097ec681f3Smrg                    align = ret[1]
2107ec681f3Smrg                    # Make sure the alignment is a power of 2
2117ec681f3Smrg                    assert(align > 0 and not(align & (align - 1)));
2127ec681f3Smrg
2137ec681f3Smrg                return ret
2147ec681f3Smrg
2157ec681f3Smrg    print("Invalid modifier")
2167ec681f3Smrg    assert(False)
2177ec681f3Smrg
2187ec681f3Smrgclass Field(object):
2197ec681f3Smrg    def __init__(self, parser, attrs):
2207ec681f3Smrg        self.parser = parser
2217ec681f3Smrg        if "name" in attrs:
2227ec681f3Smrg            self.name = safe_name(attrs["name"]).lower()
2237ec681f3Smrg            self.human_name = attrs["name"]
2247ec681f3Smrg
2257ec681f3Smrg        if ":" in str(attrs["start"]):
2267ec681f3Smrg            (word, bit) = attrs["start"].split(":")
2277ec681f3Smrg            self.start = (int(word) * 32) + int(bit)
2287ec681f3Smrg        else:
2297ec681f3Smrg            self.start = int(attrs["start"])
2307ec681f3Smrg
2317ec681f3Smrg        self.end = self.start + int(attrs["size"]) - 1
2327ec681f3Smrg        self.type = attrs["type"]
2337ec681f3Smrg
2347ec681f3Smrg        if self.type == 'bool' and self.start != self.end:
2357ec681f3Smrg            print("#error Field {} has bool type but more than one bit of size".format(self.name));
2367ec681f3Smrg
2377ec681f3Smrg        if "prefix" in attrs:
2387ec681f3Smrg            self.prefix = safe_name(attrs["prefix"]).upper()
2397ec681f3Smrg        else:
2407ec681f3Smrg            self.prefix = None
2417ec681f3Smrg
2427ec681f3Smrg        if "exact" in attrs:
2437ec681f3Smrg            self.exact = int(attrs["exact"])
2447ec681f3Smrg        else:
2457ec681f3Smrg            self.exact = None
2467ec681f3Smrg
2477ec681f3Smrg        self.default = attrs.get("default")
2487ec681f3Smrg
2497ec681f3Smrg        # Map enum values
2507ec681f3Smrg        if self.type in self.parser.enums and self.default is not None:
2517ec681f3Smrg            self.default = safe_name('{}_{}_{}'.format(global_prefix, self.type, self.default)).upper()
2527ec681f3Smrg
2537ec681f3Smrg        self.modifier  = parse_modifier(attrs.get("modifier"))
2547ec681f3Smrg
2557ec681f3Smrg    def emit_template_struct(self, dim):
2567ec681f3Smrg        if self.type == 'address':
2577ec681f3Smrg            type = 'uint64_t'
2587ec681f3Smrg        elif self.type == 'bool':
2597ec681f3Smrg            type = 'bool'
2607ec681f3Smrg        elif self.type == 'float':
2617ec681f3Smrg            type = 'float'
2627ec681f3Smrg        elif self.type in ['uint', 'hex'] and self.end - self.start > 32:
2637ec681f3Smrg            type = 'uint64_t'
2647ec681f3Smrg        elif self.type == 'int':
2657ec681f3Smrg            type = 'int32_t'
2667ec681f3Smrg        elif self.type in ['uint', 'uint/float', 'Pixel Format', 'hex']:
2677ec681f3Smrg            type = 'uint32_t'
2687ec681f3Smrg        elif self.type in self.parser.structs:
2697ec681f3Smrg            type = 'struct ' + self.parser.gen_prefix(safe_name(self.type.upper()))
2707ec681f3Smrg        elif self.type in self.parser.enums:
2717ec681f3Smrg            type = 'enum ' + enum_name(self.type)
2727ec681f3Smrg        else:
2737ec681f3Smrg            print("#error unhandled type: %s" % self.type)
2747ec681f3Smrg            type = "uint32_t"
2757ec681f3Smrg
2767ec681f3Smrg        print("   %-36s %s%s;" % (type, self.name, dim))
2777ec681f3Smrg
2787ec681f3Smrg        for value in self.values:
2797ec681f3Smrg            name = prefixed_upper_name(self.prefix, value.name)
2807ec681f3Smrg            print("#define %-40s %d" % (name, value.value))
2817ec681f3Smrg
2827ec681f3Smrg    def overlaps(self, field):
2837ec681f3Smrg        return self != field and max(self.start, field.start) <= min(self.end, field.end)
2847ec681f3Smrg
2857ec681f3Smrgclass Group(object):
2867ec681f3Smrg    def __init__(self, parser, parent, start, count, label):
2877ec681f3Smrg        self.parser = parser
2887ec681f3Smrg        self.parent = parent
2897ec681f3Smrg        self.start = start
2907ec681f3Smrg        self.count = count
2917ec681f3Smrg        self.label = label
2927ec681f3Smrg        self.size = 0
2937ec681f3Smrg        self.length = 0
2947ec681f3Smrg        self.fields = []
2957ec681f3Smrg
2967ec681f3Smrg    def get_length(self):
2977ec681f3Smrg        # Determine number of bytes in this group.
2987ec681f3Smrg        calculated = max(field.end // 8 for field in self.fields) + 1 if len(self.fields) > 0 else 0
2997ec681f3Smrg        if self.length > 0:
3007ec681f3Smrg            assert(self.length >= calculated)
3017ec681f3Smrg        else:
3027ec681f3Smrg            self.length = calculated
3037ec681f3Smrg        return self.length
3047ec681f3Smrg
3057ec681f3Smrg
3067ec681f3Smrg    def emit_template_struct(self, dim):
3077ec681f3Smrg        if self.count == 0:
3087ec681f3Smrg            print("   /* variable length fields follow */")
3097ec681f3Smrg        else:
3107ec681f3Smrg            if self.count > 1:
3117ec681f3Smrg                dim = "%s[%d]" % (dim, self.count)
3127ec681f3Smrg
3137ec681f3Smrg            if len(self.fields) == 0:
3147ec681f3Smrg                print("   int dummy;")
3157ec681f3Smrg
3167ec681f3Smrg            for field in self.fields:
3177ec681f3Smrg                if field.exact is not None:
3187ec681f3Smrg                    continue
3197ec681f3Smrg
3207ec681f3Smrg                field.emit_template_struct(dim)
3217ec681f3Smrg
3227ec681f3Smrg    class Word:
3237ec681f3Smrg        def __init__(self):
3247ec681f3Smrg            self.size = 32
3257ec681f3Smrg            self.contributors = []
3267ec681f3Smrg
3277ec681f3Smrg    class FieldRef:
3287ec681f3Smrg        def __init__(self, field, path, start, end):
3297ec681f3Smrg            self.field = field
3307ec681f3Smrg            self.path = path
3317ec681f3Smrg            self.start = start
3327ec681f3Smrg            self.end = end
3337ec681f3Smrg
3347ec681f3Smrg    def collect_fields(self, fields, offset, path, all_fields):
3357ec681f3Smrg        for field in fields:
3367ec681f3Smrg            field_path = '{}{}'.format(path, field.name)
3377ec681f3Smrg            field_offset = offset + field.start
3387ec681f3Smrg
3397ec681f3Smrg            if field.type in self.parser.structs:
3407ec681f3Smrg                sub_struct = self.parser.structs[field.type]
3417ec681f3Smrg                self.collect_fields(sub_struct.fields, field_offset, field_path + '.', all_fields)
3427ec681f3Smrg                continue
3437ec681f3Smrg
3447ec681f3Smrg            start = field_offset
3457ec681f3Smrg            end = offset + field.end
3467ec681f3Smrg            all_fields.append(self.FieldRef(field, field_path, start, end))
3477ec681f3Smrg
3487ec681f3Smrg    def collect_words(self, fields, offset, path, words):
3497ec681f3Smrg        for field in fields:
3507ec681f3Smrg            field_path = '{}{}'.format(path, field.name)
3517ec681f3Smrg            start = offset + field.start
3527ec681f3Smrg
3537ec681f3Smrg            if field.type in self.parser.structs:
3547ec681f3Smrg                sub_fields = self.parser.structs[field.type].fields
3557ec681f3Smrg                self.collect_words(sub_fields, start, field_path + '.', words)
3567ec681f3Smrg                continue
3577ec681f3Smrg
3587ec681f3Smrg            end = offset + field.end
3597ec681f3Smrg            contributor = self.FieldRef(field, field_path, start, end)
3607ec681f3Smrg            first_word = contributor.start // 32
3617ec681f3Smrg            last_word = contributor.end // 32
3627ec681f3Smrg            for b in range(first_word, last_word + 1):
3637ec681f3Smrg                if not b in words:
3647ec681f3Smrg                    words[b] = self.Word()
3657ec681f3Smrg                words[b].contributors.append(contributor)
3667ec681f3Smrg
3677ec681f3Smrg    def emit_pack_function(self):
3687ec681f3Smrg        self.get_length()
3697ec681f3Smrg
3707ec681f3Smrg        words = {}
3717ec681f3Smrg        self.collect_words(self.fields, 0, '', words)
3727ec681f3Smrg
3737ec681f3Smrg        # Validate the modifier is lossless
3747ec681f3Smrg        for field in self.fields:
3757ec681f3Smrg            if field.modifier is None:
3767ec681f3Smrg                continue
3777ec681f3Smrg
3787ec681f3Smrg            assert(field.exact is None)
3797ec681f3Smrg
3807ec681f3Smrg            if field.modifier[0] == "shr":
3817ec681f3Smrg                shift = field.modifier[1]
3827ec681f3Smrg                mask = hex((1 << shift) - 1)
3837ec681f3Smrg                print("   assert((values->{} & {}) == 0);".format(field.name, mask))
3847ec681f3Smrg            elif field.modifier[0] == "minus":
3857ec681f3Smrg                print("   assert(values->{} >= {});".format(field.name, field.modifier[1]))
3867ec681f3Smrg            elif field.modifier[0] == "log2":
3877ec681f3Smrg                print("   assert(util_is_power_of_two_nonzero(values->{}));".format(field.name))
3887ec681f3Smrg
3897ec681f3Smrg        for index in range(self.length // 4):
3907ec681f3Smrg            # Handle MBZ words
3917ec681f3Smrg            if not index in words:
3927ec681f3Smrg                print("   cl[%2d] = 0;" % index)
3937ec681f3Smrg                continue
3947ec681f3Smrg
3957ec681f3Smrg            word = words[index]
3967ec681f3Smrg
3977ec681f3Smrg            word_start = index * 32
3987ec681f3Smrg
3997ec681f3Smrg            v = None
4007ec681f3Smrg            prefix = "   cl[%2d] =" % index
4017ec681f3Smrg
4027ec681f3Smrg            for contributor in word.contributors:
4037ec681f3Smrg                field = contributor.field
4047ec681f3Smrg                name = field.name
4057ec681f3Smrg                start = contributor.start
4067ec681f3Smrg                end = contributor.end
4077ec681f3Smrg                contrib_word_start = (start // 32) * 32
4087ec681f3Smrg                start -= contrib_word_start
4097ec681f3Smrg                end -= contrib_word_start
4107ec681f3Smrg
4117ec681f3Smrg                value = str(field.exact) if field.exact is not None else "values->{}".format(contributor.path)
4127ec681f3Smrg                if field.modifier is not None:
4137ec681f3Smrg                    if field.modifier[0] == "shr":
4147ec681f3Smrg                        value = "{} >> {}".format(value, field.modifier[1])
4157ec681f3Smrg                    elif field.modifier[0] == "minus":
4167ec681f3Smrg                        value = "{} - {}".format(value, field.modifier[1])
4177ec681f3Smrg                    elif field.modifier[0] == "align":
4187ec681f3Smrg                        value = "ALIGN_POT({}, {})".format(value, field.modifier[1])
4197ec681f3Smrg                    elif field.modifier[0] == "log2":
4207ec681f3Smrg                        value = "util_logbase2({})".format(value)
4217ec681f3Smrg
4227ec681f3Smrg                if field.type in ["uint", "hex", "Pixel Format", "address"]:
4237ec681f3Smrg                    s = "__gen_uint(%s, %d, %d)" % \
4247ec681f3Smrg                        (value, start, end)
4257ec681f3Smrg                elif field.type in self.parser.enums:
4267ec681f3Smrg                    s = "__gen_uint(%s, %d, %d)" % \
4277ec681f3Smrg                        (value, start, end)
4287ec681f3Smrg                elif field.type == "int":
4297ec681f3Smrg                    s = "__gen_sint(%s, %d, %d)" % \
4307ec681f3Smrg                        (value, start, end)
4317ec681f3Smrg                elif field.type == "bool":
4327ec681f3Smrg                    s = "__gen_uint(%s, %d, %d)" % \
4337ec681f3Smrg                        (value, start, end)
4347ec681f3Smrg                elif field.type == "float":
4357ec681f3Smrg                    assert(start == 0 and end == 31)
4367ec681f3Smrg                    s = "__gen_uint(fui({}), 0, 32)".format(value)
4377ec681f3Smrg                else:
4387ec681f3Smrg                    s = "#error unhandled field {}, type {}".format(contributor.path, field.type)
4397ec681f3Smrg
4407ec681f3Smrg                if not s == None:
4417ec681f3Smrg                    shift = word_start - contrib_word_start
4427ec681f3Smrg                    if shift:
4437ec681f3Smrg                        s = "%s >> %d" % (s, shift)
4447ec681f3Smrg
4457ec681f3Smrg                    if contributor == word.contributors[-1]:
4467ec681f3Smrg                        print("%s %s;" % (prefix, s))
4477ec681f3Smrg                    else:
4487ec681f3Smrg                        print("%s %s |" % (prefix, s))
4497ec681f3Smrg                    prefix = "           "
4507ec681f3Smrg
4517ec681f3Smrg            continue
4527ec681f3Smrg
4537ec681f3Smrg    # Given a field (start, end) contained in word `index`, generate the 32-bit
4547ec681f3Smrg    # mask of present bits relative to the word
4557ec681f3Smrg    def mask_for_word(self, index, start, end):
4567ec681f3Smrg        field_word_start = index * 32
4577ec681f3Smrg        start -= field_word_start
4587ec681f3Smrg        end -= field_word_start
4597ec681f3Smrg        # Cap multiword at one word
4607ec681f3Smrg        start = max(start, 0)
4617ec681f3Smrg        end = min(end, 32 - 1)
4627ec681f3Smrg        count = (end - start + 1)
4637ec681f3Smrg        return (((1 << count) - 1) << start)
4647ec681f3Smrg
4657ec681f3Smrg    def emit_unpack_function(self):
4667ec681f3Smrg        # First, verify there is no garbage in unused bits
4677ec681f3Smrg        words = {}
4687ec681f3Smrg        self.collect_words(self.fields, 0, '', words)
4697ec681f3Smrg
4707ec681f3Smrg        for index in range(self.length // 4):
4717ec681f3Smrg            base = index * 32
4727ec681f3Smrg            word = words.get(index, self.Word())
4737ec681f3Smrg            masks = [self.mask_for_word(index, c.start, c.end) for c in word.contributors]
4747ec681f3Smrg            mask = reduce(lambda x,y: x | y, masks, 0)
4757ec681f3Smrg
4767ec681f3Smrg            ALL_ONES = 0xffffffff
4777ec681f3Smrg
4787ec681f3Smrg            if mask != ALL_ONES:
4797ec681f3Smrg                TMPL = '   if (((const uint32_t *) cl)[{}] & {}) fprintf(fp, "XXX: Unknown field of {} unpacked at word {}: got %X, bad mask %X\\n", ((const uint32_t *) cl)[{}], ((const uint32_t *) cl)[{}] & {});'
4807ec681f3Smrg                print(TMPL.format(index, hex(mask ^ ALL_ONES), self.label, index, index, index, hex(mask ^ ALL_ONES)))
4817ec681f3Smrg
4827ec681f3Smrg        fieldrefs = []
4837ec681f3Smrg        self.collect_fields(self.fields, 0, '', fieldrefs)
4847ec681f3Smrg        for fieldref in fieldrefs:
4857ec681f3Smrg            field = fieldref.field
4867ec681f3Smrg            convert = None
4877ec681f3Smrg
4887ec681f3Smrg            args = []
4897ec681f3Smrg            args.append('cl')
4907ec681f3Smrg            args.append(str(fieldref.start))
4917ec681f3Smrg            args.append(str(fieldref.end))
4927ec681f3Smrg
4937ec681f3Smrg            if field.type in set(["uint", "uint/float", "address", "Pixel Format", "hex"]) | self.parser.enums:
4947ec681f3Smrg                convert = "__gen_unpack_uint"
4957ec681f3Smrg            elif field.type == "int":
4967ec681f3Smrg                convert = "__gen_unpack_sint"
4977ec681f3Smrg            elif field.type == "bool":
4987ec681f3Smrg                convert = "__gen_unpack_uint"
4997ec681f3Smrg            elif field.type == "float":
5007ec681f3Smrg                convert = "__gen_unpack_float"
5017ec681f3Smrg            else:
5027ec681f3Smrg                s = "/* unhandled field %s, type %s */\n" % (field.name, field.type)
5037ec681f3Smrg
5047ec681f3Smrg            suffix = ""
5057ec681f3Smrg            prefix = ""
5067ec681f3Smrg            if field.modifier:
5077ec681f3Smrg                if field.modifier[0] == "minus":
5087ec681f3Smrg                    suffix = " + {}".format(field.modifier[1])
5097ec681f3Smrg                elif field.modifier[0] == "shr":
5107ec681f3Smrg                    suffix = " << {}".format(field.modifier[1])
5117ec681f3Smrg                if field.modifier[0] == "log2":
5127ec681f3Smrg                    prefix = "1 << "
5137ec681f3Smrg
5147ec681f3Smrg            decoded = '{}{}({}){}'.format(prefix, convert, ', '.join(args), suffix)
5157ec681f3Smrg
5167ec681f3Smrg            print('   values->{} = {};'.format(fieldref.path, decoded))
5177ec681f3Smrg            if field.modifier and field.modifier[0] == "align":
5187ec681f3Smrg                mask = hex(field.modifier[1] - 1)
5197ec681f3Smrg                print('   assert(!(values->{} & {}));'.format(fieldref.path, mask))
5207ec681f3Smrg
5217ec681f3Smrg    def emit_print_function(self):
5227ec681f3Smrg        for field in self.fields:
5237ec681f3Smrg            convert = None
5247ec681f3Smrg            name, val = field.human_name, 'values->{}'.format(field.name)
5257ec681f3Smrg
5267ec681f3Smrg            if field.type in self.parser.structs:
5277ec681f3Smrg                pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
5287ec681f3Smrg                print('   fprintf(fp, "%*s{}:\\n", indent, "");'.format(field.human_name))
5297ec681f3Smrg                print("   {}_print(fp, &values->{}, indent + 2);".format(pack_name, field.name))
5307ec681f3Smrg            elif field.type == "address":
5317ec681f3Smrg                # TODO resolve to name
5327ec681f3Smrg                print('   fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
5337ec681f3Smrg            elif field.type in self.parser.enums:
5347ec681f3Smrg                print('   if ({}_as_str({}))'.format(enum_name(field.type), val))
5357ec681f3Smrg                print('     fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name, enum_name(field.type), val))
5367ec681f3Smrg                print('    else')
5377ec681f3Smrg                print('     fprintf(fp, "%*s{}: unknown %X (XXX)\\n", indent, "", {});'.format(name, val))
5387ec681f3Smrg            elif field.type == "int":
5397ec681f3Smrg                print('   fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name, val))
5407ec681f3Smrg            elif field.type == "bool":
5417ec681f3Smrg                print('   fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name, val))
5427ec681f3Smrg            elif field.type == "float":
5437ec681f3Smrg                print('   fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name, val))
5447ec681f3Smrg            elif field.type in ["uint", "hex"] and (field.end - field.start) >= 32:
5457ec681f3Smrg                print('   fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
5467ec681f3Smrg            elif field.type == "hex":
5477ec681f3Smrg                print('   fprintf(fp, "%*s{}: 0x%" PRIx32 "\\n", indent, "", {});'.format(name, val))
5487ec681f3Smrg            elif field.type in "Pixel Format":
5497ec681f3Smrg                print('   agx_pixel_format_print(fp, {});'.format(val))
5507ec681f3Smrg            elif field.type == "uint/float":
5517ec681f3Smrg                print('   fprintf(fp, "%*s{}: 0x%X (%f)\\n", indent, "", {}, uif({}));'.format(name, val, val))
5527ec681f3Smrg            else:
5537ec681f3Smrg                print('   fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name, val))
5547ec681f3Smrg
5557ec681f3Smrgclass Value(object):
5567ec681f3Smrg    def __init__(self, attrs):
5577ec681f3Smrg        self.name = attrs["name"]
5587ec681f3Smrg        self.value = int(attrs["value"], 0)
5597ec681f3Smrg
5607ec681f3Smrgclass Parser(object):
5617ec681f3Smrg    def __init__(self):
5627ec681f3Smrg        self.parser = xml.parsers.expat.ParserCreate()
5637ec681f3Smrg        self.parser.StartElementHandler = self.start_element
5647ec681f3Smrg        self.parser.EndElementHandler = self.end_element
5657ec681f3Smrg
5667ec681f3Smrg        self.struct = None
5677ec681f3Smrg        self.structs = {}
5687ec681f3Smrg        # Set of enum names we've seen.
5697ec681f3Smrg        self.enums = set()
5707ec681f3Smrg
5717ec681f3Smrg    def gen_prefix(self, name):
5727ec681f3Smrg        return '{}_{}'.format(global_prefix.upper(), name)
5737ec681f3Smrg
5747ec681f3Smrg    def start_element(self, name, attrs):
5757ec681f3Smrg        if name == "agxml":
5767ec681f3Smrg            print(pack_header)
5777ec681f3Smrg        elif name == "struct":
5787ec681f3Smrg            name = attrs["name"]
5797ec681f3Smrg            self.no_direct_packing = attrs.get("no-direct-packing", False)
5807ec681f3Smrg            object_name = self.gen_prefix(safe_name(name.upper()))
5817ec681f3Smrg            self.struct = object_name
5827ec681f3Smrg
5837ec681f3Smrg            self.group = Group(self, None, 0, 1, name)
5847ec681f3Smrg            if "size" in attrs:
5857ec681f3Smrg                self.group.length = int(attrs["size"])
5867ec681f3Smrg            self.group.align = int(attrs["align"]) if "align" in attrs else None
5877ec681f3Smrg            self.structs[attrs["name"]] = self.group
5887ec681f3Smrg        elif name == "field":
5897ec681f3Smrg            self.group.fields.append(Field(self, attrs))
5907ec681f3Smrg            self.values = []
5917ec681f3Smrg        elif name == "enum":
5927ec681f3Smrg            self.values = []
5937ec681f3Smrg            self.enum = safe_name(attrs["name"])
5947ec681f3Smrg            self.enums.add(attrs["name"])
5957ec681f3Smrg            if "prefix" in attrs:
5967ec681f3Smrg                self.prefix = attrs["prefix"]
5977ec681f3Smrg            else:
5987ec681f3Smrg                self.prefix= None
5997ec681f3Smrg        elif name == "value":
6007ec681f3Smrg            self.values.append(Value(attrs))
6017ec681f3Smrg
6027ec681f3Smrg    def end_element(self, name):
6037ec681f3Smrg        if name == "struct":
6047ec681f3Smrg            self.emit_struct()
6057ec681f3Smrg            self.struct = None
6067ec681f3Smrg            self.group = None
6077ec681f3Smrg        elif name  == "field":
6087ec681f3Smrg            self.group.fields[-1].values = self.values
6097ec681f3Smrg        elif name  == "enum":
6107ec681f3Smrg            self.emit_enum()
6117ec681f3Smrg            self.enum = None
6127ec681f3Smrg        elif name == "agxml":
6137ec681f3Smrg            print('#endif')
6147ec681f3Smrg
6157ec681f3Smrg    def emit_header(self, name):
6167ec681f3Smrg        default_fields = []
6177ec681f3Smrg        for field in self.group.fields:
6187ec681f3Smrg            if not type(field) is Field:
6197ec681f3Smrg                continue
6207ec681f3Smrg            if field.default is not None:
6217ec681f3Smrg                default_fields.append("   .{} = {}".format(field.name, field.default))
6227ec681f3Smrg            elif field.type in self.structs:
6237ec681f3Smrg                default_fields.append("   .{} = {{ {}_header }}".format(field.name, self.gen_prefix(safe_name(field.type.upper()))))
6247ec681f3Smrg
6257ec681f3Smrg        print('#define %-40s\\' % (name + '_header'))
6267ec681f3Smrg        if default_fields:
6277ec681f3Smrg            print(",  \\\n".join(default_fields))
6287ec681f3Smrg        else:
6297ec681f3Smrg            print('   0')
6307ec681f3Smrg        print('')
6317ec681f3Smrg
6327ec681f3Smrg    def emit_template_struct(self, name, group):
6337ec681f3Smrg        print("struct %s {" % name)
6347ec681f3Smrg        group.emit_template_struct("")
6357ec681f3Smrg        print("};\n")
6367ec681f3Smrg
6377ec681f3Smrg    def emit_pack_function(self, name, group):
6387ec681f3Smrg        print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
6397ec681f3Smrg              (name, ' ' * (len(name) + 6), name))
6407ec681f3Smrg
6417ec681f3Smrg        group.emit_pack_function()
6427ec681f3Smrg
6437ec681f3Smrg        print("}\n\n")
6447ec681f3Smrg
6457ec681f3Smrg        print('#define {} {}'.format (name + "_LENGTH", self.group.length))
6467ec681f3Smrg        if self.group.align != None:
6477ec681f3Smrg            print('#define {} {}'.format (name + "_ALIGN", self.group.align))
6487ec681f3Smrg        print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name.lower(), self.group.length // 4))
6497ec681f3Smrg
6507ec681f3Smrg    def emit_unpack_function(self, name, group):
6517ec681f3Smrg        print("static inline void")
6527ec681f3Smrg        print("%s_unpack(FILE *fp, const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
6537ec681f3Smrg              (name.upper(), ' ' * (len(name) + 8), name))
6547ec681f3Smrg
6557ec681f3Smrg        group.emit_unpack_function()
6567ec681f3Smrg
6577ec681f3Smrg        print("}\n")
6587ec681f3Smrg
6597ec681f3Smrg    def emit_print_function(self, name, group):
6607ec681f3Smrg        print("static inline void")
6617ec681f3Smrg        print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name.upper(), name))
6627ec681f3Smrg
6637ec681f3Smrg        group.emit_print_function()
6647ec681f3Smrg
6657ec681f3Smrg        print("}\n")
6667ec681f3Smrg
6677ec681f3Smrg    def emit_struct(self):
6687ec681f3Smrg        name = self.struct
6697ec681f3Smrg
6707ec681f3Smrg        self.emit_template_struct(self.struct, self.group)
6717ec681f3Smrg        self.emit_header(name)
6727ec681f3Smrg        if self.no_direct_packing == False:
6737ec681f3Smrg            self.emit_pack_function(self.struct, self.group)
6747ec681f3Smrg            self.emit_unpack_function(self.struct, self.group)
6757ec681f3Smrg        self.emit_print_function(self.struct, self.group)
6767ec681f3Smrg
6777ec681f3Smrg    def enum_prefix(self, name):
6787ec681f3Smrg        return
6797ec681f3Smrg
6807ec681f3Smrg    def emit_enum(self):
6817ec681f3Smrg        e_name = enum_name(self.enum)
6827ec681f3Smrg        prefix = e_name if self.enum != 'Format' else global_prefix
6837ec681f3Smrg        print('enum {} {{'.format(e_name))
6847ec681f3Smrg
6857ec681f3Smrg        for value in self.values:
6867ec681f3Smrg            name = '{}_{}'.format(prefix, value.name)
6877ec681f3Smrg            name = safe_name(name).upper()
6887ec681f3Smrg            print('        % -36s = %6d,' % (name, value.value))
6897ec681f3Smrg        print('};\n')
6907ec681f3Smrg
6917ec681f3Smrg        print("static inline const char *")
6927ec681f3Smrg        print("{}_as_str(enum {} imm)\n{{".format(e_name.lower(), e_name))
6937ec681f3Smrg        print("    switch (imm) {")
6947ec681f3Smrg        for value in self.values:
6957ec681f3Smrg            name = '{}_{}'.format(prefix, value.name)
6967ec681f3Smrg            name = safe_name(name).upper()
6977ec681f3Smrg            print('    case {}: return "{}";'.format(name, value.name))
6987ec681f3Smrg        print('    default: break;')
6997ec681f3Smrg        print("    }")
7007ec681f3Smrg        print("    return NULL;")
7017ec681f3Smrg        print("}\n")
7027ec681f3Smrg
7037ec681f3Smrg    def parse(self, filename):
7047ec681f3Smrg        file = open(filename, "rb")
7057ec681f3Smrg        self.parser.ParseFile(file)
7067ec681f3Smrg        file.close()
7077ec681f3Smrg
7087ec681f3Smrgif len(sys.argv) < 2:
7097ec681f3Smrg    print("No input xml file specified")
7107ec681f3Smrg    sys.exit(1)
7117ec681f3Smrg
7127ec681f3Smrginput_file = sys.argv[1]
7137ec681f3Smrg
7147ec681f3Smrgp = Parser()
7157ec681f3Smrgp.parse(input_file)
716