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