asahi: Remove no-direct-packing
[platform/upstream/mesa.git] / src / asahi / lib / gen_pack.py
1 #encoding=utf-8
2
3 # Copyright (C) 2016 Intel Corporation
4 # Copyright (C) 2016 Broadcom
5 # Copyright (C) 2020 Collabora, Ltd.
6 #
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:
13 #
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
16 # Software.
17 #
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
24 # IN THE SOFTWARE.
25
26 import xml.parsers.expat
27 import sys
28 import operator
29 import math
30 from functools import reduce
31
32 global_prefix = "agx"
33
34 pack_header = """
35 /* Generated code, see midgard.xml and gen_pack_header.py
36  *
37  * Packets, enums and structures for Panfrost.
38  *
39  * This file has been generated, do not hand edit.
40  */
41
42 #ifndef AGX_PACK_H
43 #define AGX_PACK_H
44
45 #include <stdio.h>
46 #include <inttypes.h>
47
48 #include "util/bitpack_helpers.h"
49
50 #define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
51
52 static inline uint64_t
53 __gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
54 {
55    uint64_t val = 0;
56    const int width = end - start + 1;
57    const uint64_t mask = (width == 64 ? ~0 : (1ull << width) - 1 );
58
59    for (unsigned byte = start / 8; byte <= end / 8; byte++) {
60       val |= ((uint64_t) cl[byte]) << ((byte - start / 8) * 8);
61    }
62
63    return (val >> (start % 8)) & mask;
64 }
65
66 /*
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.
69  */
70 static inline uint32_t
71 __gen_pack_lod(float f, uint32_t start, uint32_t end)
72 {
73     uint32_t fixed = CLAMP(f * (1 << 6), 0 /* 0.0 */, 0x380 /* 14.0 */);
74     return util_bitpack_uint(fixed, start, end);
75 }
76
77 static inline float
78 __gen_unpack_lod(const uint8_t *restrict cl, uint32_t start, uint32_t end)
79 {
80     return ((float) __gen_unpack_uint(cl, start, end)) / (1 << 6);
81 }
82
83 static inline uint64_t
84 __gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
85 {
86    int size = end - start + 1;
87    int64_t val = __gen_unpack_uint(cl, start, end);
88
89    return util_sign_extend(val, size);
90 }
91
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; }))
98
99 #define agx_unpack(fp, src, T, name)                        \\
100         struct AGX_ ## T name;                         \\
101         AGX_ ## T ## _unpack(fp, (uint8_t *)(src), &name)
102
103 #define agx_print(fp, T, var, indent)                   \\
104         AGX_ ## T ## _print(fp, &(var), indent)
105
106 """
107
108 def to_alphanum(name):
109     substitutions = {
110         ' ': '_',
111         '/': '_',
112         '[': '',
113         ']': '',
114         '(': '',
115         ')': '',
116         '-': '_',
117         ':': '',
118         '.': '',
119         ',': '',
120         '=': '',
121         '>': '',
122         '#': '',
123         '&': '',
124         '*': '',
125         '"': '',
126         '+': '',
127         '\'': '',
128     }
129
130     for i, j in substitutions.items():
131         name = name.replace(i, j)
132
133     return name
134
135 def safe_name(name):
136     name = to_alphanum(name)
137     if not name[0].isalpha():
138         name = '_' + name
139
140     return name
141
142 def prefixed_upper_name(prefix, name):
143     if prefix:
144         name = prefix + "_" + name
145     return safe_name(name).upper()
146
147 def enum_name(name):
148     return "{}_{}".format(global_prefix, safe_name(name)).lower()
149
150 MODIFIERS = ["shr", "minus", "align", "log2"]
151
152 def parse_modifier(modifier):
153     if modifier is None:
154         return None
155
156     for mod in MODIFIERS:
157         if modifier[0:len(mod)] == mod:
158             if mod == "log2":
159                 assert(len(mod) == len(modifier))
160                 return [mod]
161
162             if modifier[len(mod)] == '(' and modifier[-1] == ')':
163                 ret = [mod, int(modifier[(len(mod) + 1):-1])]
164                 if ret[0] == 'align':
165                     align = ret[1]
166                     # Make sure the alignment is a power of 2
167                     assert(align > 0 and not(align & (align - 1)));
168
169                 return ret
170
171     print("Invalid modifier")
172     assert(False)
173
174 class Field(object):
175     def __init__(self, parser, attrs):
176         self.parser = parser
177         if "name" in attrs:
178             self.name = safe_name(attrs["name"]).lower()
179             self.human_name = attrs["name"]
180
181         if ":" in str(attrs["start"]):
182             (word, bit) = attrs["start"].split(":")
183             self.start = (int(word) * 32) + int(bit)
184         else:
185             self.start = int(attrs["start"])
186
187         self.end = self.start + int(attrs["size"]) - 1
188         self.type = attrs["type"]
189
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));
192
193         if "prefix" in attrs:
194             self.prefix = safe_name(attrs["prefix"]).upper()
195         else:
196             self.prefix = None
197
198         self.default = attrs.get("default")
199
200         # Map enum values
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()
203
204         self.modifier  = parse_modifier(attrs.get("modifier"))
205
206     def emit_template_struct(self, dim):
207         if self.type == 'address':
208             type = 'uint64_t'
209         elif self.type == 'bool':
210             type = 'bool'
211         elif self.type in ['float', 'lod']:
212             type = 'float'
213         elif self.type in ['uint', 'hex'] and self.end - self.start > 32:
214             type = 'uint64_t'
215         elif self.type == 'int':
216             type = 'int32_t'
217         elif self.type in ['uint', 'hex']:
218             type = 'uint32_t'
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)
223         else:
224             print("#error unhandled type: %s" % self.type)
225             type = "uint32_t"
226
227         print("   %-36s %s%s;" % (type, self.name, dim))
228
229         for value in self.values:
230             name = prefixed_upper_name(self.prefix, value.name)
231             print("#define %-40s %d" % (name, value.value))
232
233     def overlaps(self, field):
234         return self != field and max(self.start, field.start) <= min(self.end, field.end)
235
236 class Group(object):
237     def __init__(self, parser, parent, start, count, label):
238         self.parser = parser
239         self.parent = parent
240         self.start = start
241         self.count = count
242         self.label = label
243         self.size = 0
244         self.length = 0
245         self.fields = []
246
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
250         if self.length > 0:
251             assert(self.length >= calculated)
252         else:
253             self.length = calculated
254         return self.length
255
256
257     def emit_template_struct(self, dim):
258         if self.count == 0:
259             print("   /* variable length fields follow */")
260         else:
261             if self.count > 1:
262                 dim = "%s[%d]" % (dim, self.count)
263
264             if len(self.fields) == 0:
265                 print("   int dummy;")
266
267             for field in self.fields:
268                 field.emit_template_struct(dim)
269
270     class Word:
271         def __init__(self):
272             self.size = 32
273             self.contributors = []
274
275     class FieldRef:
276         def __init__(self, field, path, start, end):
277             self.field = field
278             self.path = path
279             self.start = start
280             self.end = end
281
282     def collect_fields(self, fields, offset, path, all_fields):
283         for field in fields:
284             field_path = '{}{}'.format(path, field.name)
285             field_offset = offset + field.start
286
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)
290                 continue
291
292             start = field_offset
293             end = offset + field.end
294             all_fields.append(self.FieldRef(field, field_path, start, end))
295
296     def collect_words(self, fields, offset, path, words):
297         for field in fields:
298             field_path = '{}{}'.format(path, field.name)
299             start = offset + field.start
300
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)
304                 continue
305
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):
311                 if not b in words:
312                     words[b] = self.Word()
313                 words[b].contributors.append(contributor)
314
315     def emit_pack_function(self):
316         self.get_length()
317
318         words = {}
319         self.collect_words(self.fields, 0, '', words)
320
321         # Validate the modifier is lossless
322         for field in self.fields:
323             if field.modifier is None:
324                 continue
325
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))
334
335         for index in range(math.ceil(self.length / 4)):
336             # Handle MBZ words
337             if not index in words:
338                 print("   cl[%2d] = 0;" % index)
339                 continue
340
341             word = words[index]
342
343             word_start = index * 32
344
345             v = None
346             prefix = "   cl[%2d] =" % index
347
348             for contributor in word.contributors:
349                 field = contributor.field
350                 name = field.name
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
356
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)
367
368                 if field.type in ["uint", "hex", "address"]:
369                     s = "util_bitpack_uint(%s, %d, %d)" % \
370                         (value, start, end)
371                 elif field.type in self.parser.enums:
372                     s = "util_bitpack_uint(%s, %d, %d)" % \
373                         (value, start, end)
374                 elif field.type == "int":
375                     s = "util_bitpack_sint(%s, %d, %d)" % \
376                         (value, start, end)
377                 elif field.type == "bool":
378                     s = "util_bitpack_uint(%s, %d, %d)" % \
379                         (value, start, end)
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)
386                 else:
387                     s = "#error unhandled field {}, type {}".format(contributor.path, field.type)
388
389                 if not s == None:
390                     shift = word_start - contrib_word_start
391                     if shift:
392                         s = "%s >> %d" % (s, shift)
393
394                     if contributor == word.contributors[-1]:
395                         print("%s %s;" % (prefix, s))
396                     else:
397                         print("%s %s |" % (prefix, s))
398                     prefix = "           "
399
400             continue
401
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)
413
414     def emit_unpack_function(self):
415         # First, verify there is no garbage in unused bits
416         words = {}
417         self.collect_words(self.fields, 0, '', words)
418
419         for index in range(self.length // 4):
420             base = index * 32
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)
424
425             ALL_ONES = 0xffffffff
426
427             if mask != ALL_ONES:
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)))
430
431         fieldrefs = []
432         self.collect_fields(self.fields, 0, '', fieldrefs)
433         for fieldref in fieldrefs:
434             field = fieldref.field
435             convert = None
436
437             args = []
438             args.append('cl')
439             args.append(str(fieldref.start))
440             args.append(str(fieldref.end))
441
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"
452             else:
453                 s = "/* unhandled field %s, type %s */\n" % (field.name, field.type)
454
455             suffix = ""
456             prefix = ""
457             if field.modifier:
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":
463                     prefix = "1 << "
464
465             if field.type in self.parser.enums:
466                 prefix = f"(enum {enum_name(field.type)}) {prefix}"
467
468             decoded = '{}{}({}){}'.format(prefix, convert, ', '.join(args), suffix)
469
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))
474
475     def emit_print_function(self):
476         for field in self.fields:
477             convert = None
478             name, val = field.human_name, 'values->{}'.format(field.name)
479
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))
490                 print('    else')
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))
502             else:
503                 print('   fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name, val))
504
505 class Value(object):
506     def __init__(self, attrs):
507         self.name = attrs["name"]
508         self.value = int(attrs["value"], 0)
509
510 class Parser(object):
511     def __init__(self):
512         self.parser = xml.parsers.expat.ParserCreate()
513         self.parser.StartElementHandler = self.start_element
514         self.parser.EndElementHandler = self.end_element
515
516         self.struct = None
517         self.structs = {}
518         # Set of enum names we've seen.
519         self.enums = set()
520
521     def gen_prefix(self, name):
522         return '{}_{}'.format(global_prefix.upper(), name)
523
524     def start_element(self, name, attrs):
525         if name == "genxml":
526             print(pack_header)
527         elif name == "struct":
528             name = attrs["name"]
529             object_name = self.gen_prefix(safe_name(name.upper()))
530             self.struct = object_name
531
532             self.group = Group(self, None, 0, 1, name)
533             if "size" in attrs:
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))
539             self.values = []
540         elif name == "enum":
541             self.values = []
542             self.enum = safe_name(attrs["name"])
543             self.enums.add(attrs["name"])
544             if "prefix" in attrs:
545                 self.prefix = attrs["prefix"]
546             else:
547                 self.prefix= None
548         elif name == "value":
549             self.values.append(Value(attrs))
550
551     def end_element(self, name):
552         if name == "struct":
553             self.emit_struct()
554             self.struct = None
555             self.group = None
556         elif name  == "field":
557             self.group.fields[-1].values = self.values
558         elif name  == "enum":
559             self.emit_enum()
560             self.enum = None
561         elif name == "genxml":
562             print('#endif')
563
564     def emit_header(self, name):
565         default_fields = []
566         for field in self.group.fields:
567             if not type(field) is Field:
568                 continue
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()))))
573
574         print('#define %-40s\\' % (name + '_header'))
575         if default_fields:
576             print(",  \\\n".join(default_fields))
577         else:
578             print('   0')
579         print('')
580
581     def emit_template_struct(self, name, group):
582         print("struct %s {" % name)
583         group.emit_template_struct("")
584         print("};\n")
585
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))
589
590         group.emit_pack_function()
591
592         print("}\n\n")
593
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))
598
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))
603
604         group.emit_unpack_function()
605
606         print("}\n")
607
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))
611
612         group.emit_print_function()
613
614         print("}\n")
615
616     def emit_struct(self):
617         name = self.struct
618
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)
624
625     def enum_prefix(self, name):
626         return 
627
628     def emit_enum(self):
629         e_name = enum_name(self.enum)
630         prefix = e_name if self.enum != 'Format' else global_prefix
631         print('enum {} {{'.format(e_name))
632
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))
637         print('};\n')
638
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;')
647         print("    }")
648         print("    return NULL;")
649         print("}\n")
650
651     def parse(self, filename):
652         file = open(filename, "rb")
653         self.parser.ParseFile(file)
654         file.close()
655
656 if len(sys.argv) < 2:
657     print("No input xml file specified")
658     sys.exit(1)
659
660 input_file = sys.argv[1]
661
662 p = Parser()
663 p.parse(input_file)