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
29 from functools
import reduce
31 global_prefix
= "mali"
34 /* Generated code, see midgard.xml and gen_pack_header.py
36 * Packets, enums and structures for Panfrost.
38 * This file has been generated, do not hand edit.
50 #include "util/u_math.h"
52 #define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
54 static inline uint64_t
55 __gen_uint(uint64_t v, uint32_t start, uint32_t end)
58 const int width = end - start + 1;
60 const uint64_t max = (1ull << width) - 1;
68 static inline uint32_t
69 __gen_sint(int32_t v, uint32_t start, uint32_t end)
72 const int width = end - start + 1;
74 const int64_t max = (1ll << (width - 1)) - 1;
75 const int64_t min = -(1ll << (width - 1));
76 assert(min <= v && v <= max);
80 return ((uint32_t) v) << start;
83 static inline uint32_t
84 __gen_padded(uint32_t v, uint32_t start, uint32_t end)
86 unsigned shift = __builtin_ctz(v);
87 unsigned odd = v >> (shift + 1);
90 assert((v >> shift) & 1);
93 assert((end - start + 1) == 8);
96 return __gen_uint(shift | (odd << 5), start, end);
100 static inline uint64_t
101 __gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
104 const int width = end - start + 1;
105 const uint32_t mask = (width == 32 ? ~0 : (1 << width) - 1 );
107 for (int byte = start / 8; byte <= end / 8; byte++) {
108 val |= cl[byte] << ((byte - start / 8) * 8);
111 return (val >> (start % 8)) & mask;
114 static inline uint64_t
115 __gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
117 int size = end - start + 1;
118 int64_t val = __gen_unpack_uint(cl, start, end);
120 /* Get the sign bit extended. */
121 return (val << (64 - size)) >> (64 - size);
124 static inline uint64_t
125 __gen_unpack_padded(const uint8_t *restrict cl, uint32_t start, uint32_t end)
127 unsigned val = __gen_unpack_uint(cl, start, end);
128 unsigned shift = val & 0b11111;
129 unsigned odd = val >> 5;
131 return (2*odd + 1) << shift;
134 #define pan_pack(dst, T, name) \
135 for (struct MALI_ ## T name = { MALI_ ## T ## _header }, \
136 *_loop_terminate = (void *) (dst); \
137 __builtin_expect(_loop_terminate != NULL, 1); \
138 ({ MALI_ ## T ## _pack((uint32_t *) (dst), &name); \
139 _loop_terminate = NULL; }))
143 def to_alphanum(name
):
165 for i
, j
in substitutions
.items():
166 name
= name
.replace(i
, j
)
171 name
= to_alphanum(name
)
172 if not name
[0].isalpha():
177 def prefixed_upper_name(prefix
, name
):
179 name
= prefix
+ "_" + name
180 return safe_name(name
).upper()
183 return "{}_{}".format(global_prefix
, safe_name(name
)).lower()
185 def num_from_str(num_str
):
186 if num_str
.lower().startswith('0x'):
187 return int(num_str
, base
=16)
189 assert(not num_str
.startswith('0') and 'octals numbers not allowed')
192 MODIFIERS
= ["shr", "minus"]
194 def parse_modifier(modifier
):
198 for mod
in MODIFIERS
:
199 if modifier
[0:len(mod
)] == mod
and modifier
[len(mod
)] == '(' and modifier
[-1] == ')':
200 return [mod
, int(modifier
[(len(mod
) + 1):-1])]
202 print("Invalid modifier")
206 def __init__(self
, parser
, attrs
):
209 self
.name
= safe_name(attrs
["name"]).lower()
210 self
.human_name
= attrs
["name"]
212 if ":" in str(attrs
["start"]):
213 (word
, bit
) = attrs
["start"].split(":")
214 self
.start
= (int(word
) * 32) + int(bit
)
216 self
.start
= int(attrs
["start"])
218 self
.end
= self
.start
+ int(attrs
["size"]) - 1
219 self
.type = attrs
["type"]
221 if self
.type == 'bool' and self
.start
!= self
.end
:
222 print("#error Field {} has bool type but more than one bit of size".format(self
.name
));
224 if "prefix" in attrs
:
225 self
.prefix
= safe_name(attrs
["prefix"]).upper()
230 self
.exact
= int(attrs
["exact"])
234 self
.default
= attrs
.get("default")
237 if self
.type in self
.parser
.enums
and self
.default
is not None:
238 self
.default
= safe_name('{}_{}_{}'.format(global_prefix
, self
.type, self
.default
)).upper()
240 self
.modifier
= parse_modifier(attrs
.get("modifier"))
242 def emit_template_struct(self
, dim
, opaque_structs
):
243 if self
.type == 'address':
245 elif self
.type == 'bool':
247 elif self
.type == 'float':
249 elif self
.type == 'uint' and self
.end
- self
.start
> 32:
251 elif self
.type == 'int':
253 elif self
.type in ['uint', 'padded']:
255 elif self
.type in self
.parser
.structs
:
256 type = 'struct ' + self
.parser
.gen_prefix(safe_name(self
.type.upper()))
259 type = type.lower() + '_packed'
260 elif self
.type in self
.parser
.enums
:
261 type = 'enum ' + enum_name(self
.type)
263 print("#error unhandled type: %s" % self
.type)
266 print(" %-36s %s%s;" % (type, self
.name
, dim
))
268 for value
in self
.values
:
269 name
= prefixed_upper_name(self
.prefix
, value
.name
)
270 print("#define %-40s %d" % (name
, value
.value
))
272 def overlaps(self
, field
):
273 return self
!= field
and max(self
.start
, field
.start
) <= min(self
.end
, field
.end
)
277 def __init__(self
, parser
, parent
, start
, count
):
286 def emit_template_struct(self
, dim
, opaque_structs
):
288 print(" /* variable length fields follow */")
291 dim
= "%s[%d]" % (dim
, self
.count
)
293 for field
in self
.fields
:
294 if field
.exact
is not None:
297 field
.emit_template_struct(dim
, opaque_structs
)
304 def collect_words(self
, words
):
305 for field
in self
.fields
:
306 first_word
= field
.start
// 32
307 last_word
= field
.end
// 32
309 for b
in range(first_word
, last_word
+ 1):
311 words
[b
] = self
.Word()
313 words
[b
].fields
.append(field
)
315 def emit_pack_function(self
, opaque_structs
):
316 # Determine number of bytes in this group.
317 calculated
= max(field
.end
// 8 for field
in self
.fields
) + 1
320 assert(self
.length
>= calculated
)
322 self
.length
= calculated
325 self
.collect_words(words
)
327 emitted_structs
= set()
329 # Validate the modifier is lossless
330 for field
in self
.fields
:
331 if field
.modifier
is None:
334 assert(field
.exact
is None)
336 if field
.modifier
[0] == "shr":
337 shift
= field
.modifier
[1]
338 mask
= hex((1 << shift
) - 1)
339 print(" assert((values->{} & {}) == 0);".format(field
.name
, mask
))
340 elif field
.modifier
[0] == "minus":
341 print(" assert(values->{} >= {});".format(field
.name
, field
.modifier
[1]))
343 for index
in range(self
.length
// 4):
345 if not index
in words
:
346 print(" cl[%2d] = 0;" % index
)
351 word_start
= index
* 32
354 prefix
= " cl[%2d] =" % index
356 first
= word
.fields
[0]
357 if first
.type in self
.parser
.structs
and first
.start
not in emitted_structs
:
358 pack_name
= self
.parser
.gen_prefix(safe_name(first
.type.upper()))
360 assert((first
.start
% 32) == 0)
361 assert(first
.end
== first
.start
+ (self
.parser
.structs
[first
.type].length
* 8) - 1)
362 emitted_structs
.add(first
.start
)
365 print(" memcpy(cl + {}, &values->{}, {});".format(first
.start
// 32, first
.name
, (first
.end
- first
.start
+ 1) // 8))
367 print(" {}_pack(cl + {}, &values->{});".format(pack_name
, first
.start
// 32, first
.name
))
369 for field
in word
.fields
:
373 field_word_start
= (field
.start
// 32) * 32
374 start
-= field_word_start
375 end
-= field_word_start
377 value
= str(field
.exact
) if field
.exact
is not None else "values->%s" % name
378 if field
.modifier
is not None:
379 if field
.modifier
[0] == "shr":
380 value
= "{} >> {}".format(value
, field
.modifier
[1])
381 elif field
.modifier
[0] == "minus":
382 value
= "{} - {}".format(value
, field
.modifier
[1])
384 if field
.type == "uint" or field
.type == "address":
385 s
= "__gen_uint(%s, %d, %d)" % \
387 elif field
.type == "padded":
388 s
= "__gen_padded(%s, %d, %d)" % \
390 elif field
.type in self
.parser
.enums
:
391 s
= "__gen_uint(%s, %d, %d)" % \
393 elif field
.type == "int":
394 s
= "__gen_sint(%s, %d, %d)" % \
396 elif field
.type == "bool":
397 s
= "__gen_uint(%s, %d, %d)" % \
399 elif field
.type == "float":
400 assert(start
== 0 and end
== 31)
401 s
= "__gen_uint(fui({}), 0, 32)".format(value
)
402 elif field
.type in self
.parser
.structs
:
403 # Structs are packed directly
404 assert(len(word
.fields
) == 1)
407 s
= "#error unhandled field {}, type {}".format(name
, field
.type)
410 shift
= word_start
- field_word_start
412 s
= "%s >> %d" % (s
, shift
)
414 if field
== word
.fields
[-1]:
415 print("%s %s;" % (prefix
, s
))
417 print("%s %s |" % (prefix
, s
))
422 # Given a field (start, end) contained in word `index`, generate the 32-bit
423 # mask of present bits relative to the word
424 def mask_for_word(self
, index
, start
, end
):
425 field_word_start
= index
* 32
426 start
-= field_word_start
427 end
-= field_word_start
428 # Cap multiword at one word
429 start
= max(start
, 0)
430 end
= min(end
, 32 - 1)
431 count
= (end
- start
+ 1)
432 return (((1 << count
) - 1) << start
)
434 def emit_unpack_function(self
):
435 # First, verify there is no garbage in unused bits
437 self
.collect_words(words
)
439 for index
in range(self
.length
// 4):
441 word
= words
.get(index
, self
.Word())
442 masks
= [self
.mask_for_word(index
, f
.start
, f
.end
) for f
in word
.fields
]
443 mask
= reduce(lambda x
,y
: x | y
, masks
, 0)
445 ALL_ONES
= 0xffffffff
448 TMPL
= ' if (((const uint32_t *) cl)[{}] & {}) fprintf(stderr, "XXX: Invalid field unpacked at word {}\\n");'
449 print(TMPL
.format(index
, hex(mask ^ ALL_ONES
), index
))
451 for field
in self
.fields
:
452 # Recurse for structs, see pack() for validation
453 if field
.type in self
.parser
.structs
:
454 pack_name
= self
.parser
.gen_prefix(safe_name(field
.type)).upper()
455 print(" {}_unpack(cl + {}, &values->{});".format(pack_name
, field
.start
// 8, field
.name
))
462 args
.append(str(field
.start
))
463 args
.append(str(field
.end
))
465 if field
.type in set(["uint", "address"]) | self
.parser
.enums
:
466 convert
= "__gen_unpack_uint"
467 elif field
.type == "int":
468 convert
= "__gen_unpack_sint"
469 elif field
.type == "padded":
470 convert
= "__gen_unpack_padded"
471 elif field
.type == "bool":
472 convert
= "__gen_unpack_uint"
473 elif field
.type == "float":
474 convert
= "__gen_unpack_float"
476 s
= "/* unhandled field %s, type %s */\n" % (field
.name
, field
.type)
480 if field
.modifier
[0] == "minus":
481 suffix
= " + {}".format(field
.modifier
[1])
482 elif field
.modifier
[0] == "shr":
483 suffix
= " << {}".format(field
.modifier
[1])
485 decoded
= '{}({}){}'.format(convert
, ', '.join(args
), suffix
)
487 print(' values->{} = {};'.format(field
.name
, decoded
))
489 def emit_print_function(self
):
490 for field
in self
.fields
:
492 name
, val
= field
.human_name
, 'values->{}'.format(field
.name
)
494 if field
.type in self
.parser
.structs
:
495 pack_name
= self
.parser
.gen_prefix(safe_name(field
.type)).upper()
496 print(' fprintf(fp, "%*s{}:\\n", indent, "");'.format(field
.human_name
))
497 print(" {}_print(fp, &values->{}, indent + 2);".format(pack_name
, field
.name
))
498 elif field
.type == "address":
499 # TODO resolve to name
500 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name
, val
))
501 elif field
.type in self
.parser
.enums
:
502 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name
, enum_name(field
.type), val
))
503 elif field
.type == "int":
504 print(' fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name
, val
))
505 elif field
.type == "bool":
506 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name
, val
))
507 elif field
.type == "float":
508 print(' fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name
, val
))
509 elif field
.type == "uint" and (field
.end
- field
.start
) >= 32:
510 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name
, val
))
512 print(' fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name
, val
))
515 def __init__(self
, attrs
):
516 self
.name
= attrs
["name"]
517 self
.value
= int(attrs
["value"])
519 class Parser(object):
521 self
.parser
= xml
.parsers
.expat
.ParserCreate()
522 self
.parser
.StartElementHandler
= self
.start_element
523 self
.parser
.EndElementHandler
= self
.end_element
527 # Set of enum names we've seen.
530 def gen_prefix(self
, name
):
531 return '{}_{}'.format(global_prefix
.upper(), name
)
533 def start_element(self
, name
, attrs
):
536 elif name
== "struct":
538 self
.with_opaque
= attrs
.get("with_opaque", False)
540 object_name
= self
.gen_prefix(safe_name(name
.upper()))
541 self
.struct
= object_name
543 self
.group
= Group(self
, None, 0, 1)
545 self
.group
.length
= int(attrs
["size"]) * 4
546 self
.structs
[attrs
["name"]] = self
.group
547 elif name
== "field":
548 self
.group
.fields
.append(Field(self
, attrs
))
552 self
.enum
= safe_name(attrs
["name"])
553 self
.enums
.add(attrs
["name"])
554 if "prefix" in attrs
:
555 self
.prefix
= attrs
["prefix"]
558 elif name
== "value":
559 self
.values
.append(Value(attrs
))
561 def end_element(self
, name
):
566 elif name
== "field":
567 self
.group
.fields
[-1].values
= self
.values
571 elif name
== "panxml":
572 # Include at the end so it can depend on us but not the converse
573 print('#include "panfrost-job.h"')
576 def emit_header(self
, name
):
578 for field
in self
.group
.fields
:
579 if not type(field
) is Field
:
581 if field
.default
is not None:
582 default_fields
.append(" .{} = {}".format(field
.name
, field
.default
))
583 elif field
.type in self
.structs
:
584 default_fields
.append(" .{} = {{ {}_header }}".format(field
.name
, self
.gen_prefix(safe_name(field
.type.upper()))))
586 print('#define %-40s\\' % (name
+ '_header'))
588 print(", \\\n".join(default_fields
))
593 def emit_template_struct(self
, name
, group
, opaque_structs
):
594 print("struct %s {" % (name
+ ('_OPAQUE' if opaque_structs
else '')))
595 group
.emit_template_struct("", opaque_structs
)
599 # Just so it isn't left undefined
600 print('#define %-40s 0' % (name
+ '_OPAQUE_header'))
602 def emit_pack_function(self
, name
, group
, with_opaque
):
603 print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
604 (name
, ' ' * (len(name
) + 6), name
))
606 group
.emit_pack_function(False)
611 print("static inline void\n%s_OPAQUE_pack(uint32_t * restrict cl,\n%sconst struct %s_OPAQUE * restrict values)\n{" %
612 (name
, ' ' * (len(name
) + 6), name
))
614 group
.emit_pack_function(True)
618 # Should be a whole number of words
619 assert((self
.group
.length
% 4) == 0)
621 print('#define {} {}'.format (name
+ "_LENGTH", self
.group
.length
))
622 print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name
.lower(), self
.group
.length
// 4))
624 def emit_unpack_function(self
, name
, group
):
625 print("static inline void")
626 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
627 (name
.upper(), ' ' * (len(name
) + 8), name
))
629 group
.emit_unpack_function()
633 def emit_print_function(self
, name
, group
):
634 print("static inline void")
635 print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name
.upper(), name
))
637 group
.emit_print_function()
641 def emit_struct(self
):
644 self
.emit_template_struct(self
.struct
, self
.group
, False)
646 self
.emit_template_struct(self
.struct
, self
.group
, True)
647 self
.emit_header(name
)
648 self
.emit_pack_function(self
.struct
, self
.group
, self
.with_opaque
)
649 self
.emit_unpack_function(self
.struct
, self
.group
)
650 self
.emit_print_function(self
.struct
, self
.group
)
652 def enum_prefix(self
, name
):
656 e_name
= enum_name(self
.enum
)
657 prefix
= e_name
if self
.enum
!= 'Format' else global_prefix
658 print('enum {} {{'.format(e_name
))
660 for value
in self
.values
:
661 name
= '{}_{}'.format(prefix
, value
.name
)
662 name
= safe_name(name
).upper()
663 print(' % -36s = %6d,' % (name
, value
.value
))
666 print("static inline const char *")
667 print("{}_as_str(enum {} imm)\n{{".format(e_name
.lower(), e_name
))
668 print(" switch (imm) {")
669 for value
in self
.values
:
670 name
= '{}_{}'.format(prefix
, value
.name
)
671 name
= safe_name(name
).upper()
672 print(' case {}: return "{}";'.format(name
, value
.name
))
673 print(' default: return "XXX: INVALID";')
677 def parse(self
, filename
):
678 file = open(filename
, "rb")
679 self
.parser
.ParseFile(file)
682 if len(sys
.argv
) < 2:
683 print("No input xml file specified")
686 input_file
= sys
.argv
[1]