3 from __future__
import (
4 absolute_import
, division
, print_function
, unicode_literals
7 import xml
.parsers
.expat
14 * Copyright (C) 2016 Intel Corporation
16 * Permission is hereby granted, free of charge, to any person obtaining a
17 * copy of this software and associated documentation files (the "Software"),
18 * to deal in the Software without restriction, including without limitation
19 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
20 * and/or sell copies of the Software, and to permit persons to whom the
21 * Software is furnished to do so, subject to the following conditions:
23 * The above copyright notice and this permission notice (including the next
24 * paragraph) shall be included in all copies or substantial portions of the
27 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
30 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
32 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
37 pack_header
= """%(license)s
39 /* Instructions, enums and structures for %(platform)s.
41 * This file has been generated, do not hand edit.
53 #ifndef __gen_validate_value
54 #define __gen_validate_value(x)
57 #ifndef __gen_field_functions
58 #define __gen_field_functions
61 #define NDEBUG_UNUSED __attribute__((unused))
71 static inline uint64_t
72 __gen_mbo(uint32_t start, uint32_t end)
74 return (~0ull >> (64 - (end - start + 1))) << start;
77 static inline uint64_t
78 __gen_uint(uint64_t v, uint32_t start, NDEBUG_UNUSED uint32_t end)
80 __gen_validate_value(v);
83 const int width = end - start + 1;
85 const uint64_t max = (1ull << width) - 1;
93 static inline uint64_t
94 __gen_sint(int64_t v, uint32_t start, uint32_t end)
96 const int width = end - start + 1;
98 __gen_validate_value(v);
102 const int64_t max = (1ll << (width - 1)) - 1;
103 const int64_t min = -(1ll << (width - 1));
104 assert(min <= v && v <= max);
108 const uint64_t mask = ~0ull >> (64 - width);
110 return (v & mask) << start;
113 static inline uint64_t
114 __gen_offset(uint64_t v, NDEBUG_UNUSED uint32_t start, NDEBUG_UNUSED uint32_t end)
116 __gen_validate_value(v);
118 uint64_t mask = (~0ull >> (64 - (end - start + 1))) << start;
120 assert((v & ~mask) == 0);
126 static inline uint32_t
129 __gen_validate_value(v);
130 return ((union __gen_value) { .f = (v) }).dw;
133 static inline uint64_t
134 __gen_sfixed(float v, uint32_t start, uint32_t end, uint32_t fract_bits)
136 __gen_validate_value(v);
138 const float factor = (1 << fract_bits);
141 const float max = ((1 << (end - start)) - 1) / factor;
142 const float min = -(1 << (end - start)) / factor;
143 assert(min <= v && v <= max);
146 const int64_t int_val = llroundf(v * factor);
147 const uint64_t mask = ~0ull >> (64 - (end - start + 1));
149 return (int_val & mask) << start;
152 static inline uint64_t
153 __gen_ufixed(float v, uint32_t start, NDEBUG_UNUSED uint32_t end, uint32_t fract_bits)
155 __gen_validate_value(v);
157 const float factor = (1 << fract_bits);
160 const float max = ((1 << (end - start + 1)) - 1) / factor;
161 const float min = 0.0f;
162 assert(min <= v && v <= max);
165 const uint64_t uint_val = llroundf(v * factor);
167 return uint_val << start;
170 #ifndef __gen_address_type
171 #error #define __gen_address_type before including this file
174 #ifndef __gen_user_data
175 #error #define __gen_combine_address before including this file
184 def to_alphanum(name
):
207 for i
, j
in substitutions
.items():
208 name
= name
.replace(i
, j
)
213 name
= to_alphanum(name
)
214 if not name
[0].isalpha():
219 def num_from_str(num_str
):
220 if num_str
.lower().startswith('0x'):
221 return int(num_str
, base
=16)
223 assert(not num_str
.startswith('0') and 'octals numbers not allowed')
227 ufixed_pattern
= re
.compile(r
"u(\d+)\.(\d+)")
228 sfixed_pattern
= re
.compile(r
"s(\d+)\.(\d+)")
230 def __init__(self
, parser
, attrs
):
233 self
.name
= safe_name(attrs
["name"])
234 self
.start
= int(attrs
["start"])
235 self
.end
= int(attrs
["end"])
236 self
.type = attrs
["type"]
238 if "prefix" in attrs
:
239 self
.prefix
= attrs
["prefix"]
243 if "default" in attrs
:
244 self
.default
= int(attrs
["default"])
248 ufixed_match
= Field
.ufixed_pattern
.match(self
.type)
251 self
.fractional_size
= int(ufixed_match
.group(2))
253 sfixed_match
= Field
.sfixed_pattern
.match(self
.type)
256 self
.fractional_size
= int(sfixed_match
.group(2))
258 def is_builtin_type(self
):
259 builtins
= [ 'address', 'bool', 'float', 'ufixed',
260 'offset', 'sfixed', 'offset', 'int', 'uint', 'mbo' ]
261 return self
.type in builtins
263 def is_struct_type(self
):
264 return self
.type in self
.parser
.structs
266 def is_enum_type(self
):
267 return self
.type in self
.parser
.enums
269 def emit_template_struct(self
, dim
):
270 if self
.type == 'address':
271 type = '__gen_address_type'
272 elif self
.type == 'bool':
274 elif self
.type == 'float':
276 elif self
.type == 'ufixed':
278 elif self
.type == 'sfixed':
280 elif self
.type == 'uint' and self
.end
- self
.start
> 32:
282 elif self
.type == 'offset':
284 elif self
.type == 'int':
286 elif self
.type == 'uint':
288 elif self
.is_struct_type():
289 type = 'struct ' + self
.parser
.gen_prefix(safe_name(self
.type))
290 elif self
.is_enum_type():
291 type = 'enum ' + self
.parser
.gen_prefix(safe_name(self
.type))
292 elif self
.type == 'mbo':
295 print("#error unhandled type: %s" % self
.type)
298 print(" %-36s %s%s;" % (type, self
.name
, dim
))
301 if len(self
.values
) > 0 and self
.default
== None:
303 prefix
= self
.prefix
+ "_"
305 for value
in self
.values
:
306 print("#define %-40s %d" % (prefix
+ value
.name
, value
.value
))
309 def __init__(self
, parser
, parent
, start
, count
, size
):
317 def emit_template_struct(self
, dim
):
319 print(" /* variable length fields follow */")
322 dim
= "%s[%d]" % (dim
, self
.count
)
324 for field
in self
.fields
:
325 field
.emit_template_struct(dim
)
333 def collect_dwords(self
, dwords
, start
, dim
):
334 for field
in self
.fields
:
335 if type(field
) is Group
:
337 field
.collect_dwords(dwords
, start
+ field
.start
, dim
)
339 for i
in range(field
.count
):
340 field
.collect_dwords(dwords
,
341 start
+ field
.start
+ i
* field
.size
,
345 index
= (start
+ field
.start
) // 32
346 if not index
in dwords
:
347 dwords
[index
] = self
.DWord()
349 clone
= copy
.copy(field
)
350 clone
.start
= clone
.start
+ start
351 clone
.end
= clone
.end
+ start
353 dwords
[index
].fields
.append(clone
)
355 if field
.type == "address":
356 # assert dwords[index].address == None
357 dwords
[index
].address
= field
359 # Coalesce all the dwords covered by this field. The two cases we
360 # handle are where multiple fields are in a 64 bit word (typically
361 # and address and a few bits) or where a single struct field
362 # completely covers multiple dwords.
363 while index
< (start
+ field
.end
) // 32:
364 if index
+ 1 in dwords
and not dwords
[index
] == dwords
[index
+ 1]:
365 dwords
[index
].fields
.extend(dwords
[index
+ 1].fields
)
366 dwords
[index
].size
= 64
367 dwords
[index
+ 1] = dwords
[index
]
370 def collect_dwords_and_length(self
):
372 self
.collect_dwords(dwords
, 0, "")
374 # Determine number of dwords in this group. If we have a size, use
375 # that, since that'll account for MBZ dwords at the end of a group
376 # (like dword 8 on BDW+ 3DSTATE_HS). Otherwise, use the largest dword
377 # index we've seen plus one.
379 length
= self
.size
// 32
381 length
= max(dwords
.keys()) + 1
385 return (dwords
, length
)
387 def emit_pack_function(self
, dwords
, length
):
388 for index
in range(length
):
390 if not index
in dwords
:
392 print(" dw[%d] = 0;" % index
)
395 # For 64 bit dwords, we aliased the two dword entries in the dword
396 # dict it occupies. Now that we're emitting the pack function,
397 # skip the duplicate entries.
399 if index
> 0 and index
- 1 in dwords
and dw
== dwords
[index
- 1]:
402 # Special case: only one field and it's a struct at the beginning
403 # of the dword. In this case we pack directly into the
404 # destination. This is the only way we handle embedded structs
405 # larger than 32 bits.
406 if len(dw
.fields
) == 1:
408 name
= field
.name
+ field
.dim
409 if field
.is_struct_type() and field
.start
% 32 == 0:
411 print(" %s_pack(data, &dw[%d], &values->%s);" %
412 (self
.parser
.gen_prefix(safe_name(field
.type)), index
, name
))
415 # Pack any fields of struct type first so we have integer values
416 # to the dword for those fields.
418 for field
in dw
.fields
:
419 if type(field
) is Field
and field
.is_struct_type():
420 name
= field
.name
+ field
.dim
422 print(" uint32_t v%d_%d;" % (index
, field_index
))
423 print(" %s_pack(data, &v%d_%d, &values->%s);" %
424 (self
.parser
.gen_prefix(safe_name(field
.type)), index
, field_index
, name
))
425 field_index
= field_index
+ 1
428 dword_start
= index
* 32
429 if dw
.address
== None:
434 if dw
.size
== 32 and dw
.address
== None:
436 print(" dw[%d] =" % index
)
437 elif len(dw
.fields
) > address_count
:
439 print(" const uint%d_t %s =" % (dw
.size
, v
))
444 non_address_fields
= []
445 for field
in dw
.fields
:
446 if field
.type != "mbo":
447 name
= field
.name
+ field
.dim
449 if field
.type == "mbo":
450 non_address_fields
.append("__gen_mbo(%d, %d)" % \
451 (field
.start
- dword_start
, field
.end
- dword_start
))
452 elif field
.type == "address":
454 elif field
.type == "uint":
455 non_address_fields
.append("__gen_uint(values->%s, %d, %d)" % \
456 (name
, field
.start
- dword_start
, field
.end
- dword_start
))
457 elif field
.is_enum_type():
458 non_address_fields
.append("__gen_uint(values->%s, %d, %d)" % \
459 (name
, field
.start
- dword_start
, field
.end
- dword_start
))
460 elif field
.type == "int":
461 non_address_fields
.append("__gen_sint(values->%s, %d, %d)" % \
462 (name
, field
.start
- dword_start
, field
.end
- dword_start
))
463 elif field
.type == "bool":
464 non_address_fields
.append("__gen_uint(values->%s, %d, %d)" % \
465 (name
, field
.start
- dword_start
, field
.end
- dword_start
))
466 elif field
.type == "float":
467 non_address_fields
.append("__gen_float(values->%s)" % name
)
468 elif field
.type == "offset":
469 non_address_fields
.append("__gen_offset(values->%s, %d, %d)" % \
470 (name
, field
.start
- dword_start
, field
.end
- dword_start
))
471 elif field
.type == 'ufixed':
472 non_address_fields
.append("__gen_ufixed(values->%s, %d, %d, %d)" % \
473 (name
, field
.start
- dword_start
, field
.end
- dword_start
, field
.fractional_size
))
474 elif field
.type == 'sfixed':
475 non_address_fields
.append("__gen_sfixed(values->%s, %d, %d, %d)" % \
476 (name
, field
.start
- dword_start
, field
.end
- dword_start
, field
.fractional_size
))
477 elif field
.is_struct_type():
478 non_address_fields
.append("__gen_uint(v%d_%d, %d, %d)" % \
479 (index
, field_index
, field
.start
- dword_start
, field
.end
- dword_start
))
480 field_index
= field_index
+ 1
482 non_address_fields
.append("/* unhandled field %s, type %s */\n" % \
485 if len(non_address_fields
) > 0:
486 print(" |\n".join(" " + f
for f
in non_address_fields
) + ";")
490 print(" dw[%d] = __gen_combine_address(data, &dw[%d], values->%s, %s);" % (index
, index
, dw
.address
.name
+ field
.dim
, v
))
494 v_address
= "v%d_address" % index
495 print(" const uint64_t %s =\n __gen_combine_address(data, &dw[%d], values->%s, %s);" %
496 (v_address
, index
, dw
.address
.name
+ field
.dim
, v
))
499 print(" dw[%d] = %s;" % (index
, v
))
500 print(" dw[%d] = %s >> 32;" % (index
+ 1, v
))
503 def __init__(self
, attrs
):
504 self
.name
= safe_name(attrs
["name"])
505 self
.value
= ast
.literal_eval(attrs
["value"])
507 class Parser(object):
509 self
.parser
= xml
.parsers
.expat
.ParserCreate()
510 self
.parser
.StartElementHandler
= self
.start_element
511 self
.parser
.EndElementHandler
= self
.end_element
513 self
.instruction
= None
515 # Set of enum names we've seen.
519 def gen_prefix(self
, name
):
521 return 'GEN%s%s' % (self
.gen
, name
)
523 return 'GEN%s_%s' % (self
.gen
, name
)
526 return self
.gen_prefix("PACK_H")
528 def start_element(self
, name
, attrs
):
530 self
.platform
= attrs
["name"]
531 self
.gen
= attrs
["gen"].replace('.', '')
532 print(pack_header
% {'license': license
, 'platform': self
.platform
, 'guard': self
.gen_guard()})
533 elif name
in ("instruction", "struct", "register"):
534 if name
== "instruction":
535 self
.instruction
= safe_name(attrs
["name"])
536 self
.length_bias
= int(attrs
["bias"])
537 elif name
== "struct":
538 self
.struct
= safe_name(attrs
["name"])
539 self
.structs
[attrs
["name"]] = 1
540 elif name
== "register":
541 self
.register
= safe_name(attrs
["name"])
542 self
.reg_num
= num_from_str(attrs
["num"])
543 self
.registers
[attrs
["name"]] = 1
544 if "length" in attrs
:
545 self
.length
= int(attrs
["length"])
546 size
= self
.length
* 32
550 self
.group
= Group(self
, None, 0, 1, size
)
552 elif name
== "group":
553 group
= Group(self
, self
.group
,
554 int(attrs
["start"]), int(attrs
["count"]), int(attrs
["size"]))
555 self
.group
.fields
.append(group
)
557 elif name
== "field":
558 self
.group
.fields
.append(Field(self
, attrs
))
562 self
.enum
= safe_name(attrs
["name"])
563 self
.enums
.add(attrs
["name"])
564 if "prefix" in attrs
:
565 self
.prefix
= safe_name(attrs
["prefix"])
568 elif name
== "value":
569 self
.values
.append(Value(attrs
))
571 def end_element(self
, name
):
572 if name
== "instruction":
573 self
.emit_instruction()
574 self
.instruction
= None
576 elif name
== "struct":
580 elif name
== "register":
585 elif name
== "group":
586 self
.group
= self
.group
.parent
587 elif name
== "field":
588 self
.group
.fields
[-1].values
= self
.values
592 elif name
== "genxml":
593 print('#endif /* %s */' % self
.gen_guard())
595 def emit_template_struct(self
, name
, group
):
596 print("struct %s {" % self
.gen_prefix(name
))
597 group
.emit_template_struct("")
600 def emit_pack_function(self
, name
, group
):
601 name
= self
.gen_prefix(name
)
602 print(textwrap
.dedent("""\
604 %s_pack(__attribute__((unused)) __gen_user_data *data,
605 %s__attribute__((unused)) void * restrict dst,
606 %s__attribute__((unused)) const struct %s * restrict values)
607 {""") % (name
, ' ' * len(name
), ' ' * len(name
), name
))
609 (dwords
, length
) = group
.collect_dwords_and_length()
611 # Cast dst to make header C++ friendly
612 print(" uint32_t * restrict dw = (uint32_t * restrict) dst;")
614 group
.emit_pack_function(dwords
, length
)
618 def emit_instruction(self
):
619 name
= self
.instruction
620 if not self
.length
== None:
621 print('#define %-33s %6d' %
622 (self
.gen_prefix(name
+ "_length"), self
.length
))
623 print('#define %-33s %6d' %
624 (self
.gen_prefix(name
+ "_length_bias"), self
.length_bias
))
627 for field
in self
.group
.fields
:
628 if not type(field
) is Field
:
630 if field
.default
== None:
632 default_fields
.append(" .%-35s = %6d" % (field
.name
, field
.default
))
635 print('#define %-40s\\' % (self
.gen_prefix(name
+ '_header')))
636 print(", \\\n".join(default_fields
))
639 self
.emit_template_struct(self
.instruction
, self
.group
)
641 self
.emit_pack_function(self
.instruction
, self
.group
)
643 def emit_register(self
):
645 if not self
.reg_num
== None:
646 print('#define %-33s 0x%04x' %
647 (self
.gen_prefix(name
+ "_num"), self
.reg_num
))
649 if not self
.length
== None:
650 print('#define %-33s %6d' %
651 (self
.gen_prefix(name
+ "_length"), self
.length
))
653 self
.emit_template_struct(self
.register
, self
.group
)
654 self
.emit_pack_function(self
.register
, self
.group
)
656 def emit_struct(self
):
658 if not self
.length
== None:
659 print('#define %-33s %6d' %
660 (self
.gen_prefix(name
+ "_length"), self
.length
))
662 self
.emit_template_struct(self
.struct
, self
.group
)
663 self
.emit_pack_function(self
.struct
, self
.group
)
666 print('enum %s {' % self
.gen_prefix(self
.enum
))
667 for value
in self
.values
:
669 name
= self
.prefix
+ "_" + value
.name
672 print(' %-36s = %6d,' % (name
.upper(), value
.value
))
675 def parse(self
, filename
):
676 file = open(filename
, "rb")
677 self
.parser
.ParseFile(file)
680 if len(sys
.argv
) < 2:
681 print("No input xml file specified")
684 input_file
= sys
.argv
[1]