3 from __future__
import (
4 absolute_import
, division
, print_function
, unicode_literals
8 import xml
.parsers
.expat
15 * Copyright (C) 2016 Intel Corporation
17 * Permission is hereby granted, free of charge, to any person obtaining a
18 * copy of this software and associated documentation files (the "Software"),
19 * to deal in the Software without restriction, including without limitation
20 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
21 * and/or sell copies of the Software, and to permit persons to whom the
22 * Software is furnished to do so, subject to the following conditions:
24 * The above copyright notice and this permission notice (including the next
25 * paragraph) shall be included in all copies or substantial portions of the
28 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
31 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
33 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
38 pack_header
= """%(license)s
40 /* Instructions, enums and structures for %(platform)s.
42 * This file has been generated, do not hand edit.
54 #ifndef __gen_validate_value
55 #define __gen_validate_value(x)
58 #ifndef __gen_field_functions
59 #define __gen_field_functions
62 #define NDEBUG_UNUSED __attribute__((unused))
72 static inline uint64_t
73 __gen_mbo(uint32_t start, uint32_t end)
75 return (~0ull >> (64 - (end - start + 1))) << start;
78 static inline uint64_t
79 __gen_uint(uint64_t v, uint32_t start, NDEBUG_UNUSED uint32_t end)
81 __gen_validate_value(v);
84 const int width = end - start + 1;
86 const uint64_t max = (1ull << width) - 1;
94 static inline uint64_t
95 __gen_sint(int64_t v, uint32_t start, uint32_t end)
97 const int width = end - start + 1;
99 __gen_validate_value(v);
103 const int64_t max = (1ll << (width - 1)) - 1;
104 const int64_t min = -(1ll << (width - 1));
105 assert(min <= v && v <= max);
109 const uint64_t mask = ~0ull >> (64 - width);
111 return (v & mask) << start;
114 static inline uint64_t
115 __gen_offset(uint64_t v, NDEBUG_UNUSED uint32_t start, NDEBUG_UNUSED uint32_t end)
117 __gen_validate_value(v);
119 uint64_t mask = (~0ull >> (64 - (end - start + 1))) << start;
121 assert((v & ~mask) == 0);
127 static inline uint32_t
130 __gen_validate_value(v);
131 return ((union __gen_value) { .f = (v) }).dw;
134 static inline uint64_t
135 __gen_sfixed(float v, uint32_t start, uint32_t end, uint32_t fract_bits)
137 __gen_validate_value(v);
139 const float factor = (1 << fract_bits);
142 const float max = ((1 << (end - start)) - 1) / factor;
143 const float min = -(1 << (end - start)) / factor;
144 assert(min <= v && v <= max);
147 const int64_t int_val = llroundf(v * factor);
148 const uint64_t mask = ~0ull >> (64 - (end - start + 1));
150 return (int_val & mask) << start;
153 static inline uint64_t
154 __gen_ufixed(float v, uint32_t start, NDEBUG_UNUSED uint32_t end, uint32_t fract_bits)
156 __gen_validate_value(v);
158 const float factor = (1 << fract_bits);
161 const float max = ((1 << (end - start + 1)) - 1) / factor;
162 const float min = 0.0f;
163 assert(min <= v && v <= max);
166 const uint64_t uint_val = llroundf(v * factor);
168 return uint_val << start;
171 #ifndef __gen_address_type
172 #error #define __gen_address_type before including this file
175 #ifndef __gen_user_data
176 #error #define __gen_combine_address before including this file
185 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'), '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 assert self
.start
<= self
.end
, \
239 'field {} has end ({}) < start ({})'.format(self
.name
, self
.end
,
241 if self
.type == 'bool':
242 assert self
.end
== self
.start
, \
243 'bool field ({}) is too wide'.format(self
.name
)
245 if "prefix" in attrs
:
246 self
.prefix
= attrs
["prefix"]
250 if "default" in attrs
:
251 # Base 0 recognizes 0x, 0o, 0b prefixes in addition to decimal ints.
252 self
.default
= int(attrs
["default"], base
=0)
256 ufixed_match
= Field
.ufixed_pattern
.match(self
.type)
259 self
.fractional_size
= int(ufixed_match
.group(2))
261 sfixed_match
= Field
.sfixed_pattern
.match(self
.type)
264 self
.fractional_size
= int(sfixed_match
.group(2))
266 def is_builtin_type(self
):
267 builtins
= [ 'address', 'bool', 'float', 'ufixed',
268 'offset', 'sfixed', 'offset', 'int', 'uint', 'mbo' ]
269 return self
.type in builtins
271 def is_struct_type(self
):
272 return self
.type in self
.parser
.structs
274 def is_enum_type(self
):
275 return self
.type in self
.parser
.enums
277 def emit_template_struct(self
, dim
):
278 if self
.type == 'address':
279 type = '__gen_address_type'
280 elif self
.type == 'bool':
282 elif self
.type == 'float':
284 elif self
.type == 'ufixed':
286 elif self
.type == 'sfixed':
288 elif self
.type == 'uint' and self
.end
- self
.start
> 32:
290 elif self
.type == 'offset':
292 elif self
.type == 'int':
294 elif self
.type == 'uint':
296 elif self
.is_struct_type():
297 type = 'struct ' + self
.parser
.gen_prefix(safe_name(self
.type))
298 elif self
.is_enum_type():
299 type = 'enum ' + self
.parser
.gen_prefix(safe_name(self
.type))
300 elif self
.type == 'mbo':
303 print("#error unhandled type: %s" % self
.type)
306 print(" %-36s %s%s;" % (type, self
.name
, dim
))
309 if self
.values
and self
.default
is None:
311 prefix
= self
.prefix
+ "_"
313 for value
in self
.values
:
314 print("#define %-40s %d" % (prefix
+ value
.name
, value
.value
))
317 def __init__(self
, parser
, parent
, start
, count
, size
):
325 def emit_template_struct(self
, dim
):
327 print(" /* variable length fields follow */")
330 dim
= "%s[%d]" % (dim
, self
.count
)
332 for field
in self
.fields
:
333 field
.emit_template_struct(dim
)
341 def collect_dwords(self
, dwords
, start
, dim
):
342 for field
in self
.fields
:
343 if isinstance(field
, Group
):
345 field
.collect_dwords(dwords
, start
+ field
.start
, dim
)
347 for i
in range(field
.count
):
348 field
.collect_dwords(dwords
,
349 start
+ field
.start
+ i
* field
.size
,
353 index
= (start
+ field
.start
) // 32
354 if not index
in dwords
:
355 dwords
[index
] = self
.DWord()
357 clone
= copy
.copy(field
)
358 clone
.start
= clone
.start
+ start
359 clone
.end
= clone
.end
+ start
361 dwords
[index
].fields
.append(clone
)
363 if field
.type == "address":
364 # assert dwords[index].address == None
365 dwords
[index
].address
= field
367 # Coalesce all the dwords covered by this field. The two cases we
368 # handle are where multiple fields are in a 64 bit word (typically
369 # and address and a few bits) or where a single struct field
370 # completely covers multiple dwords.
371 while index
< (start
+ field
.end
) // 32:
372 if index
+ 1 in dwords
and not dwords
[index
] == dwords
[index
+ 1]:
373 dwords
[index
].fields
.extend(dwords
[index
+ 1].fields
)
374 dwords
[index
].size
= 64
375 dwords
[index
+ 1] = dwords
[index
]
378 def collect_dwords_and_length(self
):
380 self
.collect_dwords(dwords
, 0, "")
382 # Determine number of dwords in this group. If we have a size, use
383 # that, since that'll account for MBZ dwords at the end of a group
384 # (like dword 8 on BDW+ 3DSTATE_HS). Otherwise, use the largest dword
385 # index we've seen plus one.
387 length
= self
.size
// 32
389 length
= max(dwords
.keys()) + 1
393 return (dwords
, length
)
395 def emit_pack_function(self
, dwords
, length
):
396 for index
in range(length
):
398 if not index
in dwords
:
400 print(" dw[%d] = 0;" % index
)
403 # For 64 bit dwords, we aliased the two dword entries in the dword
404 # dict it occupies. Now that we're emitting the pack function,
405 # skip the duplicate entries.
407 if index
> 0 and index
- 1 in dwords
and dw
== dwords
[index
- 1]:
410 # Special case: only one field and it's a struct at the beginning
411 # of the dword. In this case we pack directly into the
412 # destination. This is the only way we handle embedded structs
413 # larger than 32 bits.
414 if len(dw
.fields
) == 1:
416 name
= field
.name
+ field
.dim
417 if field
.is_struct_type() and field
.start
% 32 == 0:
419 print(" %s_pack(data, &dw[%d], &values->%s);" %
420 (self
.parser
.gen_prefix(safe_name(field
.type)), index
, name
))
423 # Pack any fields of struct type first so we have integer values
424 # to the dword for those fields.
426 for field
in dw
.fields
:
427 if isinstance(field
, Field
) and field
.is_struct_type():
428 name
= field
.name
+ field
.dim
430 print(" uint32_t v%d_%d;" % (index
, field_index
))
431 print(" %s_pack(data, &v%d_%d, &values->%s);" %
432 (self
.parser
.gen_prefix(safe_name(field
.type)), index
, field_index
, name
))
433 field_index
= field_index
+ 1
436 dword_start
= index
* 32
437 if dw
.address
== None:
442 if dw
.size
== 32 and dw
.address
== None:
444 print(" dw[%d] =" % index
)
445 elif len(dw
.fields
) > address_count
:
447 print(" const uint%d_t %s =" % (dw
.size
, v
))
452 non_address_fields
= []
453 for field
in dw
.fields
:
454 if field
.type != "mbo":
455 name
= field
.name
+ field
.dim
457 if field
.type == "mbo":
458 non_address_fields
.append("__gen_mbo(%d, %d)" % \
459 (field
.start
- dword_start
, field
.end
- dword_start
))
460 elif field
.type == "address":
462 elif field
.type == "uint":
463 non_address_fields
.append("__gen_uint(values->%s, %d, %d)" % \
464 (name
, field
.start
- dword_start
, field
.end
- dword_start
))
465 elif field
.is_enum_type():
466 non_address_fields
.append("__gen_uint(values->%s, %d, %d)" % \
467 (name
, field
.start
- dword_start
, field
.end
- dword_start
))
468 elif field
.type == "int":
469 non_address_fields
.append("__gen_sint(values->%s, %d, %d)" % \
470 (name
, field
.start
- dword_start
, field
.end
- dword_start
))
471 elif field
.type == "bool":
472 non_address_fields
.append("__gen_uint(values->%s, %d, %d)" % \
473 (name
, field
.start
- dword_start
, field
.end
- dword_start
))
474 elif field
.type == "float":
475 non_address_fields
.append("__gen_float(values->%s)" % name
)
476 elif field
.type == "offset":
477 non_address_fields
.append("__gen_offset(values->%s, %d, %d)" % \
478 (name
, field
.start
- dword_start
, field
.end
- dword_start
))
479 elif field
.type == 'ufixed':
480 non_address_fields
.append("__gen_ufixed(values->%s, %d, %d, %d)" % \
481 (name
, field
.start
- dword_start
, field
.end
- dword_start
, field
.fractional_size
))
482 elif field
.type == 'sfixed':
483 non_address_fields
.append("__gen_sfixed(values->%s, %d, %d, %d)" % \
484 (name
, field
.start
- dword_start
, field
.end
- dword_start
, field
.fractional_size
))
485 elif field
.is_struct_type():
486 non_address_fields
.append("__gen_uint(v%d_%d, %d, %d)" % \
487 (index
, field_index
, field
.start
- dword_start
, field
.end
- dword_start
))
488 field_index
= field_index
+ 1
490 non_address_fields
.append("/* unhandled field %s, type %s */\n" % \
493 if non_address_fields
:
494 print(" |\n".join(" " + f
for f
in non_address_fields
) + ";")
498 print(" dw[%d] = __gen_combine_address(data, &dw[%d], values->%s, %s);" % (index
, index
, dw
.address
.name
+ field
.dim
, v
))
502 v_address
= "v%d_address" % index
503 print(" const uint64_t %s =\n __gen_combine_address(data, &dw[%d], values->%s, %s);" %
504 (v_address
, index
, dw
.address
.name
+ field
.dim
, v
))
505 if len(dw
.fields
) > address_count
:
506 print(" dw[%d] = %s;" % (index
, v_address
))
507 print(" dw[%d] = (%s >> 32) | (%s >> 32);" % (index
+ 1, v_address
, v
))
511 print(" dw[%d] = %s;" % (index
, v
))
512 print(" dw[%d] = %s >> 32;" % (index
+ 1, v
))
515 def __init__(self
, attrs
):
516 self
.name
= safe_name(attrs
["name"])
517 self
.value
= ast
.literal_eval(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
525 self
.instruction
= None
527 # Set of enum names we've seen.
531 def gen_prefix(self
, name
):
533 return 'GEN%s%s' % (self
.gen
, name
)
534 return 'GEN%s_%s' % (self
.gen
, name
)
537 return self
.gen_prefix("PACK_H")
539 def start_element(self
, name
, attrs
):
541 self
.platform
= attrs
["name"]
542 self
.gen
= attrs
["gen"].replace('.', '')
543 print(pack_header
% {'license': license
, 'platform': self
.platform
, 'guard': self
.gen_guard()})
544 elif name
in ("instruction", "struct", "register"):
545 if name
== "instruction":
546 self
.instruction
= safe_name(attrs
["name"])
547 self
.length_bias
= int(attrs
["bias"])
548 if "engine" in attrs
:
549 self
.instruction_engines
= set(attrs
["engine"].split('|'))
551 # When an instruction doesn't have the engine specified,
552 # it is considered to be for all engines, so 'None' is used
553 # to signify that the instruction belongs to all engines.
554 self
.instruction_engines
= None
555 elif name
== "struct":
556 self
.struct
= safe_name(attrs
["name"])
557 self
.structs
[attrs
["name"]] = 1
558 elif name
== "register":
559 self
.register
= safe_name(attrs
["name"])
560 self
.reg_num
= num_from_str(attrs
["num"])
561 self
.registers
[attrs
["name"]] = 1
562 if "length" in attrs
:
563 self
.length
= int(attrs
["length"])
564 size
= self
.length
* 32
568 self
.group
= Group(self
, None, 0, 1, size
)
570 elif name
== "group":
571 group
= Group(self
, self
.group
,
572 int(attrs
["start"]), int(attrs
["count"]), int(attrs
["size"]))
573 self
.group
.fields
.append(group
)
575 elif name
== "field":
576 self
.group
.fields
.append(Field(self
, attrs
))
580 self
.enum
= safe_name(attrs
["name"])
581 self
.enums
.add(attrs
["name"])
582 if "prefix" in attrs
:
583 self
.prefix
= safe_name(attrs
["prefix"])
586 elif name
== "value":
587 self
.values
.append(Value(attrs
))
589 def end_element(self
, name
):
590 if name
== "instruction":
591 self
.emit_instruction()
592 self
.instruction
= None
594 elif name
== "struct":
598 elif name
== "register":
603 elif name
== "group":
604 self
.group
= self
.group
.parent
605 elif name
== "field":
606 self
.group
.fields
[-1].values
= self
.values
610 elif name
== "genxml":
611 print('#endif /* %s */' % self
.gen_guard())
613 def emit_template_struct(self
, name
, group
):
614 print("struct %s {" % self
.gen_prefix(name
))
615 group
.emit_template_struct("")
618 def emit_pack_function(self
, name
, group
):
619 name
= self
.gen_prefix(name
)
620 print(textwrap
.dedent("""\
622 %s_pack(__attribute__((unused)) __gen_user_data *data,
623 %s__attribute__((unused)) void * restrict dst,
624 %s__attribute__((unused)) const struct %s * restrict values)
625 {""") % (name
, ' ' * len(name
), ' ' * len(name
), name
))
627 (dwords
, length
) = group
.collect_dwords_and_length()
629 # Cast dst to make header C++ friendly
630 print(" uint32_t * restrict dw = (uint32_t * restrict) dst;")
632 group
.emit_pack_function(dwords
, length
)
636 def emit_instruction(self
):
637 name
= self
.instruction
638 if self
.instruction_engines
and not self
.instruction_engines
& self
.engines
:
641 if not self
.length
is None:
642 print('#define %-33s %6d' %
643 (self
.gen_prefix(name
+ "_length"), self
.length
))
644 print('#define %-33s %6d' %
645 (self
.gen_prefix(name
+ "_length_bias"), self
.length_bias
))
648 for field
in self
.group
.fields
:
649 if not isinstance(field
, Field
):
651 if field
.default
is None:
653 default_fields
.append(" .%-35s = %6d" % (field
.name
, field
.default
))
656 print('#define %-40s\\' % (self
.gen_prefix(name
+ '_header')))
657 print(", \\\n".join(default_fields
))
660 self
.emit_template_struct(self
.instruction
, self
.group
)
662 self
.emit_pack_function(self
.instruction
, self
.group
)
664 def emit_register(self
):
666 if not self
.reg_num
is None:
667 print('#define %-33s 0x%04x' %
668 (self
.gen_prefix(name
+ "_num"), self
.reg_num
))
670 if not self
.length
is None:
671 print('#define %-33s %6d' %
672 (self
.gen_prefix(name
+ "_length"), self
.length
))
674 self
.emit_template_struct(self
.register
, self
.group
)
675 self
.emit_pack_function(self
.register
, self
.group
)
677 def emit_struct(self
):
679 if not self
.length
is None:
680 print('#define %-33s %6d' %
681 (self
.gen_prefix(name
+ "_length"), self
.length
))
683 self
.emit_template_struct(self
.struct
, self
.group
)
684 self
.emit_pack_function(self
.struct
, self
.group
)
687 print('enum %s {' % self
.gen_prefix(self
.enum
))
688 for value
in self
.values
:
690 name
= self
.prefix
+ "_" + value
.name
693 print(' %-36s = %6d,' % (name
.upper(), value
.value
))
696 def parse(self
, filename
):
697 file = open(filename
, "rb")
698 self
.parser
.ParseFile(file)
702 p
= argparse
.ArgumentParser()
703 p
.add_argument('xml_source', metavar
='XML_SOURCE',
704 help="Input xml file")
705 p
.add_argument('--engines', nargs
='?', type=str, default
='render',
706 help="Comma-separated list of engines whose instructions should be parsed (default: %(default)s)")
708 pargs
= p
.parse_args()
710 if pargs
.engines
is None:
711 print("No engines specified")
719 input_file
= pargs
.xml_source
720 engines
= pargs
.engines
.split(',')
721 valid_engines
= [ 'render', 'blitter', 'video' ]
722 if set(engines
) - set(valid_engines
):
723 print("Invalid engine specified, valid engines are:\n")
724 for e
in valid_engines
:
729 p
.engines
= set(engines
)
732 if __name__
== '__main__':