genxml: require future imports for python2 compatibility.
[mesa.git] / src / intel / genxml / gen_pack_header.py
1 #!/usr/bin/env python3
2 #encoding=utf-8
3
4 from __future__ import (
5 absolute_import, division, print_function, unicode_literals
6 )
7 import xml.parsers.expat
8 import re
9 import sys
10 import copy
11
12 license = """/*
13 * Copyright (C) 2016 Intel Corporation
14 *
15 * Permission is hereby granted, free of charge, to any person obtaining a
16 * copy of this software and associated documentation files (the "Software"),
17 * to deal in the Software without restriction, including without limitation
18 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
19 * and/or sell copies of the Software, and to permit persons to whom the
20 * Software is furnished to do so, subject to the following conditions:
21 *
22 * The above copyright notice and this permission notice (including the next
23 * paragraph) shall be included in all copies or substantial portions of the
24 * Software.
25 *
26 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
29 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
31 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
32 * IN THE SOFTWARE.
33 */
34 """
35
36 pack_header = """%(license)s
37
38 /* Instructions, enums and structures for %(platform)s.
39 *
40 * This file has been generated, do not hand edit.
41 */
42
43 #pragma once
44
45 #include <stdio.h>
46 #include <stdint.h>
47 #include <stdbool.h>
48 #include <assert.h>
49 #include <math.h>
50
51 #ifndef __gen_validate_value
52 #define __gen_validate_value(x)
53 #endif
54
55 #ifndef __gen_field_functions
56 #define __gen_field_functions
57
58 union __gen_value {
59 float f;
60 uint32_t dw;
61 };
62
63 static inline uint64_t
64 __gen_mbo(uint32_t start, uint32_t end)
65 {
66 return (~0ull >> (64 - (end - start + 1))) << start;
67 }
68
69 static inline uint64_t
70 __gen_uint(uint64_t v, uint32_t start, uint32_t end)
71 {
72 __gen_validate_value(v);
73
74 #if DEBUG
75 const int width = end - start + 1;
76 if (width < 64) {
77 const uint64_t max = (1ull << width) - 1;
78 assert(v <= max);
79 }
80 #endif
81
82 return v << start;
83 }
84
85 static inline uint64_t
86 __gen_sint(int64_t v, uint32_t start, uint32_t end)
87 {
88 const int width = end - start + 1;
89
90 __gen_validate_value(v);
91
92 #if DEBUG
93 if (width < 64) {
94 const int64_t max = (1ll << (width - 1)) - 1;
95 const int64_t min = -(1ll << (width - 1));
96 assert(min <= v && v <= max);
97 }
98 #endif
99
100 const uint64_t mask = ~0ull >> (64 - width);
101
102 return (v & mask) << start;
103 }
104
105 static inline uint64_t
106 __gen_offset(uint64_t v, uint32_t start, uint32_t end)
107 {
108 __gen_validate_value(v);
109 #if DEBUG
110 uint64_t mask = (~0ull >> (64 - (end - start + 1))) << start;
111
112 assert((v & ~mask) == 0);
113 #endif
114
115 return v;
116 }
117
118 static inline uint32_t
119 __gen_float(float v)
120 {
121 __gen_validate_value(v);
122 return ((union __gen_value) { .f = (v) }).dw;
123 }
124
125 static inline uint64_t
126 __gen_sfixed(float v, uint32_t start, uint32_t end, uint32_t fract_bits)
127 {
128 __gen_validate_value(v);
129
130 const float factor = (1 << fract_bits);
131
132 #if DEBUG
133 const float max = ((1 << (end - start)) - 1) / factor;
134 const float min = -(1 << (end - start)) / factor;
135 assert(min <= v && v <= max);
136 #endif
137
138 const int64_t int_val = llroundf(v * factor);
139 const uint64_t mask = ~0ull >> (64 - (end - start + 1));
140
141 return (int_val & mask) << start;
142 }
143
144 static inline uint64_t
145 __gen_ufixed(float v, uint32_t start, uint32_t end, uint32_t fract_bits)
146 {
147 __gen_validate_value(v);
148
149 const float factor = (1 << fract_bits);
150
151 #if DEBUG
152 const float max = ((1 << (end - start + 1)) - 1) / factor;
153 const float min = 0.0f;
154 assert(min <= v && v <= max);
155 #endif
156
157 const uint64_t uint_val = llroundf(v * factor);
158
159 return uint_val << start;
160 }
161
162 #ifndef __gen_address_type
163 #error #define __gen_address_type before including this file
164 #endif
165
166 #ifndef __gen_user_data
167 #error #define __gen_combine_address before including this file
168 #endif
169
170 #endif
171
172 """
173
174 def to_alphanum(name):
175 substitutions = {
176 ' ': '',
177 '/': '',
178 '[': '',
179 ']': '',
180 '(': '',
181 ')': '',
182 '-': '',
183 ':': '',
184 '.': '',
185 ',': '',
186 '=': '',
187 '>': '',
188 '#': '',
189 'α': 'alpha',
190 '&': '',
191 '*': '',
192 '"': '',
193 '+': '',
194 '\'': '',
195 }
196
197 for i, j in substitutions.items():
198 name = name.replace(i, j)
199
200 return name
201
202 def safe_name(name):
203 name = to_alphanum(name)
204 if not str.isalpha(name[0]):
205 name = '_' + name
206
207 return name
208
209 def num_from_str(num_str):
210 if num_str.lower().startswith('0x'):
211 return int(num_str, base=16)
212 else:
213 assert(not num_str.startswith('0') and 'octals numbers not allowed')
214 return int(num_str)
215
216 class Field(object):
217 ufixed_pattern = re.compile(r"u(\d+)\.(\d+)")
218 sfixed_pattern = re.compile(r"s(\d+)\.(\d+)")
219
220 def __init__(self, parser, attrs):
221 self.parser = parser
222 if "name" in attrs:
223 self.name = safe_name(attrs["name"])
224 self.start = int(attrs["start"])
225 self.end = int(attrs["end"])
226 self.type = attrs["type"]
227
228 if "prefix" in attrs:
229 self.prefix = attrs["prefix"]
230 else:
231 self.prefix = None
232
233 if "default" in attrs:
234 self.default = int(attrs["default"])
235 else:
236 self.default = None
237
238 ufixed_match = Field.ufixed_pattern.match(self.type)
239 if ufixed_match:
240 self.type = 'ufixed'
241 self.fractional_size = int(ufixed_match.group(2))
242
243 sfixed_match = Field.sfixed_pattern.match(self.type)
244 if sfixed_match:
245 self.type = 'sfixed'
246 self.fractional_size = int(sfixed_match.group(2))
247
248 def emit_template_struct(self, dim):
249 if self.type == 'address':
250 type = '__gen_address_type'
251 elif self.type == 'bool':
252 type = 'bool'
253 elif self.type == 'float':
254 type = 'float'
255 elif self.type == 'ufixed':
256 type = 'float'
257 elif self.type == 'sfixed':
258 type = 'float'
259 elif self.type == 'uint' and self.end - self.start > 32:
260 type = 'uint64_t'
261 elif self.type == 'offset':
262 type = 'uint64_t'
263 elif self.type == 'int':
264 type = 'int32_t'
265 elif self.type == 'uint':
266 type = 'uint32_t'
267 elif self.type in self.parser.structs:
268 type = 'struct ' + self.parser.gen_prefix(safe_name(self.type))
269 elif self.type == 'mbo':
270 return
271 else:
272 print("#error unhandled type: %s" % self.type)
273
274 print(" %-36s %s%s;" % (type, self.name, dim))
275
276 if len(self.values) > 0 and self.default == None:
277 if self.prefix:
278 prefix = self.prefix + "_"
279 else:
280 prefix = ""
281
282 for value in self.values:
283 print("#define %-40s %d" % (prefix + value.name, value.value))
284
285 class Group(object):
286 def __init__(self, parser, parent, start, count, size):
287 self.parser = parser
288 self.parent = parent
289 self.start = start
290 self.count = count
291 self.size = size
292 self.fields = []
293
294 def emit_template_struct(self, dim):
295 if self.count == 0:
296 print(" /* variable length fields follow */")
297 else:
298 if self.count > 1:
299 dim = "%s[%d]" % (dim, self.count)
300
301 for field in self.fields:
302 field.emit_template_struct(dim)
303
304 class DWord:
305 def __init__(self):
306 self.size = 32
307 self.fields = []
308 self.address = None
309
310 def collect_dwords(self, dwords, start, dim):
311 for field in self.fields:
312 if type(field) is Group:
313 if field.count == 1:
314 field.collect_dwords(dwords, start + field.start, dim)
315 else:
316 for i in range(field.count):
317 field.collect_dwords(dwords,
318 start + field.start + i * field.size,
319 "%s[%d]" % (dim, i))
320 continue
321
322 index = (start + field.start) // 32
323 if not index in dwords:
324 dwords[index] = self.DWord()
325
326 clone = copy.copy(field)
327 clone.start = clone.start + start
328 clone.end = clone.end + start
329 clone.dim = dim
330 dwords[index].fields.append(clone)
331
332 if field.type == "address":
333 # assert dwords[index].address == None
334 dwords[index].address = field
335
336 # Coalesce all the dwords covered by this field. The two cases we
337 # handle are where multiple fields are in a 64 bit word (typically
338 # and address and a few bits) or where a single struct field
339 # completely covers multiple dwords.
340 while index < (start + field.end) // 32:
341 if index + 1 in dwords and not dwords[index] == dwords[index + 1]:
342 dwords[index].fields.extend(dwords[index + 1].fields)
343 dwords[index].size = 64
344 dwords[index + 1] = dwords[index]
345 index = index + 1
346
347 def emit_pack_function(self, start):
348 dwords = {}
349 self.collect_dwords(dwords, 0, "")
350
351 # Determine number of dwords in this group. If we have a size, use
352 # that, since that'll account for MBZ dwords at the end of a group
353 # (like dword 8 on BDW+ 3DSTATE_HS). Otherwise, use the largest dword
354 # index we've seen plus one.
355 if self.size > 0:
356 length = self.size // 32
357 else:
358 length = max(dwords.keys()) + 1
359
360 for index in range(length):
361 # Handle MBZ dwords
362 if not index in dwords:
363 print("")
364 print(" dw[%d] = 0;" % index)
365 continue
366
367 # For 64 bit dwords, we aliased the two dword entries in the dword
368 # dict it occupies. Now that we're emitting the pack function,
369 # skip the duplicate entries.
370 dw = dwords[index]
371 if index > 0 and index - 1 in dwords and dw == dwords[index - 1]:
372 continue
373
374 # Special case: only one field and it's a struct at the beginning
375 # of the dword. In this case we pack directly into the
376 # destination. This is the only way we handle embedded structs
377 # larger than 32 bits.
378 if len(dw.fields) == 1:
379 field = dw.fields[0]
380 name = field.name + field.dim
381 if field.type in self.parser.structs and field.start % 32 == 0:
382 print("")
383 print(" %s_pack(data, &dw[%d], &values->%s);" %
384 (self.parser.gen_prefix(safe_name(field.type)), index, name))
385 continue
386
387 # Pack any fields of struct type first so we have integer values
388 # to the dword for those fields.
389 field_index = 0
390 for field in dw.fields:
391 if type(field) is Field and field.type in self.parser.structs:
392 name = field.name + field.dim
393 print("")
394 print(" uint32_t v%d_%d;" % (index, field_index))
395 print(" %s_pack(data, &v%d_%d, &values->%s);" %
396 (self.parser.gen_prefix(safe_name(field.type)), index, field_index, name))
397 field_index = field_index + 1
398
399 print("")
400 dword_start = index * 32
401 if dw.address == None:
402 address_count = 0
403 else:
404 address_count = 1
405
406 if dw.size == 32 and dw.address == None:
407 v = None
408 print(" dw[%d] =" % index)
409 elif len(dw.fields) > address_count:
410 v = "v%d" % index
411 print(" const uint%d_t %s =" % (dw.size, v))
412 else:
413 v = "0"
414
415 field_index = 0
416 for field in dw.fields:
417 if field.type != "mbo":
418 name = field.name + field.dim
419
420 if field.type == "mbo":
421 s = "__gen_mbo(%d, %d)" % \
422 (field.start - dword_start, field.end - dword_start)
423 elif field.type == "address":
424 s = None
425 elif field.type == "uint":
426 s = "__gen_uint(values->%s, %d, %d)" % \
427 (name, field.start - dword_start, field.end - dword_start)
428 elif field.type == "int":
429 s = "__gen_sint(values->%s, %d, %d)" % \
430 (name, field.start - dword_start, field.end - dword_start)
431 elif field.type == "bool":
432 s = "__gen_uint(values->%s, %d, %d)" % \
433 (name, field.start - dword_start, field.end - dword_start)
434 elif field.type == "float":
435 s = "__gen_float(values->%s)" % name
436 elif field.type == "offset":
437 s = "__gen_offset(values->%s, %d, %d)" % \
438 (name, field.start - dword_start, field.end - dword_start)
439 elif field.type == 'ufixed':
440 s = "__gen_ufixed(values->%s, %d, %d, %d)" % \
441 (name, field.start - dword_start, field.end - dword_start, field.fractional_size)
442 elif field.type == 'sfixed':
443 s = "__gen_sfixed(values->%s, %d, %d, %d)" % \
444 (name, field.start - dword_start, field.end - dword_start, field.fractional_size)
445 elif field.type in self.parser.structs:
446 s = "__gen_uint(v%d_%d, %d, %d)" % \
447 (index, field_index, field.start - dword_start, field.end - dword_start)
448 field_index = field_index + 1
449 else:
450 print("/* unhandled field %s, type %s */\n" % (name, field.type))
451 s = None
452
453 if not s == None:
454 if field == dw.fields[-1]:
455 print(" %s;" % s)
456 else:
457 print(" %s |" % s)
458
459 if dw.size == 32:
460 if dw.address:
461 print(" dw[%d] = __gen_combine_address(data, &dw[%d], values->%s, %s);" % (index, index, dw.address.name, v))
462 continue
463
464 if dw.address:
465 v_address = "v%d_address" % index
466 print(" const uint64_t %s =\n __gen_combine_address(data, &dw[%d], values->%s, %s);" %
467 (v_address, index, dw.address.name, v))
468 v = v_address
469
470 print(" dw[%d] = %s;" % (index, v))
471 print(" dw[%d] = %s >> 32;" % (index + 1, v))
472
473 class Value(object):
474 def __init__(self, attrs):
475 self.name = safe_name(attrs["name"])
476 self.value = int(attrs["value"])
477
478 class Parser(object):
479 def __init__(self):
480 self.parser = xml.parsers.expat.ParserCreate()
481 self.parser.StartElementHandler = self.start_element
482 self.parser.EndElementHandler = self.end_element
483
484 self.instruction = None
485 self.structs = {}
486 self.registers = {}
487
488 def start_element(self, name, attrs):
489 if name == "genxml":
490 self.platform = attrs["name"]
491 self.gen = attrs["gen"].replace('.', '')
492 print(pack_header % {'license': license, 'platform': self.platform})
493 elif name in ("instruction", "struct", "register"):
494 if name == "instruction":
495 self.instruction = safe_name(attrs["name"])
496 self.length_bias = int(attrs["bias"])
497 elif name == "struct":
498 self.struct = safe_name(attrs["name"])
499 self.structs[attrs["name"]] = 1
500 elif name == "register":
501 self.register = safe_name(attrs["name"])
502 self.reg_num = num_from_str(attrs["num"])
503 self.registers[attrs["name"]] = 1
504 if "length" in attrs:
505 self.length = int(attrs["length"])
506 size = self.length * 32
507 else:
508 self.length = None
509 size = 0
510 self.group = Group(self, None, 0, 1, size)
511
512 elif name == "group":
513 group = Group(self, self.group,
514 int(attrs["start"]), int(attrs["count"]), int(attrs["size"]))
515 self.group.fields.append(group)
516 self.group = group
517 elif name == "field":
518 self.group.fields.append(Field(self, attrs))
519 self.values = []
520 elif name == "enum":
521 self.values = []
522 self.enum = safe_name(attrs["name"])
523 if "prefix" in attrs:
524 self.prefix = safe_name(attrs["prefix"])
525 else:
526 self.prefix= None
527 elif name == "value":
528 self.values.append(Value(attrs))
529
530 def end_element(self, name):
531 if name == "instruction":
532 self.emit_instruction()
533 self.instruction = None
534 self.group = None
535 elif name == "struct":
536 self.emit_struct()
537 self.struct = None
538 self.group = None
539 elif name == "register":
540 self.emit_register()
541 self.register = None
542 self.reg_num = None
543 self.group = None
544 elif name == "group":
545 self.group = self.group.parent
546 elif name == "field":
547 self.group.fields[-1].values = self.values
548 elif name == "enum":
549 self.emit_enum()
550 self.enum = None
551
552 def gen_prefix(self, name):
553 if name[0] == "_":
554 return 'GEN%s%s' % (self.gen, name)
555 else:
556 return 'GEN%s_%s' % (self.gen, name)
557
558 def emit_template_struct(self, name, group):
559 print("struct %s {" % self.gen_prefix(name))
560 group.emit_template_struct("")
561 print("};\n")
562
563 def emit_pack_function(self, name, group):
564 name = self.gen_prefix(name)
565 print("static inline void\n%s_pack(__gen_user_data *data, void * restrict dst,\n%sconst struct %s * restrict values)\n{" %
566 (name, ' ' * (len(name) + 6), name))
567
568 # Cast dst to make header C++ friendly
569 print(" uint32_t * restrict dw = (uint32_t * restrict) dst;")
570
571 group.emit_pack_function(0)
572
573 print("}\n")
574
575 def emit_instruction(self):
576 name = self.instruction
577 if not self.length == None:
578 print('#define %-33s %6d' %
579 (self.gen_prefix(name + "_length"), self.length))
580 print('#define %-33s %6d' %
581 (self.gen_prefix(name + "_length_bias"), self.length_bias))
582
583 default_fields = []
584 for field in self.group.fields:
585 if not type(field) is Field:
586 continue
587 if field.default == None:
588 continue
589 default_fields.append(" .%-35s = %6d" % (field.name, field.default))
590
591 if default_fields:
592 print('#define %-40s\\' % (self.gen_prefix(name + '_header')))
593 print(", \\\n".join(default_fields))
594 print('')
595
596 self.emit_template_struct(self.instruction, self.group)
597
598 self.emit_pack_function(self.instruction, self.group)
599
600 def emit_register(self):
601 name = self.register
602 if not self.reg_num == None:
603 print('#define %-33s 0x%04x' %
604 (self.gen_prefix(name + "_num"), self.reg_num))
605
606 if not self.length == None:
607 print('#define %-33s %6d' %
608 (self.gen_prefix(name + "_length"), self.length))
609
610 self.emit_template_struct(self.register, self.group)
611 self.emit_pack_function(self.register, self.group)
612
613 def emit_struct(self):
614 name = self.struct
615 if not self.length == None:
616 print('#define %-33s %6d' %
617 (self.gen_prefix(name + "_length"), self.length))
618
619 self.emit_template_struct(self.struct, self.group)
620 self.emit_pack_function(self.struct, self.group)
621
622 def emit_enum(self):
623 print('/* enum %s */' % self.gen_prefix(self.enum))
624 for value in self.values:
625 if self.prefix:
626 name = self.prefix + "_" + value.name
627 else:
628 name = value.name
629 print('#define %-36s %6d' % (name.upper(), value.value))
630 print('')
631
632 def parse(self, filename):
633 file = open(filename, "rb")
634 self.parser.ParseFile(file)
635 file.close()
636
637 if len(sys.argv) < 2:
638 print("No input xml file specified")
639 sys.exit(1)
640
641 input_file = sys.argv[1]
642
643 p = Parser()
644 p.parse(input_file)