3 # Copyright (C) 2016 Intel Corporation
4 # Copyright (C) 2016 Broadcom
5 # Copyright (C) 2020 Collabora, Ltd.
7 # Permission is hereby granted, free of charge, to any person obtaining a
8 # copy of this software and associated documentation files (the "Software"),
9 # to deal in the Software without restriction, including without limitation
10 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 # and/or sell copies of the Software, and to permit persons to whom the
12 # Software is furnished to do so, subject to the following conditions:
14 # The above copyright notice and this permission notice (including the next
15 # paragraph) shall be included in all copies or substantial portions of the
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
26 import xml.parsers.expat
30 from functools import reduce
35 /* Generated code, see midgard.xml and gen_pack_header.py
37 * Packets, enums and structures for Panfrost.
39 * This file has been generated, do not hand edit.
48 #include "util/bitpack_helpers.h"
50 #define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
52 static inline uint64_t
53 __gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
56 const int width = end - start + 1;
57 const uint64_t mask = (width == 64 ? ~0 : (1ull << width) - 1 );
59 for (unsigned byte = start / 8; byte <= end / 8; byte++) {
60 val |= ((uint64_t) cl[byte]) << ((byte - start / 8) * 8);
63 return (val >> (start % 8)) & mask;
67 * LODs are 4:6 fixed point. We must clamp before converting to integers to
68 * avoid undefined behaviour for out-of-bounds inputs like +/- infinity.
70 static inline uint32_t
71 __gen_pack_lod(float f, uint32_t start, uint32_t end)
73 uint32_t fixed = CLAMP(f * (1 << 6), 0 /* 0.0 */, 0x380 /* 14.0 */);
74 return util_bitpack_uint(fixed, start, end);
78 __gen_unpack_lod(const uint8_t *restrict cl, uint32_t start, uint32_t end)
80 return ((float) __gen_unpack_uint(cl, start, end)) / (1 << 6);
83 static inline uint64_t
84 __gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
86 int size = end - start + 1;
87 int64_t val = __gen_unpack_uint(cl, start, end);
89 return util_sign_extend(val, size);
92 #define agx_pack(dst, T, name) \\
93 for (struct AGX_ ## T name = { AGX_ ## T ## _header }, \\
94 *_loop_terminate = (void *) (dst); \\
95 __builtin_expect(_loop_terminate != NULL, 1); \\
96 ({ AGX_ ## T ## _pack((uint32_t *) (dst), &name); \\
97 _loop_terminate = NULL; }))
99 #define agx_unpack(fp, src, T, name) \\
100 struct AGX_ ## T name; \\
101 AGX_ ## T ## _unpack(fp, (uint8_t *)(src), &name)
103 #define agx_print(fp, T, var, indent) \\
104 AGX_ ## T ## _print(fp, &(var), indent)
108 def to_alphanum(name):
130 for i, j in substitutions.items():
131 name = name.replace(i, j)
136 name = to_alphanum(name)
137 if not name[0].isalpha():
142 def prefixed_upper_name(prefix, name):
144 name = prefix + "_" + name
145 return safe_name(name).upper()
148 return "{}_{}".format(global_prefix, safe_name(name)).lower()
150 MODIFIERS = ["shr", "minus", "align", "log2"]
152 def parse_modifier(modifier):
156 for mod in MODIFIERS:
157 if modifier[0:len(mod)] == mod:
159 assert(len(mod) == len(modifier))
162 if modifier[len(mod)] == '(' and modifier[-1] == ')':
163 ret = [mod, int(modifier[(len(mod) + 1):-1])]
164 if ret[0] == 'align':
166 # Make sure the alignment is a power of 2
167 assert(align > 0 and not(align & (align - 1)));
171 print("Invalid modifier")
175 def __init__(self, parser, attrs):
178 self.name = safe_name(attrs["name"]).lower()
179 self.human_name = attrs["name"]
181 if ":" in str(attrs["start"]):
182 (word, bit) = attrs["start"].split(":")
183 self.start = (int(word) * 32) + int(bit)
185 self.start = int(attrs["start"])
187 self.end = self.start + int(attrs["size"]) - 1
188 self.type = attrs["type"]
190 if self.type == 'bool' and self.start != self.end:
191 print("#error Field {} has bool type but more than one bit of size".format(self.name));
193 if "prefix" in attrs:
194 self.prefix = safe_name(attrs["prefix"]).upper()
198 self.default = attrs.get("default")
201 if self.type in self.parser.enums and self.default is not None:
202 self.default = safe_name('{}_{}_{}'.format(global_prefix, self.type, self.default)).upper()
204 self.modifier = parse_modifier(attrs.get("modifier"))
206 def emit_template_struct(self, dim):
207 if self.type == 'address':
209 elif self.type == 'bool':
211 elif self.type in ['float', 'lod']:
213 elif self.type in ['uint', 'hex'] and self.end - self.start > 32:
215 elif self.type == 'int':
217 elif self.type in ['uint', 'hex']:
219 elif self.type in self.parser.structs:
220 type = 'struct ' + self.parser.gen_prefix(safe_name(self.type.upper()))
221 elif self.type in self.parser.enums:
222 type = 'enum ' + enum_name(self.type)
224 print("#error unhandled type: %s" % self.type)
227 print(" %-36s %s%s;" % (type, self.name, dim))
229 for value in self.values:
230 name = prefixed_upper_name(self.prefix, value.name)
231 print("#define %-40s %d" % (name, value.value))
233 def overlaps(self, field):
234 return self != field and max(self.start, field.start) <= min(self.end, field.end)
237 def __init__(self, parser, parent, start, count, label):
247 def get_length(self):
248 # Determine number of bytes in this group.
249 calculated = max(field.end // 8 for field in self.fields) + 1 if len(self.fields) > 0 else 0
251 assert(self.length >= calculated)
253 self.length = calculated
257 def emit_template_struct(self, dim):
259 print(" /* variable length fields follow */")
262 dim = "%s[%d]" % (dim, self.count)
264 if len(self.fields) == 0:
267 for field in self.fields:
268 field.emit_template_struct(dim)
273 self.contributors = []
276 def __init__(self, field, path, start, end):
282 def collect_fields(self, fields, offset, path, all_fields):
284 field_path = '{}{}'.format(path, field.name)
285 field_offset = offset + field.start
287 if field.type in self.parser.structs:
288 sub_struct = self.parser.structs[field.type]
289 self.collect_fields(sub_struct.fields, field_offset, field_path + '.', all_fields)
293 end = offset + field.end
294 all_fields.append(self.FieldRef(field, field_path, start, end))
296 def collect_words(self, fields, offset, path, words):
298 field_path = '{}{}'.format(path, field.name)
299 start = offset + field.start
301 if field.type in self.parser.structs:
302 sub_fields = self.parser.structs[field.type].fields
303 self.collect_words(sub_fields, start, field_path + '.', words)
306 end = offset + field.end
307 contributor = self.FieldRef(field, field_path, start, end)
308 first_word = contributor.start // 32
309 last_word = contributor.end // 32
310 for b in range(first_word, last_word + 1):
312 words[b] = self.Word()
313 words[b].contributors.append(contributor)
315 def emit_pack_function(self):
319 self.collect_words(self.fields, 0, '', words)
321 # Validate the modifier is lossless
322 for field in self.fields:
323 if field.modifier is None:
326 if field.modifier[0] == "shr":
327 shift = field.modifier[1]
328 mask = hex((1 << shift) - 1)
329 print(" assert((values->{} & {}) == 0);".format(field.name, mask))
330 elif field.modifier[0] == "minus":
331 print(" assert(values->{} >= {});".format(field.name, field.modifier[1]))
332 elif field.modifier[0] == "log2":
333 print(" assert(util_is_power_of_two_nonzero(values->{}));".format(field.name))
335 for index in range(math.ceil(self.length / 4)):
337 if not index in words:
338 print(" cl[%2d] = 0;" % index)
343 word_start = index * 32
346 prefix = " cl[%2d] =" % index
348 for contributor in word.contributors:
349 field = contributor.field
351 start = contributor.start
352 end = contributor.end
353 contrib_word_start = (start // 32) * 32
354 start -= contrib_word_start
355 end -= contrib_word_start
357 value = "values->{}".format(contributor.path)
358 if field.modifier is not None:
359 if field.modifier[0] == "shr":
360 value = "{} >> {}".format(value, field.modifier[1])
361 elif field.modifier[0] == "minus":
362 value = "{} - {}".format(value, field.modifier[1])
363 elif field.modifier[0] == "align":
364 value = "ALIGN_POT({}, {})".format(value, field.modifier[1])
365 elif field.modifier[0] == "log2":
366 value = "util_logbase2({})".format(value)
368 if field.type in ["uint", "hex", "address"]:
369 s = "util_bitpack_uint(%s, %d, %d)" % \
371 elif field.type in self.parser.enums:
372 s = "util_bitpack_uint(%s, %d, %d)" % \
374 elif field.type == "int":
375 s = "util_bitpack_sint(%s, %d, %d)" % \
377 elif field.type == "bool":
378 s = "util_bitpack_uint(%s, %d, %d)" % \
380 elif field.type == "float":
381 assert(start == 0 and end == 31)
382 s = "util_bitpack_float({})".format(value)
383 elif field.type == "lod":
384 assert(end - start + 1 == 10)
385 s = "__gen_pack_lod(%s, %d, %d)" % (value, start, end)
387 s = "#error unhandled field {}, type {}".format(contributor.path, field.type)
390 shift = word_start - contrib_word_start
392 s = "%s >> %d" % (s, shift)
394 if contributor == word.contributors[-1]:
395 print("%s %s;" % (prefix, s))
397 print("%s %s |" % (prefix, s))
402 # Given a field (start, end) contained in word `index`, generate the 32-bit
403 # mask of present bits relative to the word
404 def mask_for_word(self, index, start, end):
405 field_word_start = index * 32
406 start -= field_word_start
407 end -= field_word_start
408 # Cap multiword at one word
409 start = max(start, 0)
410 end = min(end, 32 - 1)
411 count = (end - start + 1)
412 return (((1 << count) - 1) << start)
414 def emit_unpack_function(self):
415 # First, verify there is no garbage in unused bits
417 self.collect_words(self.fields, 0, '', words)
419 for index in range(self.length // 4):
421 word = words.get(index, self.Word())
422 masks = [self.mask_for_word(index, c.start, c.end) for c in word.contributors]
423 mask = reduce(lambda x,y: x | y, masks, 0)
425 ALL_ONES = 0xffffffff
428 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)[{}] & {});'
429 print(TMPL.format(index, hex(mask ^ ALL_ONES), self.label, index, index, index, hex(mask ^ ALL_ONES)))
432 self.collect_fields(self.fields, 0, '', fieldrefs)
433 for fieldref in fieldrefs:
434 field = fieldref.field
439 args.append(str(fieldref.start))
440 args.append(str(fieldref.end))
442 if field.type in set(["uint", "address", "hex"]) | self.parser.enums:
443 convert = "__gen_unpack_uint"
444 elif field.type == "int":
445 convert = "__gen_unpack_sint"
446 elif field.type == "bool":
447 convert = "__gen_unpack_uint"
448 elif field.type == "float":
449 convert = "__gen_unpack_float"
450 elif field.type == "lod":
451 convert = "__gen_unpack_lod"
453 s = "/* unhandled field %s, type %s */\n" % (field.name, field.type)
458 if field.modifier[0] == "minus":
459 suffix = " + {}".format(field.modifier[1])
460 elif field.modifier[0] == "shr":
461 suffix = " << {}".format(field.modifier[1])
462 if field.modifier[0] == "log2":
465 if field.type in self.parser.enums:
466 prefix = f"(enum {enum_name(field.type)}) {prefix}"
468 decoded = '{}{}({}){}'.format(prefix, convert, ', '.join(args), suffix)
470 print(' values->{} = {};'.format(fieldref.path, decoded))
471 if field.modifier and field.modifier[0] == "align":
472 mask = hex(field.modifier[1] - 1)
473 print(' assert(!(values->{} & {}));'.format(fieldref.path, mask))
475 def emit_print_function(self):
476 for field in self.fields:
478 name, val = field.human_name, 'values->{}'.format(field.name)
480 if field.type in self.parser.structs:
481 pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
482 print(' fprintf(fp, "%*s{}:\\n", indent, "");'.format(field.human_name))
483 print(" {}_print(fp, &values->{}, indent + 2);".format(pack_name, field.name))
484 elif field.type == "address":
485 # TODO resolve to name
486 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
487 elif field.type in self.parser.enums:
488 print(' if ({}_as_str({}))'.format(enum_name(field.type), val))
489 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name, enum_name(field.type), val))
491 print(' fprintf(fp, "%*s{}: unknown %X (XXX)\\n", indent, "", {});'.format(name, val))
492 elif field.type == "int":
493 print(' fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name, val))
494 elif field.type == "bool":
495 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name, val))
496 elif field.type in ["float", "lod"]:
497 print(' fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name, val))
498 elif field.type in ["uint", "hex"] and (field.end - field.start) >= 32:
499 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
500 elif field.type == "hex":
501 print(' fprintf(fp, "%*s{}: 0x%" PRIx32 "\\n", indent, "", {});'.format(name, val))
503 print(' fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name, val))
506 def __init__(self, attrs):
507 self.name = attrs["name"]
508 self.value = int(attrs["value"], 0)
510 class Parser(object):
512 self.parser = xml.parsers.expat.ParserCreate()
513 self.parser.StartElementHandler = self.start_element
514 self.parser.EndElementHandler = self.end_element
518 # Set of enum names we've seen.
521 def gen_prefix(self, name):
522 return '{}_{}'.format(global_prefix.upper(), name)
524 def start_element(self, name, attrs):
527 elif name == "struct":
529 object_name = self.gen_prefix(safe_name(name.upper()))
530 self.struct = object_name
532 self.group = Group(self, None, 0, 1, name)
534 self.group.length = int(attrs["size"])
535 self.group.align = int(attrs["align"]) if "align" in attrs else None
536 self.structs[attrs["name"]] = self.group
537 elif name == "field":
538 self.group.fields.append(Field(self, attrs))
542 self.enum = safe_name(attrs["name"])
543 self.enums.add(attrs["name"])
544 if "prefix" in attrs:
545 self.prefix = attrs["prefix"]
548 elif name == "value":
549 self.values.append(Value(attrs))
551 def end_element(self, name):
556 elif name == "field":
557 self.group.fields[-1].values = self.values
561 elif name == "genxml":
564 def emit_header(self, name):
566 for field in self.group.fields:
567 if not type(field) is Field:
569 if field.default is not None:
570 default_fields.append(" .{} = {}".format(field.name, field.default))
571 elif field.type in self.structs:
572 default_fields.append(" .{} = {{ {}_header }}".format(field.name, self.gen_prefix(safe_name(field.type.upper()))))
574 print('#define %-40s\\' % (name + '_header'))
576 print(", \\\n".join(default_fields))
581 def emit_template_struct(self, name, group):
582 print("struct %s {" % name)
583 group.emit_template_struct("")
586 def emit_pack_function(self, name, group):
587 print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
588 (name, ' ' * (len(name) + 6), name))
590 group.emit_pack_function()
594 print('#define {} {}'.format (name + "_LENGTH", self.group.length))
595 if self.group.align != None:
596 print('#define {} {}'.format (name + "_ALIGN", self.group.align))
597 print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name.lower(), self.group.length // 4))
599 def emit_unpack_function(self, name, group):
600 print("static inline void")
601 print("%s_unpack(FILE *fp, const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
602 (name.upper(), ' ' * (len(name) + 8), name))
604 group.emit_unpack_function()
608 def emit_print_function(self, name, group):
609 print("static inline void")
610 print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name.upper(), name))
612 group.emit_print_function()
616 def emit_struct(self):
619 self.emit_template_struct(self.struct, self.group)
620 self.emit_header(name)
621 self.emit_pack_function(self.struct, self.group)
622 self.emit_unpack_function(self.struct, self.group)
623 self.emit_print_function(self.struct, self.group)
625 def enum_prefix(self, name):
629 e_name = enum_name(self.enum)
630 prefix = e_name if self.enum != 'Format' else global_prefix
631 print('enum {} {{'.format(e_name))
633 for value in self.values:
634 name = '{}_{}'.format(prefix, value.name)
635 name = safe_name(name).upper()
636 print(' % -36s = %6d,' % (name, value.value))
639 print("static inline const char *")
640 print("{}_as_str(enum {} imm)\n{{".format(e_name.lower(), e_name))
641 print(" switch (imm) {")
642 for value in self.values:
643 name = '{}_{}'.format(prefix, value.name)
644 name = safe_name(name).upper()
645 print(' case {}: return "{}";'.format(name, value.name))
646 print(' default: break;')
648 print(" return NULL;")
651 def parse(self, filename):
652 file = open(filename, "rb")
653 self.parser.ParseFile(file)
656 if len(sys.argv) < 2:
657 print("No input xml file specified")
660 input_file = sys.argv[1]