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