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