intel: Split gen_device_info out into libintel_dev
[mesa.git] / src / intel / genxml / gen_pack_header.py
1 #encoding=utf-8
2
3 from __future__ import (
4 absolute_import, division, print_function, unicode_literals
5 )
6 import ast
7 import xml.parsers.expat
8 import re
9 import sys
10 import copy
11 import textwrap
12
13 license = """/*
14 * Copyright (C) 2016 Intel Corporation
15 *
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:
22 *
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
25 * Software.
26 *
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
33 * IN THE SOFTWARE.
34 */
35 """
36
37 pack_header = """%(license)s
38
39 /* Instructions, enums and structures for %(platform)s.
40 *
41 * This file has been generated, do not hand edit.
42 */
43
44 #ifndef %(guard)s
45 #define %(guard)s
46
47 #include <stdio.h>
48 #include <stdint.h>
49 #include <stdbool.h>
50 #include <assert.h>
51 #include <math.h>
52
53 #ifndef __gen_validate_value
54 #define __gen_validate_value(x)
55 #endif
56
57 #ifndef __gen_field_functions
58 #define __gen_field_functions
59
60 #ifdef NDEBUG
61 #define NDEBUG_UNUSED __attribute__((unused))
62 #else
63 #define NDEBUG_UNUSED
64 #endif
65
66 union __gen_value {
67 float f;
68 uint32_t dw;
69 };
70
71 static inline uint64_t
72 __gen_mbo(uint32_t start, uint32_t end)
73 {
74 return (~0ull >> (64 - (end - start + 1))) << start;
75 }
76
77 static inline uint64_t
78 __gen_uint(uint64_t v, uint32_t start, NDEBUG_UNUSED uint32_t end)
79 {
80 __gen_validate_value(v);
81
82 #ifndef NDEBUG
83 const int width = end - start + 1;
84 if (width < 64) {
85 const uint64_t max = (1ull << width) - 1;
86 assert(v <= max);
87 }
88 #endif
89
90 return v << start;
91 }
92
93 static inline uint64_t
94 __gen_sint(int64_t v, uint32_t start, uint32_t end)
95 {
96 const int width = end - start + 1;
97
98 __gen_validate_value(v);
99
100 #ifndef NDEBUG
101 if (width < 64) {
102 const int64_t max = (1ll << (width - 1)) - 1;
103 const int64_t min = -(1ll << (width - 1));
104 assert(min <= v && v <= max);
105 }
106 #endif
107
108 const uint64_t mask = ~0ull >> (64 - width);
109
110 return (v & mask) << start;
111 }
112
113 static inline uint64_t
114 __gen_offset(uint64_t v, NDEBUG_UNUSED uint32_t start, NDEBUG_UNUSED uint32_t end)
115 {
116 __gen_validate_value(v);
117 #ifndef NDEBUG
118 uint64_t mask = (~0ull >> (64 - (end - start + 1))) << start;
119
120 assert((v & ~mask) == 0);
121 #endif
122
123 return v;
124 }
125
126 static inline uint32_t
127 __gen_float(float v)
128 {
129 __gen_validate_value(v);
130 return ((union __gen_value) { .f = (v) }).dw;
131 }
132
133 static inline uint64_t
134 __gen_sfixed(float v, uint32_t start, uint32_t end, uint32_t fract_bits)
135 {
136 __gen_validate_value(v);
137
138 const float factor = (1 << fract_bits);
139
140 #ifndef NDEBUG
141 const float max = ((1 << (end - start)) - 1) / factor;
142 const float min = -(1 << (end - start)) / factor;
143 assert(min <= v && v <= max);
144 #endif
145
146 const int64_t int_val = llroundf(v * factor);
147 const uint64_t mask = ~0ull >> (64 - (end - start + 1));
148
149 return (int_val & mask) << start;
150 }
151
152 static inline uint64_t
153 __gen_ufixed(float v, uint32_t start, NDEBUG_UNUSED uint32_t end, uint32_t fract_bits)
154 {
155 __gen_validate_value(v);
156
157 const float factor = (1 << fract_bits);
158
159 #ifndef NDEBUG
160 const float max = ((1 << (end - start + 1)) - 1) / factor;
161 const float min = 0.0f;
162 assert(min <= v && v <= max);
163 #endif
164
165 const uint64_t uint_val = llroundf(v * factor);
166
167 return uint_val << start;
168 }
169
170 #ifndef __gen_address_type
171 #error #define __gen_address_type before including this file
172 #endif
173
174 #ifndef __gen_user_data
175 #error #define __gen_combine_address before including this file
176 #endif
177
178 #undef NDEBUG_UNUSED
179
180 #endif
181
182 """
183
184 def to_alphanum(name):
185 substitutions = {
186 ' ': '',
187 '/': '',
188 '[': '',
189 ']': '',
190 '(': '',
191 ')': '',
192 '-': '',
193 ':': '',
194 '.': '',
195 ',': '',
196 '=': '',
197 '>': '',
198 '#': '',
199 'α': 'alpha',
200 '&': '',
201 '*': '',
202 '"': '',
203 '+': '',
204 '\'': '',
205 }
206
207 for i, j in substitutions.items():
208 name = name.replace(i, j)
209
210 return name
211
212 def safe_name(name):
213 name = to_alphanum(name)
214 if not name[0].isalpha():
215 name = '_' + name
216
217 return name
218
219 def num_from_str(num_str):
220 if num_str.lower().startswith('0x'):
221 return int(num_str, base=16)
222 else:
223 assert(not num_str.startswith('0') and 'octals numbers not allowed')
224 return int(num_str)
225
226 class Field(object):
227 ufixed_pattern = re.compile(r"u(\d+)\.(\d+)")
228 sfixed_pattern = re.compile(r"s(\d+)\.(\d+)")
229
230 def __init__(self, parser, attrs):
231 self.parser = parser
232 if "name" in 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"]
237
238 if "prefix" in attrs:
239 self.prefix = attrs["prefix"]
240 else:
241 self.prefix = None
242
243 if "default" in attrs:
244 self.default = int(attrs["default"])
245 else:
246 self.default = None
247
248 ufixed_match = Field.ufixed_pattern.match(self.type)
249 if ufixed_match:
250 self.type = 'ufixed'
251 self.fractional_size = int(ufixed_match.group(2))
252
253 sfixed_match = Field.sfixed_pattern.match(self.type)
254 if sfixed_match:
255 self.type = 'sfixed'
256 self.fractional_size = int(sfixed_match.group(2))
257
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
262
263 def is_struct_type(self):
264 return self.type in self.parser.structs
265
266 def is_enum_type(self):
267 return self.type in self.parser.enums
268
269 def emit_template_struct(self, dim):
270 if self.type == 'address':
271 type = '__gen_address_type'
272 elif self.type == 'bool':
273 type = 'bool'
274 elif self.type == 'float':
275 type = 'float'
276 elif self.type == 'ufixed':
277 type = 'float'
278 elif self.type == 'sfixed':
279 type = 'float'
280 elif self.type == 'uint' and self.end - self.start > 32:
281 type = 'uint64_t'
282 elif self.type == 'offset':
283 type = 'uint64_t'
284 elif self.type == 'int':
285 type = 'int32_t'
286 elif self.type == 'uint':
287 type = 'uint32_t'
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':
293 return
294 else:
295 print("#error unhandled type: %s" % self.type)
296 return
297
298 print(" %-36s %s%s;" % (type, self.name, dim))
299
300 prefix = ""
301 if len(self.values) > 0 and self.default == None:
302 if self.prefix:
303 prefix = self.prefix + "_"
304
305 for value in self.values:
306 print("#define %-40s %d" % (prefix + value.name, value.value))
307
308 class Group(object):
309 def __init__(self, parser, parent, start, count, size):
310 self.parser = parser
311 self.parent = parent
312 self.start = start
313 self.count = count
314 self.size = size
315 self.fields = []
316
317 def emit_template_struct(self, dim):
318 if self.count == 0:
319 print(" /* variable length fields follow */")
320 else:
321 if self.count > 1:
322 dim = "%s[%d]" % (dim, self.count)
323
324 for field in self.fields:
325 field.emit_template_struct(dim)
326
327 class DWord:
328 def __init__(self):
329 self.size = 32
330 self.fields = []
331 self.address = None
332
333 def collect_dwords(self, dwords, start, dim):
334 for field in self.fields:
335 if type(field) is Group:
336 if field.count == 1:
337 field.collect_dwords(dwords, start + field.start, dim)
338 else:
339 for i in range(field.count):
340 field.collect_dwords(dwords,
341 start + field.start + i * field.size,
342 "%s[%d]" % (dim, i))
343 continue
344
345 index = (start + field.start) // 32
346 if not index in dwords:
347 dwords[index] = self.DWord()
348
349 clone = copy.copy(field)
350 clone.start = clone.start + start
351 clone.end = clone.end + start
352 clone.dim = dim
353 dwords[index].fields.append(clone)
354
355 if field.type == "address":
356 # assert dwords[index].address == None
357 dwords[index].address = field
358
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]
368 index = index + 1
369
370 def collect_dwords_and_length(self):
371 dwords = {}
372 self.collect_dwords(dwords, 0, "")
373
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.
378 if self.size > 0:
379 length = self.size // 32
380 elif dwords:
381 length = max(dwords.keys()) + 1
382 else:
383 length = 0
384
385 return (dwords, length)
386
387 def emit_pack_function(self, dwords, length):
388 for index in range(length):
389 # Handle MBZ dwords
390 if not index in dwords:
391 print("")
392 print(" dw[%d] = 0;" % index)
393 continue
394
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.
398 dw = dwords[index]
399 if index > 0 and index - 1 in dwords and dw == dwords[index - 1]:
400 continue
401
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:
407 field = dw.fields[0]
408 name = field.name + field.dim
409 if field.is_struct_type() and field.start % 32 == 0:
410 print("")
411 print(" %s_pack(data, &dw[%d], &values->%s);" %
412 (self.parser.gen_prefix(safe_name(field.type)), index, name))
413 continue
414
415 # Pack any fields of struct type first so we have integer values
416 # to the dword for those fields.
417 field_index = 0
418 for field in dw.fields:
419 if type(field) is Field and field.is_struct_type():
420 name = field.name + field.dim
421 print("")
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
426
427 print("")
428 dword_start = index * 32
429 if dw.address == None:
430 address_count = 0
431 else:
432 address_count = 1
433
434 if dw.size == 32 and dw.address == None:
435 v = None
436 print(" dw[%d] =" % index)
437 elif len(dw.fields) > address_count:
438 v = "v%d" % index
439 print(" const uint%d_t %s =" % (dw.size, v))
440 else:
441 v = "0"
442
443 field_index = 0
444 non_address_fields = []
445 for field in dw.fields:
446 if field.type != "mbo":
447 name = field.name + field.dim
448
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":
453 pass
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
481 else:
482 non_address_fields.append("/* unhandled field %s, type %s */\n" % \
483 (name, field.type))
484
485 if len(non_address_fields) > 0:
486 print(" |\n".join(" " + f for f in non_address_fields) + ";")
487
488 if dw.size == 32:
489 if dw.address:
490 print(" dw[%d] = __gen_combine_address(data, &dw[%d], values->%s, %s);" % (index, index, dw.address.name + field.dim, v))
491 continue
492
493 if dw.address:
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))
497 v = v_address
498
499 print(" dw[%d] = %s;" % (index, v))
500 print(" dw[%d] = %s >> 32;" % (index + 1, v))
501
502 class Value(object):
503 def __init__(self, attrs):
504 self.name = safe_name(attrs["name"])
505 self.value = ast.literal_eval(attrs["value"])
506
507 class Parser(object):
508 def __init__(self):
509 self.parser = xml.parsers.expat.ParserCreate()
510 self.parser.StartElementHandler = self.start_element
511 self.parser.EndElementHandler = self.end_element
512
513 self.instruction = None
514 self.structs = {}
515 # Set of enum names we've seen.
516 self.enums = set()
517 self.registers = {}
518
519 def gen_prefix(self, name):
520 if name[0] == "_":
521 return 'GEN%s%s' % (self.gen, name)
522 else:
523 return 'GEN%s_%s' % (self.gen, name)
524
525 def gen_guard(self):
526 return self.gen_prefix("PACK_H")
527
528 def start_element(self, name, attrs):
529 if name == "genxml":
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
547 else:
548 self.length = None
549 size = 0
550 self.group = Group(self, None, 0, 1, size)
551
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)
556 self.group = group
557 elif name == "field":
558 self.group.fields.append(Field(self, attrs))
559 self.values = []
560 elif name == "enum":
561 self.values = []
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"])
566 else:
567 self.prefix= None
568 elif name == "value":
569 self.values.append(Value(attrs))
570
571 def end_element(self, name):
572 if name == "instruction":
573 self.emit_instruction()
574 self.instruction = None
575 self.group = None
576 elif name == "struct":
577 self.emit_struct()
578 self.struct = None
579 self.group = None
580 elif name == "register":
581 self.emit_register()
582 self.register = None
583 self.reg_num = None
584 self.group = None
585 elif name == "group":
586 self.group = self.group.parent
587 elif name == "field":
588 self.group.fields[-1].values = self.values
589 elif name == "enum":
590 self.emit_enum()
591 self.enum = None
592 elif name == "genxml":
593 print('#endif /* %s */' % self.gen_guard())
594
595 def emit_template_struct(self, name, group):
596 print("struct %s {" % self.gen_prefix(name))
597 group.emit_template_struct("")
598 print("};\n")
599
600 def emit_pack_function(self, name, group):
601 name = self.gen_prefix(name)
602 print(textwrap.dedent("""\
603 static inline void
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))
608
609 (dwords, length) = group.collect_dwords_and_length()
610 if length:
611 # Cast dst to make header C++ friendly
612 print(" uint32_t * restrict dw = (uint32_t * restrict) dst;")
613
614 group.emit_pack_function(dwords, length)
615
616 print("}\n")
617
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))
625
626 default_fields = []
627 for field in self.group.fields:
628 if not type(field) is Field:
629 continue
630 if field.default == None:
631 continue
632 default_fields.append(" .%-35s = %6d" % (field.name, field.default))
633
634 if default_fields:
635 print('#define %-40s\\' % (self.gen_prefix(name + '_header')))
636 print(", \\\n".join(default_fields))
637 print('')
638
639 self.emit_template_struct(self.instruction, self.group)
640
641 self.emit_pack_function(self.instruction, self.group)
642
643 def emit_register(self):
644 name = self.register
645 if not self.reg_num == None:
646 print('#define %-33s 0x%04x' %
647 (self.gen_prefix(name + "_num"), self.reg_num))
648
649 if not self.length == None:
650 print('#define %-33s %6d' %
651 (self.gen_prefix(name + "_length"), self.length))
652
653 self.emit_template_struct(self.register, self.group)
654 self.emit_pack_function(self.register, self.group)
655
656 def emit_struct(self):
657 name = self.struct
658 if not self.length == None:
659 print('#define %-33s %6d' %
660 (self.gen_prefix(name + "_length"), self.length))
661
662 self.emit_template_struct(self.struct, self.group)
663 self.emit_pack_function(self.struct, self.group)
664
665 def emit_enum(self):
666 print('enum %s {' % self.gen_prefix(self.enum))
667 for value in self.values:
668 if self.prefix:
669 name = self.prefix + "_" + value.name
670 else:
671 name = value.name
672 print(' %-36s = %6d,' % (name.upper(), value.value))
673 print('};\n')
674
675 def parse(self, filename):
676 file = open(filename, "rb")
677 self.parser.ParseFile(file)
678 file.close()
679
680 if len(sys.argv) < 2:
681 print("No input xml file specified")
682 sys.exit(1)
683
684 input_file = sys.argv[1]
685
686 p = Parser()
687 p.parse(input_file)