anv: pCreateInfo->pApplicationInfo parameter to vkCreateInstance may be NULL
[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 if "name" in attrs:
210 self.name = safe_name(attrs["name"])
211 self.start = int(attrs["start"])
212 self.end = int(attrs["end"])
213 self.type = attrs["type"]
214
215 if "prefix" in attrs:
216 self.prefix = attrs["prefix"]
217 else:
218 self.prefix = None
219
220 if "default" in attrs:
221 self.default = int(attrs["default"])
222 else:
223 self.default = None
224
225 ufixed_match = Field.ufixed_pattern.match(self.type)
226 if ufixed_match:
227 self.type = 'ufixed'
228 self.fractional_size = int(ufixed_match.group(2))
229
230 sfixed_match = Field.sfixed_pattern.match(self.type)
231 if sfixed_match:
232 self.type = 'sfixed'
233 self.fractional_size = int(sfixed_match.group(2))
234
235 def emit_template_struct(self, dim):
236 if self.type == 'address':
237 type = '__gen_address_type'
238 elif self.type == 'bool':
239 type = 'bool'
240 elif self.type == 'float':
241 type = 'float'
242 elif self.type == 'ufixed':
243 type = 'float'
244 elif self.type == 'sfixed':
245 type = 'float'
246 elif self.type == 'uint' and self.end - self.start > 32:
247 type = 'uint64_t'
248 elif self.type == 'offset':
249 type = 'uint64_t'
250 elif self.type == 'int':
251 type = 'int32_t'
252 elif self.type == 'uint':
253 type = 'uint32_t'
254 elif self.type in self.parser.structs:
255 type = 'struct ' + self.parser.gen_prefix(safe_name(self.type))
256 elif self.type == 'mbo':
257 return
258 else:
259 print("#error unhandled type: %s" % self.type)
260
261 print(" %-36s %s%s;" % (type, self.name, dim))
262
263 if len(self.values) > 0 and self.default == None:
264 if self.prefix:
265 prefix = self.prefix + "_"
266 else:
267 prefix = ""
268
269 for value in self.values:
270 print("#define %-40s %d" % (prefix + value.name, value.value))
271
272 class Group:
273 def __init__(self, parser, parent, start, count, size):
274 self.parser = parser
275 self.parent = parent
276 self.start = start
277 self.count = count
278 self.size = size
279 self.fields = []
280
281 def emit_template_struct(self, dim):
282 if self.count == 0:
283 print(" /* variable length fields follow */")
284 else:
285 if self.count > 1:
286 dim = "%s[%d]" % (dim, self.count)
287
288 for field in self.fields:
289 field.emit_template_struct(dim)
290
291 class DWord:
292 def __init__(self):
293 self.size = 32
294 self.fields = []
295 self.address = None
296
297 def collect_dwords(self, dwords, start, dim):
298 for field in self.fields:
299 if type(field) is Group:
300 if field.count == 1:
301 field.collect_dwords(dwords, start + field.start, dim)
302 else:
303 for i in range(field.count):
304 field.collect_dwords(dwords,
305 start + field.start + i * field.size,
306 "%s[%d]" % (dim, i))
307 continue
308
309 index = (start + field.start) // 32
310 if not index in dwords:
311 dwords[index] = self.DWord()
312
313 clone = copy.copy(field)
314 clone.start = clone.start + start
315 clone.end = clone.end + start
316 clone.dim = dim
317 dwords[index].fields.append(clone)
318
319 if field.type == "address":
320 # assert dwords[index].address == None
321 dwords[index].address = field
322
323 # Coalesce all the dwords covered by this field. The two cases we
324 # handle are where multiple fields are in a 64 bit word (typically
325 # and address and a few bits) or where a single struct field
326 # completely covers multiple dwords.
327 while index < (start + field.end) // 32:
328 if index + 1 in dwords and not dwords[index] == dwords[index + 1]:
329 dwords[index].fields.extend(dwords[index + 1].fields)
330 dwords[index].size = 64
331 dwords[index + 1] = dwords[index]
332 index = index + 1
333
334 def emit_pack_function(self, start):
335 dwords = {}
336 self.collect_dwords(dwords, 0, "")
337
338 # Determine number of dwords in this group. If we have a size, use
339 # that, since that'll account for MBZ dwords at the end of a group
340 # (like dword 8 on BDW+ 3DSTATE_HS). Otherwise, use the largest dword
341 # index we've seen plus one.
342 if self.size > 0:
343 length = self.size // 32
344 else:
345 length = max(dwords.keys()) + 1
346
347 for index in range(length):
348 # Handle MBZ dwords
349 if not index in dwords:
350 print("")
351 print(" dw[%d] = 0;" % index)
352 continue
353
354 # For 64 bit dwords, we aliased the two dword entries in the dword
355 # dict it occupies. Now that we're emitting the pack function,
356 # skip the duplicate entries.
357 dw = dwords[index]
358 if index > 0 and index - 1 in dwords and dw == dwords[index - 1]:
359 continue
360
361 # Special case: only one field and it's a struct at the beginning
362 # of the dword. In this case we pack directly into the
363 # destination. This is the only way we handle embedded structs
364 # larger than 32 bits.
365 if len(dw.fields) == 1:
366 field = dw.fields[0]
367 name = field.name + field.dim
368 if field.type in self.parser.structs and field.start % 32 == 0:
369 print("")
370 print(" %s_pack(data, &dw[%d], &values->%s);" %
371 (self.parser.gen_prefix(safe_name(field.type)), index, name))
372 continue
373
374 # Pack any fields of struct type first so we have integer values
375 # to the dword for those fields.
376 field_index = 0
377 for field in dw.fields:
378 if type(field) is Field and field.type in self.parser.structs:
379 name = field.name + field.dim
380 print("")
381 print(" uint32_t v%d_%d;" % (index, field_index))
382 print(" %s_pack(data, &v%d_%d, &values->%s);" %
383 (self.parser.gen_prefix(safe_name(field.type)), index, field_index, name))
384 field_index = field_index + 1
385
386 print("")
387 dword_start = index * 32
388 if dw.address == None:
389 address_count = 0
390 else:
391 address_count = 1
392
393 if dw.size == 32 and dw.address == None:
394 v = None
395 print(" dw[%d] =" % index)
396 elif len(dw.fields) > address_count:
397 v = "v%d" % index
398 print(" const uint%d_t %s =" % (dw.size, v))
399 else:
400 v = "0"
401
402 field_index = 0
403 for field in dw.fields:
404 if field.type != "mbo":
405 name = field.name + field.dim
406
407 if field.type == "mbo":
408 s = "__gen_mbo(%d, %d)" % \
409 (field.start - dword_start, field.end - dword_start)
410 elif field.type == "address":
411 s = None
412 elif field.type == "uint":
413 s = "__gen_uint(values->%s, %d, %d)" % \
414 (name, field.start - dword_start, field.end - dword_start)
415 elif field.type == "int":
416 s = "__gen_sint(values->%s, %d, %d)" % \
417 (name, field.start - dword_start, field.end - dword_start)
418 elif field.type == "bool":
419 s = "__gen_uint(values->%s, %d, %d)" % \
420 (name, field.start - dword_start, field.end - dword_start)
421 elif field.type == "float":
422 s = "__gen_float(values->%s)" % name
423 elif field.type == "offset":
424 s = "__gen_offset(values->%s, %d, %d)" % \
425 (name, field.start - dword_start, field.end - dword_start)
426 elif field.type == 'ufixed':
427 s = "__gen_ufixed(values->%s, %d, %d, %d)" % \
428 (name, field.start - dword_start, field.end - dword_start, field.fractional_size)
429 elif field.type == 'sfixed':
430 s = "__gen_sfixed(values->%s, %d, %d, %d)" % \
431 (name, field.start - dword_start, field.end - dword_start, field.fractional_size)
432 elif field.type in self.parser.structs:
433 s = "__gen_uint(v%d_%d, %d, %d)" % \
434 (index, field_index, field.start - dword_start, field.end - dword_start)
435 field_index = field_index + 1
436 else:
437 print("/* unhandled field %s, type %s */\n" % (name, field.type))
438 s = None
439
440 if not s == None:
441 if field == dw.fields[-1]:
442 print(" %s;" % s)
443 else:
444 print(" %s |" % s)
445
446 if dw.size == 32:
447 if dw.address:
448 print(" dw[%d] = __gen_combine_address(data, &dw[%d], values->%s, %s);" % (index, index, dw.address.name, v))
449 continue
450
451 if dw.address:
452 v_address = "v%d_address" % index
453 print(" const uint64_t %s =\n __gen_combine_address(data, &dw[%d], values->%s, %s);" %
454 (v_address, index, dw.address.name, v))
455 v = v_address
456
457 print(" dw[%d] = %s;" % (index, v))
458 print(" dw[%d] = %s >> 32;" % (index + 1, v))
459
460 class Value:
461 def __init__(self, attrs):
462 self.name = safe_name(attrs["name"])
463 self.value = int(attrs["value"])
464
465 class Parser:
466 def __init__(self):
467 self.parser = xml.parsers.expat.ParserCreate()
468 self.parser.StartElementHandler = self.start_element
469 self.parser.EndElementHandler = self.end_element
470
471 self.instruction = None
472 self.structs = {}
473
474 def start_element(self, name, attrs):
475 if name == "genxml":
476 self.platform = attrs["name"]
477 self.gen = attrs["gen"].replace('.', '')
478 print(pack_header % {'license': license, 'platform': self.platform})
479 elif name == "instruction":
480 self.instruction = safe_name(attrs["name"])
481 self.length_bias = int(attrs["bias"])
482 if "length" in attrs:
483 self.length = int(attrs["length"])
484 size = self.length * 32
485 else:
486 self.length = None
487 size = 0
488 self.group = Group(self, None, 0, 1, size)
489 elif name == "struct":
490 self.struct = safe_name(attrs["name"])
491 self.structs[attrs["name"]] = 1
492 if "length" in attrs:
493 self.length = int(attrs["length"])
494 size = self.length * 32
495 else:
496 self.length = None
497 size = 0
498 self.group = Group(self, None, 0, 1, size)
499
500 elif name == "group":
501 group = Group(self, self.group,
502 int(attrs["start"]), int(attrs["count"]), int(attrs["size"]))
503 self.group.fields.append(group)
504 self.group = group
505 elif name == "field":
506 self.group.fields.append(Field(self, attrs))
507 self.values = []
508 elif name == "enum":
509 self.values = []
510 self.enum = safe_name(attrs["name"])
511 if "prefix" in attrs:
512 self.prefix = safe_name(attrs["prefix"])
513 else:
514 self.prefix= None
515 elif name == "value":
516 self.values.append(Value(attrs))
517
518 def end_element(self, name):
519 if name == "instruction":
520 self.emit_instruction()
521 self.instruction = None
522 self.group = None
523 elif name == "struct":
524 self.emit_struct()
525 self.struct = None
526 self.group = None
527 elif name == "group":
528 self.group = self.group.parent
529 elif name == "field":
530 self.group.fields[-1].values = self.values
531 elif name == "enum":
532 self.emit_enum()
533 self.enum = None
534
535 def gen_prefix(self, name):
536 if name[0] == "_":
537 return 'GEN%s%s' % (self.gen, name)
538 else:
539 return 'GEN%s_%s' % (self.gen, name)
540
541 def emit_template_struct(self, name, group):
542 print("struct %s {" % self.gen_prefix(name))
543 group.emit_template_struct("")
544 print("};\n")
545
546 def emit_pack_function(self, name, group):
547 name = self.gen_prefix(name)
548 print("static inline void\n%s_pack(__gen_user_data *data, void * restrict dst,\n%sconst struct %s * restrict values)\n{" %
549 (name, ' ' * (len(name) + 6), name))
550
551 # Cast dst to make header C++ friendly
552 print(" uint32_t * restrict dw = (uint32_t * restrict) dst;")
553
554 group.emit_pack_function(0)
555
556 print("}\n")
557
558 def emit_instruction(self):
559 name = self.instruction
560 if not self.length == None:
561 print('#define %-33s %4d' %
562 (self.gen_prefix(name + "_length"), self.length))
563 print('#define %-33s %4d' %
564 (self.gen_prefix(name + "_length_bias"), self.length_bias))
565
566 default_fields = []
567 for field in self.group.fields:
568 if not type(field) is Field:
569 continue
570 if field.default == None:
571 continue
572 default_fields.append(" .%-35s = %4d" % (field.name, field.default))
573
574 if default_fields:
575 print('#define %-40s\\' % (self.gen_prefix(name + '_header')))
576 print(", \\\n".join(default_fields))
577 print('')
578
579 self.emit_template_struct(self.instruction, self.group)
580
581 self.emit_pack_function(self.instruction, self.group)
582
583 def emit_struct(self):
584 name = self.struct
585 if not self.length == None:
586 print('#define %-33s %4d' %
587 (self.gen_prefix(name + "_length"), self.length))
588
589 self.emit_template_struct(self.struct, self.group)
590 self.emit_pack_function(self.struct, self.group)
591
592 def emit_enum(self):
593 print('/* enum %s */' % self.gen_prefix(self.enum))
594 for value in self.values:
595 if self.prefix:
596 name = self.prefix + "_" + value.name
597 else:
598 name = value.name
599 print('#define %-36s %4d' % (name.upper(), value.value))
600 print('')
601
602 def parse(self, filename):
603 file = open(filename, "rb")
604 self.parser.ParseFile(file)
605 file.close()
606
607 if len(sys.argv) < 2:
608 print("No input xml file specified")
609 sys.exit(1)
610
611 input_file = sys.argv[1]
612
613 p = Parser()
614 p.parse(input_file)