1bf215546Sopenharmony_ci#encoding=utf-8
2bf215546Sopenharmony_ci
3bf215546Sopenharmony_ci# Copyright (C) 2016 Intel Corporation
4bf215546Sopenharmony_ci# Copyright (C) 2016 Broadcom
5bf215546Sopenharmony_ci# Copyright (C) 2020 Collabora, Ltd.
6bf215546Sopenharmony_ci#
7bf215546Sopenharmony_ci# Permission is hereby granted, free of charge, to any person obtaining a
8bf215546Sopenharmony_ci# copy of this software and associated documentation files (the "Software"),
9bf215546Sopenharmony_ci# to deal in the Software without restriction, including without limitation
10bf215546Sopenharmony_ci# the rights to use, copy, modify, merge, publish, distribute, sublicense,
11bf215546Sopenharmony_ci# and/or sell copies of the Software, and to permit persons to whom the
12bf215546Sopenharmony_ci# Software is furnished to do so, subject to the following conditions:
13bf215546Sopenharmony_ci#
14bf215546Sopenharmony_ci# The above copyright notice and this permission notice (including the next
15bf215546Sopenharmony_ci# paragraph) shall be included in all copies or substantial portions of the
16bf215546Sopenharmony_ci# Software.
17bf215546Sopenharmony_ci#
18bf215546Sopenharmony_ci# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19bf215546Sopenharmony_ci# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20bf215546Sopenharmony_ci# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21bf215546Sopenharmony_ci# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22bf215546Sopenharmony_ci# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23bf215546Sopenharmony_ci# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24bf215546Sopenharmony_ci# IN THE SOFTWARE.
25bf215546Sopenharmony_ci
26bf215546Sopenharmony_ciimport xml.parsers.expat
27bf215546Sopenharmony_ciimport sys
28bf215546Sopenharmony_ciimport operator
29bf215546Sopenharmony_cifrom functools import reduce
30bf215546Sopenharmony_ci
31bf215546Sopenharmony_ciglobal_prefix = "mali"
32bf215546Sopenharmony_ci
33bf215546Sopenharmony_cipack_header = """
34bf215546Sopenharmony_ci/* Generated code, see midgard.xml and gen_pack_header.py
35bf215546Sopenharmony_ci *
36bf215546Sopenharmony_ci * Packets, enums and structures for Panfrost.
37bf215546Sopenharmony_ci *
38bf215546Sopenharmony_ci * This file has been generated, do not hand edit.
39bf215546Sopenharmony_ci */
40bf215546Sopenharmony_ci
41bf215546Sopenharmony_ci#ifndef PAN_PACK_H
42bf215546Sopenharmony_ci#define PAN_PACK_H
43bf215546Sopenharmony_ci
44bf215546Sopenharmony_ci#include <stdio.h>
45bf215546Sopenharmony_ci#include <stdint.h>
46bf215546Sopenharmony_ci#include <stdbool.h>
47bf215546Sopenharmony_ci#include <assert.h>
48bf215546Sopenharmony_ci#include <math.h>
49bf215546Sopenharmony_ci#include <inttypes.h>
50bf215546Sopenharmony_ci#include "util/macros.h"
51bf215546Sopenharmony_ci#include "util/u_math.h"
52bf215546Sopenharmony_ci
53bf215546Sopenharmony_ci#define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
54bf215546Sopenharmony_ci
55bf215546Sopenharmony_cistatic inline uint64_t
56bf215546Sopenharmony_ci__gen_uint(uint64_t v, uint32_t start, uint32_t end)
57bf215546Sopenharmony_ci{
58bf215546Sopenharmony_ci#ifndef NDEBUG
59bf215546Sopenharmony_ci   const int width = end - start + 1;
60bf215546Sopenharmony_ci   if (width < 64) {
61bf215546Sopenharmony_ci      const uint64_t max = (1ull << width) - 1;
62bf215546Sopenharmony_ci      assert(v <= max);
63bf215546Sopenharmony_ci   }
64bf215546Sopenharmony_ci#endif
65bf215546Sopenharmony_ci
66bf215546Sopenharmony_ci   return v << start;
67bf215546Sopenharmony_ci}
68bf215546Sopenharmony_ci
69bf215546Sopenharmony_cistatic inline uint32_t
70bf215546Sopenharmony_ci__gen_sint(int32_t v, uint32_t start, uint32_t end)
71bf215546Sopenharmony_ci{
72bf215546Sopenharmony_ci#ifndef NDEBUG
73bf215546Sopenharmony_ci   const int width = end - start + 1;
74bf215546Sopenharmony_ci   if (width < 64) {
75bf215546Sopenharmony_ci      const int64_t max = (1ll << (width - 1)) - 1;
76bf215546Sopenharmony_ci      const int64_t min = -(1ll << (width - 1));
77bf215546Sopenharmony_ci      assert(min <= v && v <= max);
78bf215546Sopenharmony_ci   }
79bf215546Sopenharmony_ci#endif
80bf215546Sopenharmony_ci
81bf215546Sopenharmony_ci   return (((uint32_t) v) << start) & ((2ll << end) - 1);
82bf215546Sopenharmony_ci}
83bf215546Sopenharmony_ci
84bf215546Sopenharmony_cistatic inline uint32_t
85bf215546Sopenharmony_ci__gen_padded(uint32_t v, uint32_t start, uint32_t end)
86bf215546Sopenharmony_ci{
87bf215546Sopenharmony_ci    unsigned shift = __builtin_ctz(v);
88bf215546Sopenharmony_ci    unsigned odd = v >> (shift + 1);
89bf215546Sopenharmony_ci
90bf215546Sopenharmony_ci#ifndef NDEBUG
91bf215546Sopenharmony_ci    assert((v >> shift) & 1);
92bf215546Sopenharmony_ci    assert(shift <= 31);
93bf215546Sopenharmony_ci    assert(odd <= 7);
94bf215546Sopenharmony_ci    assert((end - start + 1) == 8);
95bf215546Sopenharmony_ci#endif
96bf215546Sopenharmony_ci
97bf215546Sopenharmony_ci    return __gen_uint(shift | (odd << 5), start, end);
98bf215546Sopenharmony_ci}
99bf215546Sopenharmony_ci
100bf215546Sopenharmony_ci
101bf215546Sopenharmony_cistatic inline uint64_t
102bf215546Sopenharmony_ci__gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
103bf215546Sopenharmony_ci{
104bf215546Sopenharmony_ci   uint64_t val = 0;
105bf215546Sopenharmony_ci   const int width = end - start + 1;
106bf215546Sopenharmony_ci   const uint64_t mask = (width == 64 ? ~0 : (1ull << width) - 1 );
107bf215546Sopenharmony_ci
108bf215546Sopenharmony_ci   for (uint32_t byte = start / 8; byte <= end / 8; byte++) {
109bf215546Sopenharmony_ci      val |= ((uint64_t) cl[byte]) << ((byte - start / 8) * 8);
110bf215546Sopenharmony_ci   }
111bf215546Sopenharmony_ci
112bf215546Sopenharmony_ci   return (val >> (start % 8)) & mask;
113bf215546Sopenharmony_ci}
114bf215546Sopenharmony_ci
115bf215546Sopenharmony_cistatic inline uint64_t
116bf215546Sopenharmony_ci__gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
117bf215546Sopenharmony_ci{
118bf215546Sopenharmony_ci   int size = end - start + 1;
119bf215546Sopenharmony_ci   int64_t val = __gen_unpack_uint(cl, start, end);
120bf215546Sopenharmony_ci
121bf215546Sopenharmony_ci   return util_sign_extend(val, size);
122bf215546Sopenharmony_ci}
123bf215546Sopenharmony_ci
124bf215546Sopenharmony_cistatic inline uint64_t
125bf215546Sopenharmony_ci__gen_unpack_padded(const uint8_t *restrict cl, uint32_t start, uint32_t end)
126bf215546Sopenharmony_ci{
127bf215546Sopenharmony_ci   unsigned val = __gen_unpack_uint(cl, start, end);
128bf215546Sopenharmony_ci   unsigned shift = val & 0b11111;
129bf215546Sopenharmony_ci   unsigned odd = val >> 5;
130bf215546Sopenharmony_ci
131bf215546Sopenharmony_ci   return (2*odd + 1) << shift;
132bf215546Sopenharmony_ci}
133bf215546Sopenharmony_ci
134bf215546Sopenharmony_ci#define PREFIX1(A) MALI_ ## A
135bf215546Sopenharmony_ci#define PREFIX2(A, B) MALI_ ## A ## _ ## B
136bf215546Sopenharmony_ci#define PREFIX4(A, B, C, D) MALI_ ## A ## _ ## B ## _ ## C ## _ ## D
137bf215546Sopenharmony_ci
138bf215546Sopenharmony_ci#define pan_prepare(dst, T)                                 \\
139bf215546Sopenharmony_ci   *(dst) = (struct PREFIX1(T)){ PREFIX2(T, header) }
140bf215546Sopenharmony_ci
141bf215546Sopenharmony_ci#define pan_pack(dst, T, name)                              \\
142bf215546Sopenharmony_ci   for (struct PREFIX1(T) name = { PREFIX2(T, header) }, \\
143bf215546Sopenharmony_ci        *_loop_terminate = (void *) (dst);                  \\
144bf215546Sopenharmony_ci        __builtin_expect(_loop_terminate != NULL, 1);       \\
145bf215546Sopenharmony_ci        ({ PREFIX2(T, pack)((uint32_t *) (dst), &name);  \\
146bf215546Sopenharmony_ci           _loop_terminate = NULL; }))
147bf215546Sopenharmony_ci
148bf215546Sopenharmony_ci#define pan_unpack(src, T, name)                        \\
149bf215546Sopenharmony_ci        struct PREFIX1(T) name;                         \\
150bf215546Sopenharmony_ci        PREFIX2(T, unpack)((uint8_t *)(src), &name)
151bf215546Sopenharmony_ci
152bf215546Sopenharmony_ci#define pan_print(fp, T, var, indent)                   \\
153bf215546Sopenharmony_ci        PREFIX2(T, print)(fp, &(var), indent)
154bf215546Sopenharmony_ci
155bf215546Sopenharmony_ci#define pan_size(T) PREFIX2(T, LENGTH)
156bf215546Sopenharmony_ci#define pan_alignment(T) PREFIX2(T, ALIGN)
157bf215546Sopenharmony_ci
158bf215546Sopenharmony_ci#define pan_section_offset(A, S) \\
159bf215546Sopenharmony_ci        PREFIX4(A, SECTION, S, OFFSET)
160bf215546Sopenharmony_ci
161bf215546Sopenharmony_ci#define pan_section_ptr(base, A, S) \\
162bf215546Sopenharmony_ci        ((void *)((uint8_t *)(base) + pan_section_offset(A, S)))
163bf215546Sopenharmony_ci
164bf215546Sopenharmony_ci#define pan_section_pack(dst, A, S, name)                                                         \\
165bf215546Sopenharmony_ci   for (PREFIX4(A, SECTION, S, TYPE) name = { PREFIX4(A, SECTION, S, header) }, \\
166bf215546Sopenharmony_ci        *_loop_terminate = (void *) (dst);                                                        \\
167bf215546Sopenharmony_ci        __builtin_expect(_loop_terminate != NULL, 1);                                             \\
168bf215546Sopenharmony_ci        ({ PREFIX4(A, SECTION, S, pack) (pan_section_ptr(dst, A, S), &name);              \\
169bf215546Sopenharmony_ci           _loop_terminate = NULL; }))
170bf215546Sopenharmony_ci
171bf215546Sopenharmony_ci#define pan_section_unpack(src, A, S, name)                               \\
172bf215546Sopenharmony_ci        PREFIX4(A, SECTION, S, TYPE) name;                             \\
173bf215546Sopenharmony_ci        PREFIX4(A, SECTION, S, unpack)(pan_section_ptr(src, A, S), &name)
174bf215546Sopenharmony_ci
175bf215546Sopenharmony_ci#define pan_section_print(fp, A, S, var, indent)                          \\
176bf215546Sopenharmony_ci        PREFIX4(A, SECTION, S, print)(fp, &(var), indent)
177bf215546Sopenharmony_ci
178bf215546Sopenharmony_cistatic inline void pan_merge_helper(uint32_t *dst, const uint32_t *src, size_t bytes)
179bf215546Sopenharmony_ci{
180bf215546Sopenharmony_ci        assert((bytes & 3) == 0);
181bf215546Sopenharmony_ci
182bf215546Sopenharmony_ci        for (unsigned i = 0; i < (bytes / 4); ++i)
183bf215546Sopenharmony_ci                dst[i] |= src[i];
184bf215546Sopenharmony_ci}
185bf215546Sopenharmony_ci
186bf215546Sopenharmony_ci#define pan_merge(packed1, packed2, type) \
187bf215546Sopenharmony_ci        pan_merge_helper((packed1).opaque, (packed2).opaque, pan_size(type))
188bf215546Sopenharmony_ci
189bf215546Sopenharmony_ci/* From presentations, 16x16 tiles externally. Use shift for fast computation
190bf215546Sopenharmony_ci * of tile numbers. */
191bf215546Sopenharmony_ci
192bf215546Sopenharmony_ci#define MALI_TILE_SHIFT 4
193bf215546Sopenharmony_ci#define MALI_TILE_LENGTH (1 << MALI_TILE_SHIFT)
194bf215546Sopenharmony_ci
195bf215546Sopenharmony_ci"""
196bf215546Sopenharmony_ci
197bf215546Sopenharmony_civ6_format_printer = """
198bf215546Sopenharmony_ci
199bf215546Sopenharmony_ci#define mali_pixel_format_print(fp, format) \\
200bf215546Sopenharmony_ci    fprintf(fp, "%*sFormat (v6): %s%s%s %s%s%s%s\\n", indent, "", \\
201bf215546Sopenharmony_ci        mali_format_as_str((enum mali_format)((format >> 12) & 0xFF)), \\
202bf215546Sopenharmony_ci        (format & (1 << 20)) ? " sRGB" : "", \\
203bf215546Sopenharmony_ci        (format & (1 << 21)) ? " big-endian" : "", \\
204bf215546Sopenharmony_ci        mali_channel_as_str((enum mali_channel)((format >> 0) & 0x7)), \\
205bf215546Sopenharmony_ci        mali_channel_as_str((enum mali_channel)((format >> 3) & 0x7)), \\
206bf215546Sopenharmony_ci        mali_channel_as_str((enum mali_channel)((format >> 6) & 0x7)), \\
207bf215546Sopenharmony_ci        mali_channel_as_str((enum mali_channel)((format >> 9) & 0x7)));
208bf215546Sopenharmony_ci
209bf215546Sopenharmony_ci"""
210bf215546Sopenharmony_ci
211bf215546Sopenharmony_civ7_format_printer = """
212bf215546Sopenharmony_ci
213bf215546Sopenharmony_ci#define mali_pixel_format_print(fp, format) \\
214bf215546Sopenharmony_ci    fprintf(fp, "%*sFormat (v7): %s%s %s%s\\n", indent, "", \\
215bf215546Sopenharmony_ci        mali_format_as_str((enum mali_format)((format >> 12) & 0xFF)), \\
216bf215546Sopenharmony_ci        (format & (1 << 20)) ? " sRGB" : "", \\
217bf215546Sopenharmony_ci        mali_rgb_component_order_as_str((enum mali_rgb_component_order)(format & ((1 << 12) - 1))), \\
218bf215546Sopenharmony_ci        (format & (1 << 21)) ? " XXX BAD BIT" : "");
219bf215546Sopenharmony_ci
220bf215546Sopenharmony_ci"""
221bf215546Sopenharmony_ci
222bf215546Sopenharmony_cidef to_alphanum(name):
223bf215546Sopenharmony_ci    substitutions = {
224bf215546Sopenharmony_ci        ' ': '_',
225bf215546Sopenharmony_ci        '/': '_',
226bf215546Sopenharmony_ci        '[': '',
227bf215546Sopenharmony_ci        ']': '',
228bf215546Sopenharmony_ci        '(': '',
229bf215546Sopenharmony_ci        ')': '',
230bf215546Sopenharmony_ci        '-': '_',
231bf215546Sopenharmony_ci        ':': '',
232bf215546Sopenharmony_ci        '.': '',
233bf215546Sopenharmony_ci        ',': '',
234bf215546Sopenharmony_ci        '=': '',
235bf215546Sopenharmony_ci        '>': '',
236bf215546Sopenharmony_ci        '#': '',
237bf215546Sopenharmony_ci        '&': '',
238bf215546Sopenharmony_ci        '%': '',
239bf215546Sopenharmony_ci        '*': '',
240bf215546Sopenharmony_ci        '"': '',
241bf215546Sopenharmony_ci        '+': '',
242bf215546Sopenharmony_ci        '\'': '',
243bf215546Sopenharmony_ci    }
244bf215546Sopenharmony_ci
245bf215546Sopenharmony_ci    for i, j in substitutions.items():
246bf215546Sopenharmony_ci        name = name.replace(i, j)
247bf215546Sopenharmony_ci
248bf215546Sopenharmony_ci    return name
249bf215546Sopenharmony_ci
250bf215546Sopenharmony_cidef safe_name(name):
251bf215546Sopenharmony_ci    name = to_alphanum(name)
252bf215546Sopenharmony_ci    if not name[0].isalpha():
253bf215546Sopenharmony_ci        name = '_' + name
254bf215546Sopenharmony_ci
255bf215546Sopenharmony_ci    return name
256bf215546Sopenharmony_ci
257bf215546Sopenharmony_cidef prefixed_upper_name(prefix, name):
258bf215546Sopenharmony_ci    if prefix:
259bf215546Sopenharmony_ci        name = prefix + "_" + name
260bf215546Sopenharmony_ci    return safe_name(name).upper()
261bf215546Sopenharmony_ci
262bf215546Sopenharmony_cidef enum_name(name):
263bf215546Sopenharmony_ci    return "{}_{}".format(global_prefix, safe_name(name)).lower()
264bf215546Sopenharmony_ci
265bf215546Sopenharmony_cidef num_from_str(num_str):
266bf215546Sopenharmony_ci    if num_str.lower().startswith('0x'):
267bf215546Sopenharmony_ci        return int(num_str, base=16)
268bf215546Sopenharmony_ci    else:
269bf215546Sopenharmony_ci        assert(not num_str.startswith('0') and 'octals numbers not allowed')
270bf215546Sopenharmony_ci        return int(num_str)
271bf215546Sopenharmony_ci
272bf215546Sopenharmony_ciMODIFIERS = ["shr", "minus", "align", "log2"]
273bf215546Sopenharmony_ci
274bf215546Sopenharmony_cidef parse_modifier(modifier):
275bf215546Sopenharmony_ci    if modifier is None:
276bf215546Sopenharmony_ci        return None
277bf215546Sopenharmony_ci
278bf215546Sopenharmony_ci    for mod in MODIFIERS:
279bf215546Sopenharmony_ci        if modifier[0:len(mod)] == mod:
280bf215546Sopenharmony_ci            if mod == "log2":
281bf215546Sopenharmony_ci                assert(len(mod) == len(modifier))
282bf215546Sopenharmony_ci                return [mod]
283bf215546Sopenharmony_ci
284bf215546Sopenharmony_ci            if modifier[len(mod)] == '(' and modifier[-1] == ')':
285bf215546Sopenharmony_ci                ret = [mod, int(modifier[(len(mod) + 1):-1])]
286bf215546Sopenharmony_ci                if ret[0] == 'align':
287bf215546Sopenharmony_ci                    align = ret[1]
288bf215546Sopenharmony_ci                    # Make sure the alignment is a power of 2
289bf215546Sopenharmony_ci                    assert(align > 0 and not(align & (align - 1)));
290bf215546Sopenharmony_ci
291bf215546Sopenharmony_ci                return ret
292bf215546Sopenharmony_ci
293bf215546Sopenharmony_ci    print("Invalid modifier")
294bf215546Sopenharmony_ci    assert(False)
295bf215546Sopenharmony_ci
296bf215546Sopenharmony_ciclass Aggregate(object):
297bf215546Sopenharmony_ci    def __init__(self, parser, name, attrs):
298bf215546Sopenharmony_ci        self.parser = parser
299bf215546Sopenharmony_ci        self.sections = []
300bf215546Sopenharmony_ci        self.name = name
301bf215546Sopenharmony_ci        self.explicit_size = int(attrs["size"]) if "size" in attrs else 0
302bf215546Sopenharmony_ci        self.size = 0
303bf215546Sopenharmony_ci        self.align = int(attrs["align"]) if "align" in attrs else None
304bf215546Sopenharmony_ci
305bf215546Sopenharmony_ci    class Section:
306bf215546Sopenharmony_ci        def __init__(self, name):
307bf215546Sopenharmony_ci            self.name = name
308bf215546Sopenharmony_ci
309bf215546Sopenharmony_ci    def get_size(self):
310bf215546Sopenharmony_ci        if self.size > 0:
311bf215546Sopenharmony_ci            return self.size
312bf215546Sopenharmony_ci
313bf215546Sopenharmony_ci        size = 0
314bf215546Sopenharmony_ci        for section in self.sections:
315bf215546Sopenharmony_ci            size = max(size, section.offset + section.type.get_length())
316bf215546Sopenharmony_ci
317bf215546Sopenharmony_ci        if self.explicit_size > 0:
318bf215546Sopenharmony_ci            assert(self.explicit_size >= size)
319bf215546Sopenharmony_ci            self.size = self.explicit_size
320bf215546Sopenharmony_ci        else:
321bf215546Sopenharmony_ci            self.size = size
322bf215546Sopenharmony_ci        return self.size
323bf215546Sopenharmony_ci
324bf215546Sopenharmony_ci    def add_section(self, type_name, attrs):
325bf215546Sopenharmony_ci        assert("name" in attrs)
326bf215546Sopenharmony_ci        section = self.Section(safe_name(attrs["name"]).lower())
327bf215546Sopenharmony_ci        section.human_name = attrs["name"]
328bf215546Sopenharmony_ci        section.offset = int(attrs["offset"])
329bf215546Sopenharmony_ci        assert(section.offset % 4 == 0)
330bf215546Sopenharmony_ci        section.type = self.parser.structs[attrs["type"]]
331bf215546Sopenharmony_ci        section.type_name = type_name
332bf215546Sopenharmony_ci        self.sections.append(section)
333bf215546Sopenharmony_ci
334bf215546Sopenharmony_ciclass Field(object):
335bf215546Sopenharmony_ci    def __init__(self, parser, attrs):
336bf215546Sopenharmony_ci        self.parser = parser
337bf215546Sopenharmony_ci        if "name" in attrs:
338bf215546Sopenharmony_ci            self.name = safe_name(attrs["name"]).lower()
339bf215546Sopenharmony_ci            self.human_name = attrs["name"]
340bf215546Sopenharmony_ci
341bf215546Sopenharmony_ci        if ":" in str(attrs["start"]):
342bf215546Sopenharmony_ci            (word, bit) = attrs["start"].split(":")
343bf215546Sopenharmony_ci            self.start = (int(word) * 32) + int(bit)
344bf215546Sopenharmony_ci        else:
345bf215546Sopenharmony_ci            self.start = int(attrs["start"])
346bf215546Sopenharmony_ci
347bf215546Sopenharmony_ci        self.end = self.start + int(attrs["size"]) - 1
348bf215546Sopenharmony_ci        self.type = attrs["type"]
349bf215546Sopenharmony_ci
350bf215546Sopenharmony_ci        if self.type == 'bool' and self.start != self.end:
351bf215546Sopenharmony_ci            print("#error Field {} has bool type but more than one bit of size".format(self.name));
352bf215546Sopenharmony_ci
353bf215546Sopenharmony_ci        if "prefix" in attrs:
354bf215546Sopenharmony_ci            self.prefix = safe_name(attrs["prefix"]).upper()
355bf215546Sopenharmony_ci        else:
356bf215546Sopenharmony_ci            self.prefix = None
357bf215546Sopenharmony_ci
358bf215546Sopenharmony_ci        if "exact" in attrs:
359bf215546Sopenharmony_ci            self.exact = int(attrs["exact"])
360bf215546Sopenharmony_ci        else:
361bf215546Sopenharmony_ci            self.exact = None
362bf215546Sopenharmony_ci
363bf215546Sopenharmony_ci        self.default = attrs.get("default")
364bf215546Sopenharmony_ci
365bf215546Sopenharmony_ci        # Map enum values
366bf215546Sopenharmony_ci        if self.type in self.parser.enums and self.default is not None:
367bf215546Sopenharmony_ci            self.default = safe_name('{}_{}_{}'.format(global_prefix, self.type, self.default)).upper()
368bf215546Sopenharmony_ci
369bf215546Sopenharmony_ci        self.modifier  = parse_modifier(attrs.get("modifier"))
370bf215546Sopenharmony_ci
371bf215546Sopenharmony_ci    def emit_template_struct(self, dim):
372bf215546Sopenharmony_ci        if self.type == 'address':
373bf215546Sopenharmony_ci            type = 'uint64_t'
374bf215546Sopenharmony_ci        elif self.type == 'bool':
375bf215546Sopenharmony_ci            type = 'bool'
376bf215546Sopenharmony_ci        elif self.type == 'float':
377bf215546Sopenharmony_ci            type = 'float'
378bf215546Sopenharmony_ci        elif self.type in ['uint', 'hex'] and self.end - self.start > 32:
379bf215546Sopenharmony_ci            type = 'uint64_t'
380bf215546Sopenharmony_ci        elif self.type == 'int':
381bf215546Sopenharmony_ci            type = 'int32_t'
382bf215546Sopenharmony_ci        elif self.type in ['uint', 'hex', 'uint/float', 'padded', 'Pixel Format']:
383bf215546Sopenharmony_ci            type = 'uint32_t'
384bf215546Sopenharmony_ci        elif self.type in self.parser.structs:
385bf215546Sopenharmony_ci            type = 'struct ' + self.parser.gen_prefix(safe_name(self.type.upper()))
386bf215546Sopenharmony_ci        elif self.type in self.parser.enums:
387bf215546Sopenharmony_ci            type = 'enum ' + enum_name(self.type)
388bf215546Sopenharmony_ci        else:
389bf215546Sopenharmony_ci            print("#error unhandled type: %s" % self.type)
390bf215546Sopenharmony_ci            type = "uint32_t"
391bf215546Sopenharmony_ci
392bf215546Sopenharmony_ci        print("   %-36s %s%s;" % (type, self.name, dim))
393bf215546Sopenharmony_ci
394bf215546Sopenharmony_ci        for value in self.values:
395bf215546Sopenharmony_ci            name = prefixed_upper_name(self.prefix, value.name)
396bf215546Sopenharmony_ci            print("#define %-40s %d" % (name, value.value))
397bf215546Sopenharmony_ci
398bf215546Sopenharmony_ci    def overlaps(self, field):
399bf215546Sopenharmony_ci        return self != field and max(self.start, field.start) <= min(self.end, field.end)
400bf215546Sopenharmony_ci
401bf215546Sopenharmony_ciclass Group(object):
402bf215546Sopenharmony_ci    def __init__(self, parser, parent, start, count, label):
403bf215546Sopenharmony_ci        self.parser = parser
404bf215546Sopenharmony_ci        self.parent = parent
405bf215546Sopenharmony_ci        self.start = start
406bf215546Sopenharmony_ci        self.count = count
407bf215546Sopenharmony_ci        self.label = label
408bf215546Sopenharmony_ci        self.size = 0
409bf215546Sopenharmony_ci        self.length = 0
410bf215546Sopenharmony_ci        self.fields = []
411bf215546Sopenharmony_ci
412bf215546Sopenharmony_ci    def get_length(self):
413bf215546Sopenharmony_ci        # Determine number of bytes in this group.
414bf215546Sopenharmony_ci        calculated = max(field.end // 8 for field in self.fields) + 1 if len(self.fields) > 0 else 0
415bf215546Sopenharmony_ci        if self.length > 0:
416bf215546Sopenharmony_ci            assert(self.length >= calculated)
417bf215546Sopenharmony_ci        else:
418bf215546Sopenharmony_ci            self.length = calculated
419bf215546Sopenharmony_ci        return self.length
420bf215546Sopenharmony_ci
421bf215546Sopenharmony_ci
422bf215546Sopenharmony_ci    def emit_template_struct(self, dim):
423bf215546Sopenharmony_ci        if self.count == 0:
424bf215546Sopenharmony_ci            print("   /* variable length fields follow */")
425bf215546Sopenharmony_ci        else:
426bf215546Sopenharmony_ci            if self.count > 1:
427bf215546Sopenharmony_ci                dim = "%s[%d]" % (dim, self.count)
428bf215546Sopenharmony_ci
429bf215546Sopenharmony_ci            if len(self.fields) == 0:
430bf215546Sopenharmony_ci                print("   int dummy;")
431bf215546Sopenharmony_ci
432bf215546Sopenharmony_ci            for field in self.fields:
433bf215546Sopenharmony_ci                if field.exact is not None:
434bf215546Sopenharmony_ci                    continue
435bf215546Sopenharmony_ci
436bf215546Sopenharmony_ci                field.emit_template_struct(dim)
437bf215546Sopenharmony_ci
438bf215546Sopenharmony_ci    class Word:
439bf215546Sopenharmony_ci        def __init__(self):
440bf215546Sopenharmony_ci            self.size = 32
441bf215546Sopenharmony_ci            self.contributors = []
442bf215546Sopenharmony_ci
443bf215546Sopenharmony_ci    class FieldRef:
444bf215546Sopenharmony_ci        def __init__(self, field, path, start, end):
445bf215546Sopenharmony_ci            self.field = field
446bf215546Sopenharmony_ci            self.path = path
447bf215546Sopenharmony_ci            self.start = start
448bf215546Sopenharmony_ci            self.end = end
449bf215546Sopenharmony_ci
450bf215546Sopenharmony_ci    def collect_fields(self, fields, offset, path, all_fields):
451bf215546Sopenharmony_ci        for field in fields:
452bf215546Sopenharmony_ci            field_path = '{}{}'.format(path, field.name)
453bf215546Sopenharmony_ci            field_offset = offset + field.start
454bf215546Sopenharmony_ci
455bf215546Sopenharmony_ci            if field.type in self.parser.structs:
456bf215546Sopenharmony_ci                sub_struct = self.parser.structs[field.type]
457bf215546Sopenharmony_ci                self.collect_fields(sub_struct.fields, field_offset, field_path + '.', all_fields)
458bf215546Sopenharmony_ci                continue
459bf215546Sopenharmony_ci
460bf215546Sopenharmony_ci            start = field_offset
461bf215546Sopenharmony_ci            end = offset + field.end
462bf215546Sopenharmony_ci            all_fields.append(self.FieldRef(field, field_path, start, end))
463bf215546Sopenharmony_ci
464bf215546Sopenharmony_ci    def collect_words(self, fields, offset, path, words):
465bf215546Sopenharmony_ci        for field in fields:
466bf215546Sopenharmony_ci            field_path = '{}{}'.format(path, field.name)
467bf215546Sopenharmony_ci            start = offset + field.start
468bf215546Sopenharmony_ci
469bf215546Sopenharmony_ci            if field.type in self.parser.structs:
470bf215546Sopenharmony_ci                sub_fields = self.parser.structs[field.type].fields
471bf215546Sopenharmony_ci                self.collect_words(sub_fields, start, field_path + '.', words)
472bf215546Sopenharmony_ci                continue
473bf215546Sopenharmony_ci
474bf215546Sopenharmony_ci            end = offset + field.end
475bf215546Sopenharmony_ci            contributor = self.FieldRef(field, field_path, start, end)
476bf215546Sopenharmony_ci            first_word = contributor.start // 32
477bf215546Sopenharmony_ci            last_word = contributor.end // 32
478bf215546Sopenharmony_ci            for b in range(first_word, last_word + 1):
479bf215546Sopenharmony_ci                if not b in words:
480bf215546Sopenharmony_ci                    words[b] = self.Word()
481bf215546Sopenharmony_ci                words[b].contributors.append(contributor)
482bf215546Sopenharmony_ci
483bf215546Sopenharmony_ci    def emit_pack_function(self):
484bf215546Sopenharmony_ci        self.get_length()
485bf215546Sopenharmony_ci
486bf215546Sopenharmony_ci        words = {}
487bf215546Sopenharmony_ci        self.collect_words(self.fields, 0, '', words)
488bf215546Sopenharmony_ci
489bf215546Sopenharmony_ci        # Validate the modifier is lossless
490bf215546Sopenharmony_ci        for field in self.fields:
491bf215546Sopenharmony_ci            if field.modifier is None:
492bf215546Sopenharmony_ci                continue
493bf215546Sopenharmony_ci
494bf215546Sopenharmony_ci            assert(field.exact is None)
495bf215546Sopenharmony_ci
496bf215546Sopenharmony_ci            if field.modifier[0] == "shr":
497bf215546Sopenharmony_ci                shift = field.modifier[1]
498bf215546Sopenharmony_ci                mask = hex((1 << shift) - 1)
499bf215546Sopenharmony_ci                print("   assert((values->{} & {}) == 0);".format(field.name, mask))
500bf215546Sopenharmony_ci            elif field.modifier[0] == "minus":
501bf215546Sopenharmony_ci                print("   assert(values->{} >= {});".format(field.name, field.modifier[1]))
502bf215546Sopenharmony_ci            elif field.modifier[0] == "log2":
503bf215546Sopenharmony_ci                print("   assert(util_is_power_of_two_nonzero(values->{}));".format(field.name))
504bf215546Sopenharmony_ci
505bf215546Sopenharmony_ci        for index in range(self.length // 4):
506bf215546Sopenharmony_ci            # Handle MBZ words
507bf215546Sopenharmony_ci            if not index in words:
508bf215546Sopenharmony_ci                print("   cl[%2d] = 0;" % index)
509bf215546Sopenharmony_ci                continue
510bf215546Sopenharmony_ci
511bf215546Sopenharmony_ci            word = words[index]
512bf215546Sopenharmony_ci
513bf215546Sopenharmony_ci            word_start = index * 32
514bf215546Sopenharmony_ci
515bf215546Sopenharmony_ci            v = None
516bf215546Sopenharmony_ci            prefix = "   cl[%2d] =" % index
517bf215546Sopenharmony_ci
518bf215546Sopenharmony_ci            for contributor in word.contributors:
519bf215546Sopenharmony_ci                field = contributor.field
520bf215546Sopenharmony_ci                name = field.name
521bf215546Sopenharmony_ci                start = contributor.start
522bf215546Sopenharmony_ci                end = contributor.end
523bf215546Sopenharmony_ci                contrib_word_start = (start // 32) * 32
524bf215546Sopenharmony_ci                start -= contrib_word_start
525bf215546Sopenharmony_ci                end -= contrib_word_start
526bf215546Sopenharmony_ci
527bf215546Sopenharmony_ci                value = str(field.exact) if field.exact is not None else "values->{}".format(contributor.path)
528bf215546Sopenharmony_ci                if field.modifier is not None:
529bf215546Sopenharmony_ci                    if field.modifier[0] == "shr":
530bf215546Sopenharmony_ci                        value = "{} >> {}".format(value, field.modifier[1])
531bf215546Sopenharmony_ci                    elif field.modifier[0] == "minus":
532bf215546Sopenharmony_ci                        value = "{} - {}".format(value, field.modifier[1])
533bf215546Sopenharmony_ci                    elif field.modifier[0] == "align":
534bf215546Sopenharmony_ci                        value = "ALIGN_POT({}, {})".format(value, field.modifier[1])
535bf215546Sopenharmony_ci                    elif field.modifier[0] == "log2":
536bf215546Sopenharmony_ci                        value = "util_logbase2({})".format(value)
537bf215546Sopenharmony_ci
538bf215546Sopenharmony_ci                if field.type in ["uint", "hex", "uint/float", "address", "Pixel Format"]:
539bf215546Sopenharmony_ci                    s = "__gen_uint(%s, %d, %d)" % \
540bf215546Sopenharmony_ci                        (value, start, end)
541bf215546Sopenharmony_ci                elif field.type == "padded":
542bf215546Sopenharmony_ci                    s = "__gen_padded(%s, %d, %d)" % \
543bf215546Sopenharmony_ci                        (value, start, end)
544bf215546Sopenharmony_ci                elif field.type in self.parser.enums:
545bf215546Sopenharmony_ci                    s = "__gen_uint(%s, %d, %d)" % \
546bf215546Sopenharmony_ci                        (value, start, end)
547bf215546Sopenharmony_ci                elif field.type == "int":
548bf215546Sopenharmony_ci                    s = "__gen_sint(%s, %d, %d)" % \
549bf215546Sopenharmony_ci                        (value, start, end)
550bf215546Sopenharmony_ci                elif field.type == "bool":
551bf215546Sopenharmony_ci                    s = "__gen_uint(%s, %d, %d)" % \
552bf215546Sopenharmony_ci                        (value, start, end)
553bf215546Sopenharmony_ci                elif field.type == "float":
554bf215546Sopenharmony_ci                    assert(start == 0 and end == 31)
555bf215546Sopenharmony_ci                    s = "__gen_uint(fui({}), 0, 32)".format(value)
556bf215546Sopenharmony_ci                else:
557bf215546Sopenharmony_ci                    s = "#error unhandled field {}, type {}".format(contributor.path, field.type)
558bf215546Sopenharmony_ci
559bf215546Sopenharmony_ci                if not s == None:
560bf215546Sopenharmony_ci                    shift = word_start - contrib_word_start
561bf215546Sopenharmony_ci                    if shift:
562bf215546Sopenharmony_ci                        s = "%s >> %d" % (s, shift)
563bf215546Sopenharmony_ci
564bf215546Sopenharmony_ci                    if contributor == word.contributors[-1]:
565bf215546Sopenharmony_ci                        print("%s %s;" % (prefix, s))
566bf215546Sopenharmony_ci                    else:
567bf215546Sopenharmony_ci                        print("%s %s |" % (prefix, s))
568bf215546Sopenharmony_ci                    prefix = "           "
569bf215546Sopenharmony_ci
570bf215546Sopenharmony_ci            continue
571bf215546Sopenharmony_ci
572bf215546Sopenharmony_ci    # Given a field (start, end) contained in word `index`, generate the 32-bit
573bf215546Sopenharmony_ci    # mask of present bits relative to the word
574bf215546Sopenharmony_ci    def mask_for_word(self, index, start, end):
575bf215546Sopenharmony_ci        field_word_start = index * 32
576bf215546Sopenharmony_ci        start -= field_word_start
577bf215546Sopenharmony_ci        end -= field_word_start
578bf215546Sopenharmony_ci        # Cap multiword at one word
579bf215546Sopenharmony_ci        start = max(start, 0)
580bf215546Sopenharmony_ci        end = min(end, 32 - 1)
581bf215546Sopenharmony_ci        count = (end - start + 1)
582bf215546Sopenharmony_ci        return (((1 << count) - 1) << start)
583bf215546Sopenharmony_ci
584bf215546Sopenharmony_ci    def emit_unpack_function(self):
585bf215546Sopenharmony_ci        # First, verify there is no garbage in unused bits
586bf215546Sopenharmony_ci        words = {}
587bf215546Sopenharmony_ci        self.collect_words(self.fields, 0, '', words)
588bf215546Sopenharmony_ci
589bf215546Sopenharmony_ci        for index in range(self.length // 4):
590bf215546Sopenharmony_ci            base = index * 32
591bf215546Sopenharmony_ci            word = words.get(index, self.Word())
592bf215546Sopenharmony_ci            masks = [self.mask_for_word(index, c.start, c.end) for c in word.contributors]
593bf215546Sopenharmony_ci            mask = reduce(lambda x,y: x | y, masks, 0)
594bf215546Sopenharmony_ci
595bf215546Sopenharmony_ci            ALL_ONES = 0xffffffff
596bf215546Sopenharmony_ci
597bf215546Sopenharmony_ci            if mask != ALL_ONES:
598bf215546Sopenharmony_ci                TMPL = '   if (((const uint32_t *) cl)[{}] & {}) fprintf(stderr, "XXX: Invalid field of {} unpacked at word {}\\n");'
599bf215546Sopenharmony_ci                print(TMPL.format(index, hex(mask ^ ALL_ONES), self.label, index))
600bf215546Sopenharmony_ci
601bf215546Sopenharmony_ci        fieldrefs = []
602bf215546Sopenharmony_ci        self.collect_fields(self.fields, 0, '', fieldrefs)
603bf215546Sopenharmony_ci        for fieldref in fieldrefs:
604bf215546Sopenharmony_ci            field = fieldref.field
605bf215546Sopenharmony_ci            convert = None
606bf215546Sopenharmony_ci
607bf215546Sopenharmony_ci            args = []
608bf215546Sopenharmony_ci            args.append('cl')
609bf215546Sopenharmony_ci            args.append(str(fieldref.start))
610bf215546Sopenharmony_ci            args.append(str(fieldref.end))
611bf215546Sopenharmony_ci
612bf215546Sopenharmony_ci            if field.type in set(["uint", "hex", "uint/float", "address", "Pixel Format"]):
613bf215546Sopenharmony_ci                convert = "__gen_unpack_uint"
614bf215546Sopenharmony_ci            elif field.type in self.parser.enums:
615bf215546Sopenharmony_ci                convert = "(enum %s)__gen_unpack_uint" % enum_name(field.type)
616bf215546Sopenharmony_ci            elif field.type == "int":
617bf215546Sopenharmony_ci                convert = "__gen_unpack_sint"
618bf215546Sopenharmony_ci            elif field.type == "padded":
619bf215546Sopenharmony_ci                convert = "__gen_unpack_padded"
620bf215546Sopenharmony_ci            elif field.type == "bool":
621bf215546Sopenharmony_ci                convert = "__gen_unpack_uint"
622bf215546Sopenharmony_ci            elif field.type == "float":
623bf215546Sopenharmony_ci                convert = "__gen_unpack_float"
624bf215546Sopenharmony_ci            else:
625bf215546Sopenharmony_ci                s = "/* unhandled field %s, type %s */\n" % (field.name, field.type)
626bf215546Sopenharmony_ci
627bf215546Sopenharmony_ci            suffix = ""
628bf215546Sopenharmony_ci            prefix = ""
629bf215546Sopenharmony_ci            if field.modifier:
630bf215546Sopenharmony_ci                if field.modifier[0] == "minus":
631bf215546Sopenharmony_ci                    suffix = " + {}".format(field.modifier[1])
632bf215546Sopenharmony_ci                elif field.modifier[0] == "shr":
633bf215546Sopenharmony_ci                    suffix = " << {}".format(field.modifier[1])
634bf215546Sopenharmony_ci                if field.modifier[0] == "log2":
635bf215546Sopenharmony_ci                    prefix = "1U << "
636bf215546Sopenharmony_ci
637bf215546Sopenharmony_ci            decoded = '{}{}({}){}'.format(prefix, convert, ', '.join(args), suffix)
638bf215546Sopenharmony_ci
639bf215546Sopenharmony_ci            print('   values->{} = {};'.format(fieldref.path, decoded))
640bf215546Sopenharmony_ci            if field.modifier and field.modifier[0] == "align":
641bf215546Sopenharmony_ci                mask = hex(field.modifier[1] - 1)
642bf215546Sopenharmony_ci                print('   assert(!(values->{} & {}));'.format(fieldref.path, mask))
643bf215546Sopenharmony_ci
644bf215546Sopenharmony_ci    def emit_print_function(self):
645bf215546Sopenharmony_ci        for field in self.fields:
646bf215546Sopenharmony_ci            convert = None
647bf215546Sopenharmony_ci            name, val = field.human_name, 'values->{}'.format(field.name)
648bf215546Sopenharmony_ci
649bf215546Sopenharmony_ci            if field.type in self.parser.structs:
650bf215546Sopenharmony_ci                pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
651bf215546Sopenharmony_ci                print('   fprintf(fp, "%*s{}:\\n", indent, "");'.format(field.human_name))
652bf215546Sopenharmony_ci                print("   {}_print(fp, &values->{}, indent + 2);".format(pack_name, field.name))
653bf215546Sopenharmony_ci            elif field.type == "address":
654bf215546Sopenharmony_ci                # TODO resolve to name
655bf215546Sopenharmony_ci                print('   fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
656bf215546Sopenharmony_ci            elif field.type in self.parser.enums:
657bf215546Sopenharmony_ci                print('   fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name, enum_name(field.type), val))
658bf215546Sopenharmony_ci            elif field.type == "int":
659bf215546Sopenharmony_ci                print('   fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name, val))
660bf215546Sopenharmony_ci            elif field.type == "bool":
661bf215546Sopenharmony_ci                print('   fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name, val))
662bf215546Sopenharmony_ci            elif field.type == "float":
663bf215546Sopenharmony_ci                print('   fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name, val))
664bf215546Sopenharmony_ci            elif field.type in ["uint", "hex"] and (field.end - field.start) >= 32:
665bf215546Sopenharmony_ci                print('   fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
666bf215546Sopenharmony_ci            elif field.type == "hex":
667bf215546Sopenharmony_ci                print('   fprintf(fp, "%*s{}: 0x%x\\n", indent, "", {});'.format(name, val))
668bf215546Sopenharmony_ci            elif field.type == "uint/float":
669bf215546Sopenharmony_ci                print('   fprintf(fp, "%*s{}: 0x%X (%f)\\n", indent, "", {}, uif({}));'.format(name, val, val))
670bf215546Sopenharmony_ci            elif field.type == "Pixel Format":
671bf215546Sopenharmony_ci                print('   mali_pixel_format_print(fp, {});'.format(val))
672bf215546Sopenharmony_ci            else:
673bf215546Sopenharmony_ci                print('   fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name, val))
674bf215546Sopenharmony_ci
675bf215546Sopenharmony_ciclass Value(object):
676bf215546Sopenharmony_ci    def __init__(self, attrs):
677bf215546Sopenharmony_ci        self.name = attrs["name"]
678bf215546Sopenharmony_ci        self.value = int(attrs["value"], 0)
679bf215546Sopenharmony_ci
680bf215546Sopenharmony_ciclass Parser(object):
681bf215546Sopenharmony_ci    def __init__(self):
682bf215546Sopenharmony_ci        self.parser = xml.parsers.expat.ParserCreate()
683bf215546Sopenharmony_ci        self.parser.StartElementHandler = self.start_element
684bf215546Sopenharmony_ci        self.parser.EndElementHandler = self.end_element
685bf215546Sopenharmony_ci
686bf215546Sopenharmony_ci        self.struct = None
687bf215546Sopenharmony_ci        self.structs = {}
688bf215546Sopenharmony_ci        # Set of enum names we've seen.
689bf215546Sopenharmony_ci        self.enums = set()
690bf215546Sopenharmony_ci        self.aggregate = None
691bf215546Sopenharmony_ci        self.aggregates = {}
692bf215546Sopenharmony_ci
693bf215546Sopenharmony_ci    def gen_prefix(self, name):
694bf215546Sopenharmony_ci        return '{}_{}'.format(global_prefix.upper(), name)
695bf215546Sopenharmony_ci
696bf215546Sopenharmony_ci    def start_element(self, name, attrs):
697bf215546Sopenharmony_ci        if name == "panxml":
698bf215546Sopenharmony_ci            print(pack_header)
699bf215546Sopenharmony_ci            if "arch" in attrs:
700bf215546Sopenharmony_ci                arch = int(attrs["arch"])
701bf215546Sopenharmony_ci                if arch <= 6:
702bf215546Sopenharmony_ci                    print(v6_format_printer)
703bf215546Sopenharmony_ci                else:
704bf215546Sopenharmony_ci                    print(v7_format_printer)
705bf215546Sopenharmony_ci        elif name == "struct":
706bf215546Sopenharmony_ci            name = attrs["name"]
707bf215546Sopenharmony_ci            self.no_direct_packing = attrs.get("no-direct-packing", False)
708bf215546Sopenharmony_ci            object_name = self.gen_prefix(safe_name(name.upper()))
709bf215546Sopenharmony_ci            self.struct = object_name
710bf215546Sopenharmony_ci
711bf215546Sopenharmony_ci            self.group = Group(self, None, 0, 1, name)
712bf215546Sopenharmony_ci            if "size" in attrs:
713bf215546Sopenharmony_ci                self.group.length = int(attrs["size"]) * 4
714bf215546Sopenharmony_ci            self.group.align = int(attrs["align"]) if "align" in attrs else None
715bf215546Sopenharmony_ci            self.structs[attrs["name"]] = self.group
716bf215546Sopenharmony_ci        elif name == "field":
717bf215546Sopenharmony_ci            self.group.fields.append(Field(self, attrs))
718bf215546Sopenharmony_ci            self.values = []
719bf215546Sopenharmony_ci        elif name == "enum":
720bf215546Sopenharmony_ci            self.values = []
721bf215546Sopenharmony_ci            self.enum = safe_name(attrs["name"])
722bf215546Sopenharmony_ci            self.enums.add(attrs["name"])
723bf215546Sopenharmony_ci            if "prefix" in attrs:
724bf215546Sopenharmony_ci                self.prefix = attrs["prefix"]
725bf215546Sopenharmony_ci            else:
726bf215546Sopenharmony_ci                self.prefix= None
727bf215546Sopenharmony_ci        elif name == "value":
728bf215546Sopenharmony_ci            self.values.append(Value(attrs))
729bf215546Sopenharmony_ci        elif name == "aggregate":
730bf215546Sopenharmony_ci            aggregate_name = self.gen_prefix(safe_name(attrs["name"].upper()))
731bf215546Sopenharmony_ci            self.aggregate = Aggregate(self, aggregate_name, attrs)
732bf215546Sopenharmony_ci            self.aggregates[attrs['name']] = self.aggregate
733bf215546Sopenharmony_ci        elif name == "section":
734bf215546Sopenharmony_ci            type_name = self.gen_prefix(safe_name(attrs["type"].upper()))
735bf215546Sopenharmony_ci            self.aggregate.add_section(type_name, attrs)
736bf215546Sopenharmony_ci
737bf215546Sopenharmony_ci    def end_element(self, name):
738bf215546Sopenharmony_ci        if name == "struct":
739bf215546Sopenharmony_ci            self.emit_struct()
740bf215546Sopenharmony_ci            self.struct = None
741bf215546Sopenharmony_ci            self.group = None
742bf215546Sopenharmony_ci        elif name  == "field":
743bf215546Sopenharmony_ci            self.group.fields[-1].values = self.values
744bf215546Sopenharmony_ci        elif name  == "enum":
745bf215546Sopenharmony_ci            self.emit_enum()
746bf215546Sopenharmony_ci            self.enum = None
747bf215546Sopenharmony_ci        elif name == "aggregate":
748bf215546Sopenharmony_ci            self.emit_aggregate()
749bf215546Sopenharmony_ci            self.aggregate = None
750bf215546Sopenharmony_ci        elif name == "panxml":
751bf215546Sopenharmony_ci            # Include at the end so it can depend on us but not the converse
752bf215546Sopenharmony_ci            print('#include "panfrost-job.h"')
753bf215546Sopenharmony_ci            print('#endif')
754bf215546Sopenharmony_ci
755bf215546Sopenharmony_ci    def emit_header(self, name):
756bf215546Sopenharmony_ci        default_fields = []
757bf215546Sopenharmony_ci        for field in self.group.fields:
758bf215546Sopenharmony_ci            if not type(field) is Field:
759bf215546Sopenharmony_ci                continue
760bf215546Sopenharmony_ci            if field.default is not None:
761bf215546Sopenharmony_ci                default_fields.append("   .{} = {}".format(field.name, field.default))
762bf215546Sopenharmony_ci            elif field.type in self.structs:
763bf215546Sopenharmony_ci                default_fields.append("   .{} = {{ {}_header }}".format(field.name, self.gen_prefix(safe_name(field.type.upper()))))
764bf215546Sopenharmony_ci
765bf215546Sopenharmony_ci        print('#define %-40s\\' % (name + '_header'))
766bf215546Sopenharmony_ci        if default_fields:
767bf215546Sopenharmony_ci            print(",  \\\n".join(default_fields))
768bf215546Sopenharmony_ci        else:
769bf215546Sopenharmony_ci            print('   0')
770bf215546Sopenharmony_ci        print('')
771bf215546Sopenharmony_ci
772bf215546Sopenharmony_ci    def emit_template_struct(self, name, group):
773bf215546Sopenharmony_ci        print("struct %s {" % name)
774bf215546Sopenharmony_ci        group.emit_template_struct("")
775bf215546Sopenharmony_ci        print("};\n")
776bf215546Sopenharmony_ci
777bf215546Sopenharmony_ci    def emit_aggregate(self):
778bf215546Sopenharmony_ci        aggregate = self.aggregate
779bf215546Sopenharmony_ci        print("struct %s_packed {" % aggregate.name.lower())
780bf215546Sopenharmony_ci        print("   uint32_t opaque[{}];".format(aggregate.get_size() // 4))
781bf215546Sopenharmony_ci        print("};\n")
782bf215546Sopenharmony_ci        print('#define {}_LENGTH {}'.format(aggregate.name.upper(), aggregate.size))
783bf215546Sopenharmony_ci        if aggregate.align != None:
784bf215546Sopenharmony_ci            print('#define {}_ALIGN {}'.format(aggregate.name.upper(), aggregate.align))
785bf215546Sopenharmony_ci        for section in aggregate.sections:
786bf215546Sopenharmony_ci            print('#define {}_SECTION_{}_TYPE struct {}'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
787bf215546Sopenharmony_ci            print('#define {}_SECTION_{}_header {}_header'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
788bf215546Sopenharmony_ci            print('#define {}_SECTION_{}_pack {}_pack'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
789bf215546Sopenharmony_ci            print('#define {}_SECTION_{}_unpack {}_unpack'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
790bf215546Sopenharmony_ci            print('#define {}_SECTION_{}_print {}_print'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
791bf215546Sopenharmony_ci            print('#define {}_SECTION_{}_OFFSET {}'.format(aggregate.name.upper(), section.name.upper(), section.offset))
792bf215546Sopenharmony_ci        print("")
793bf215546Sopenharmony_ci
794bf215546Sopenharmony_ci    def emit_pack_function(self, name, group):
795bf215546Sopenharmony_ci        print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
796bf215546Sopenharmony_ci              (name, ' ' * (len(name) + 6), name))
797bf215546Sopenharmony_ci
798bf215546Sopenharmony_ci        group.emit_pack_function()
799bf215546Sopenharmony_ci
800bf215546Sopenharmony_ci        print("}\n\n")
801bf215546Sopenharmony_ci
802bf215546Sopenharmony_ci        # Should be a whole number of words
803bf215546Sopenharmony_ci        assert((self.group.length % 4) == 0)
804bf215546Sopenharmony_ci
805bf215546Sopenharmony_ci        print('#define {} {}'.format (name + "_LENGTH", self.group.length))
806bf215546Sopenharmony_ci        if self.group.align != None:
807bf215546Sopenharmony_ci            print('#define {} {}'.format (name + "_ALIGN", self.group.align))
808bf215546Sopenharmony_ci        print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name.lower(), self.group.length // 4))
809bf215546Sopenharmony_ci
810bf215546Sopenharmony_ci    def emit_unpack_function(self, name, group):
811bf215546Sopenharmony_ci        print("static inline void")
812bf215546Sopenharmony_ci        print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
813bf215546Sopenharmony_ci              (name.upper(), ' ' * (len(name) + 8), name))
814bf215546Sopenharmony_ci
815bf215546Sopenharmony_ci        group.emit_unpack_function()
816bf215546Sopenharmony_ci
817bf215546Sopenharmony_ci        print("}\n")
818bf215546Sopenharmony_ci
819bf215546Sopenharmony_ci    def emit_print_function(self, name, group):
820bf215546Sopenharmony_ci        print("static inline void")
821bf215546Sopenharmony_ci        print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name.upper(), name))
822bf215546Sopenharmony_ci
823bf215546Sopenharmony_ci        group.emit_print_function()
824bf215546Sopenharmony_ci
825bf215546Sopenharmony_ci        print("}\n")
826bf215546Sopenharmony_ci
827bf215546Sopenharmony_ci    def emit_struct(self):
828bf215546Sopenharmony_ci        name = self.struct
829bf215546Sopenharmony_ci
830bf215546Sopenharmony_ci        self.emit_template_struct(self.struct, self.group)
831bf215546Sopenharmony_ci        self.emit_header(name)
832bf215546Sopenharmony_ci        if self.no_direct_packing == False:
833bf215546Sopenharmony_ci            self.emit_pack_function(self.struct, self.group)
834bf215546Sopenharmony_ci            self.emit_unpack_function(self.struct, self.group)
835bf215546Sopenharmony_ci        self.emit_print_function(self.struct, self.group)
836bf215546Sopenharmony_ci
837bf215546Sopenharmony_ci    def enum_prefix(self, name):
838bf215546Sopenharmony_ci        return
839bf215546Sopenharmony_ci
840bf215546Sopenharmony_ci    def emit_enum(self):
841bf215546Sopenharmony_ci        e_name = enum_name(self.enum)
842bf215546Sopenharmony_ci        prefix = e_name if self.enum != 'Format' else global_prefix
843bf215546Sopenharmony_ci        print('enum {} {{'.format(e_name))
844bf215546Sopenharmony_ci
845bf215546Sopenharmony_ci        for value in self.values:
846bf215546Sopenharmony_ci            name = '{}_{}'.format(prefix, value.name)
847bf215546Sopenharmony_ci            name = safe_name(name).upper()
848bf215546Sopenharmony_ci            print('        % -36s = %6d,' % (name, value.value))
849bf215546Sopenharmony_ci        print('};\n')
850bf215546Sopenharmony_ci
851bf215546Sopenharmony_ci        print("static inline const char *")
852bf215546Sopenharmony_ci        print("{}_as_str(enum {} imm)\n{{".format(e_name.lower(), e_name))
853bf215546Sopenharmony_ci        print("    switch (imm) {")
854bf215546Sopenharmony_ci        for value in self.values:
855bf215546Sopenharmony_ci            name = '{}_{}'.format(prefix, value.name)
856bf215546Sopenharmony_ci            name = safe_name(name).upper()
857bf215546Sopenharmony_ci            print('    case {}: return "{}";'.format(name, value.name))
858bf215546Sopenharmony_ci        print('    default: return "XXX: INVALID";')
859bf215546Sopenharmony_ci        print("    }")
860bf215546Sopenharmony_ci        print("}\n")
861bf215546Sopenharmony_ci
862bf215546Sopenharmony_ci    def parse(self, filename):
863bf215546Sopenharmony_ci        file = open(filename, "rb")
864bf215546Sopenharmony_ci        self.parser.ParseFile(file)
865bf215546Sopenharmony_ci        file.close()
866bf215546Sopenharmony_ci
867bf215546Sopenharmony_ciif len(sys.argv) < 2:
868bf215546Sopenharmony_ci    print("No input xml file specified")
869bf215546Sopenharmony_ci    sys.exit(1)
870bf215546Sopenharmony_ci
871bf215546Sopenharmony_ciinput_file = sys.argv[1]
872bf215546Sopenharmony_ci
873bf215546Sopenharmony_cip = Parser()
874bf215546Sopenharmony_cip.parse(input_file)
875