75c4f269cdd3e903e482d3174c2014d69924cf56
[mesa.git] / src / intel / genxml / 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 __gen_validate_value(v);
66
67 #if DEBUG
68 const int width = end - start + 1;
69 if (width < 64) {
70 const uint64_t max = (1ull << width) - 1;
71 assert(v <= max);
72 }
73 #endif
74
75 return v << start;
76 }
77
78 static inline uint64_t
79 __gen_sint(int64_t v, uint32_t start, uint32_t end)
80 {
81 const int width = end - start + 1;
82
83 __gen_validate_value(v);
84
85 #if DEBUG
86 if (width < 64) {
87 const int64_t max = (1ll << (width - 1)) - 1;
88 const int64_t min = -(1ll << (width - 1));
89 assert(min <= v && v <= max);
90 }
91 #endif
92
93 const uint64_t mask = ~0ull >> (64 - width);
94
95 return (v & mask) << start;
96 }
97
98 static inline uint64_t
99 __gen_offset(uint64_t v, uint32_t start, uint32_t end)
100 {
101 __gen_validate_value(v);
102 #if DEBUG
103 uint64_t mask = (~0ull >> (64 - (end - start + 1))) << start;
104
105 assert((v & ~mask) == 0);
106 #endif
107
108 return v;
109 }
110
111 static inline uint32_t
112 __gen_float(float v)
113 {
114 __gen_validate_value(v);
115 return ((union __gen_value) { .f = (v) }).dw;
116 }
117
118 static inline uint64_t
119 __gen_sfixed(float v, uint32_t start, uint32_t end, uint32_t fract_bits)
120 {
121 __gen_validate_value(v);
122
123 const float factor = (1 << fract_bits);
124
125 #if DEBUG
126 const float max = ((1 << (end - start)) - 1) / factor;
127 const float min = -(1 << (end - start)) / factor;
128 assert(min <= v && v <= max);
129 #endif
130
131 const int32_t int_val = roundf(v * factor);
132 const uint64_t mask = ~0ull >> (64 - (end - start + 1));
133
134 return (int_val & mask) << start;
135 }
136
137 static inline uint64_t
138 __gen_ufixed(float v, uint32_t start, uint32_t end, uint32_t fract_bits)
139 {
140 __gen_validate_value(v);
141
142 const float factor = (1 << fract_bits);
143
144 #if DEBUG
145 const float max = ((1 << (end - start + 1)) - 1) / factor;
146 const float min = 0.0f;
147 assert(min <= v && v <= max);
148 #endif
149
150 const uint32_t uint_val = roundf(v * factor);
151
152 return uint_val << start;
153 }
154
155 #ifndef __gen_address_type
156 #error #define __gen_address_type before including this file
157 #endif
158
159 #ifndef __gen_user_data
160 #error #define __gen_combine_address before including this file
161 #endif
162
163 #endif
164
165 """
166
167 def to_alphanum(name):
168 substitutions = {
169 ' ': '',
170 '/': '',
171 '[': '',
172 ']': '',
173 '(': '',
174 ')': '',
175 '-': '',
176 ':': '',
177 '.': '',
178 ',': '',
179 '=': '',
180 '>': '',
181 '#': '',
182 'α': 'alpha',
183 '&': '',
184 '*': '',
185 '"': '',
186 '+': '',
187 '\'': '',
188 }
189
190 for i, j in substitutions.items():
191 name = name.replace(i, j)
192
193 return name
194
195 def safe_name(name):
196 name = to_alphanum(name)
197 if not str.isalpha(name[0]):
198 name = '_' + name
199
200 return name
201
202 class Field:
203 ufixed_pattern = re.compile("u(\d+)\.(\d+)")
204 sfixed_pattern = re.compile("s(\d+)\.(\d+)")
205
206 def __init__(self, parser, attrs):
207 self.parser = parser
208 if "name" in attrs:
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 elif self.type == 'mbo':
256 return
257 else:
258 print("#error unhandled type: %s" % self.type)
259
260 print(" %-36s %s%s;" % (type, self.name, dim))
261
262 if len(self.values) > 0 and self.default == None:
263 if self.prefix:
264 prefix = self.prefix + "_"
265 else:
266 prefix = ""
267
268 for value in self.values:
269 print("#define %-40s %d" % (prefix + value.name, value.value))
270
271 class Group:
272 def __init__(self, parser, parent, start, count, size):
273 self.parser = parser
274 self.parent = parent
275 self.start = start
276 self.count = count
277 self.size = size
278 self.fields = []
279
280 def emit_template_struct(self, dim):
281 if self.count == 0:
282 print(" /* variable length fields follow */")
283 else:
284 if self.count > 1:
285 dim = "%s[%d]" % (dim, self.count)
286
287 for field in self.fields:
288 field.emit_template_struct(dim)
289
290 class DWord:
291 def __init__(self):
292 self.size = 32
293 self.fields = []
294 self.address = None
295
296 def collect_dwords(self, dwords, start, dim):
297 for field in self.fields:
298 if type(field) is Group:
299 if field.count == 1:
300 field.collect_dwords(dwords, start + field.start, dim)
301 else:
302 for i in range(field.count):
303 field.collect_dwords(dwords,
304 start + field.start + i * field.size,
305 "%s[%d]" % (dim, i))
306 continue
307
308 index = (start + field.start) // 32
309 if not index in dwords:
310 dwords[index] = self.DWord()
311
312 clone = copy.copy(field)
313 clone.start = clone.start + start
314 clone.end = clone.end + start
315 clone.dim = dim
316 dwords[index].fields.append(clone)
317
318 if field.type == "address":
319 # assert dwords[index].address == None
320 dwords[index].address = field
321
322 # Coalesce all the dwords covered by this field. The two cases we
323 # handle are where multiple fields are in a 64 bit word (typically
324 # and address and a few bits) or where a single struct field
325 # completely covers multiple dwords.
326 while index < (start + field.end) // 32:
327 if index + 1 in dwords and not dwords[index] == dwords[index + 1]:
328 dwords[index].fields.extend(dwords[index + 1].fields)
329 dwords[index].size = 64
330 dwords[index + 1] = dwords[index]
331 index = index + 1
332
333 def emit_pack_function(self, start):
334 dwords = {}
335 self.collect_dwords(dwords, 0, "")
336
337 # Determine number of dwords in this group. If we have a size, use
338 # that, since that'll account for MBZ dwords at the end of a group
339 # (like dword 8 on BDW+ 3DSTATE_HS). Otherwise, use the largest dword
340 # index we've seen plus one.
341 if self.size > 0:
342 length = self.size // 32
343 else:
344 length = max(dwords.keys()) + 1
345
346 for index in range(length):
347 # Handle MBZ dwords
348 if not index in dwords:
349 print("")
350 print(" dw[%d] = 0;" % index)
351 continue
352
353 # For 64 bit dwords, we aliased the two dword entries in the dword
354 # dict it occupies. Now that we're emitting the pack function,
355 # skip the duplicate entries.
356 dw = dwords[index]
357 if index > 0 and index - 1 in dwords and dw == dwords[index - 1]:
358 continue
359
360 # Special case: only one field and it's a struct at the beginning
361 # of the dword. In this case we pack directly into the
362 # destination. This is the only way we handle embedded structs
363 # larger than 32 bits.
364 if len(dw.fields) == 1:
365 field = dw.fields[0]
366 name = field.name + field.dim
367 if field.type in self.parser.structs and field.start % 32 == 0:
368 print("")
369 print(" %s_pack(data, &dw[%d], &values->%s);" %
370 (self.parser.gen_prefix(safe_name(field.type)), index, name))
371 continue
372
373 # Pack any fields of struct type first so we have integer values
374 # to the dword for those fields.
375 field_index = 0
376 for field in dw.fields:
377 if type(field) is Field and field.type in self.parser.structs:
378 name = field.name + field.dim
379 print("")
380 print(" uint32_t v%d_%d;" % (index, field_index))
381 print(" %s_pack(data, &v%d_%d, &values->%s);" %
382 (self.parser.gen_prefix(safe_name(field.type)), index, field_index, name))
383 field_index = field_index + 1
384
385 print("")
386 dword_start = index * 32
387 if dw.address == None:
388 address_count = 0
389 else:
390 address_count = 1
391
392 if dw.size == 32 and dw.address == None:
393 v = None
394 print(" dw[%d] =" % index)
395 elif len(dw.fields) > address_count:
396 v = "v%d" % index
397 print(" const uint%d_t %s =" % (dw.size, v))
398 else:
399 v = "0"
400
401 field_index = 0
402 for field in dw.fields:
403 if field.type != "mbo":
404 name = field.name + field.dim
405
406 if field.type == "mbo":
407 s = "__gen_mbo(%d, %d)" % \
408 (field.start - dword_start, field.end - dword_start)
409 elif field.type == "address":
410 s = None
411 elif field.type == "uint":
412 s = "__gen_uint(values->%s, %d, %d)" % \
413 (name, field.start - dword_start, field.end - dword_start)
414 elif field.type == "int":
415 s = "__gen_sint(values->%s, %d, %d)" % \
416 (name, field.start - dword_start, field.end - dword_start)
417 elif field.type == "bool":
418 s = "__gen_uint(values->%s, %d, %d)" % \
419 (name, field.start - dword_start, field.end - dword_start)
420 elif field.type == "float":
421 s = "__gen_float(values->%s)" % name
422 elif field.type == "offset":
423 s = "__gen_offset(values->%s, %d, %d)" % \
424 (name, field.start - dword_start, field.end - dword_start)
425 elif field.type == 'ufixed':
426 s = "__gen_ufixed(values->%s, %d, %d, %d)" % \
427 (name, field.start - dword_start, field.end - dword_start, field.fractional_size)
428 elif field.type == 'sfixed':
429 s = "__gen_sfixed(values->%s, %d, %d, %d)" % \
430 (name, field.start - dword_start, field.end - dword_start, field.fractional_size)
431 elif field.type in self.parser.structs:
432 s = "__gen_uint(v%d_%d, %d, %d)" % \
433 (index, field_index, field.start - dword_start, field.end - dword_start)
434 field_index = field_index + 1
435 else:
436 print("/* unhandled field %s, type %s */\n" % (name, field.type))
437 s = None
438
439 if not s == None:
440 if field == dw.fields[-1]:
441 print(" %s;" % s)
442 else:
443 print(" %s |" % s)
444
445 if dw.size == 32:
446 if dw.address:
447 print(" dw[%d] = __gen_combine_address(data, &dw[%d], values->%s, %s);" % (index, index, dw.address.name, v))
448 continue
449
450 if dw.address:
451 v_address = "v%d_address" % index
452 print(" const uint64_t %s =\n __gen_combine_address(data, &dw[%d], values->%s, %s);" %
453 (v_address, index, dw.address.name, v))
454 v = v_address
455
456 print(" dw[%d] = %s;" % (index, v))
457 print(" dw[%d] = %s >> 32;" % (index + 1, v))
458
459 class Value:
460 def __init__(self, attrs):
461 self.name = safe_name(attrs["name"])
462 self.value = int(attrs["value"])
463
464 class Parser:
465 def __init__(self):
466 self.parser = xml.parsers.expat.ParserCreate()
467 self.parser.StartElementHandler = self.start_element
468 self.parser.EndElementHandler = self.end_element
469
470 self.instruction = None
471 self.structs = {}
472
473 def start_element(self, name, attrs):
474 if name == "genxml":
475 self.platform = attrs["name"]
476 self.gen = attrs["gen"].replace('.', '')
477 print(pack_header % {'license': license, 'platform': self.platform})
478 elif name == "instruction":
479 self.instruction = safe_name(attrs["name"])
480 self.length_bias = int(attrs["bias"])
481 if "length" in attrs:
482 self.length = int(attrs["length"])
483 size = self.length * 32
484 else:
485 self.length = None
486 size = 0
487 self.group = Group(self, None, 0, 1, size)
488 elif name == "struct":
489 self.struct = safe_name(attrs["name"])
490 self.structs[attrs["name"]] = 1
491 if "length" in attrs:
492 self.length = int(attrs["length"])
493 size = self.length * 32
494 else:
495 self.length = None
496 size = 0
497 self.group = Group(self, None, 0, 1, size)
498
499 elif name == "group":
500 group = Group(self, self.group,
501 int(attrs["start"]), int(attrs["count"]), int(attrs["size"]))
502 self.group.fields.append(group)
503 self.group = group
504 elif name == "field":
505 self.group.fields.append(Field(self, attrs))
506 self.values = []
507 elif name == "enum":
508 self.values = []
509 self.enum = safe_name(attrs["name"])
510 if "prefix" in attrs:
511 self.prefix = safe_name(attrs["prefix"])
512 else:
513 self.prefix= None
514 elif name == "value":
515 self.values.append(Value(attrs))
516
517 def end_element(self, name):
518 if name == "instruction":
519 self.emit_instruction()
520 self.instruction = None
521 self.group = None
522 elif name == "struct":
523 self.emit_struct()
524 self.struct = None
525 self.group = None
526 elif name == "group":
527 self.group = self.group.parent
528 elif name == "field":
529 self.group.fields[-1].values = self.values
530 elif name == "enum":
531 self.emit_enum()
532 self.enum = None
533
534 def gen_prefix(self, name):
535 if name[0] == "_":
536 return 'GEN%s%s' % (self.gen, name)
537 else:
538 return 'GEN%s_%s' % (self.gen, name)
539
540 def emit_template_struct(self, name, group):
541 print("struct %s {" % self.gen_prefix(name))
542 group.emit_template_struct("")
543 print("};\n")
544
545 def emit_pack_function(self, name, group):
546 name = self.gen_prefix(name)
547 print("static inline void\n%s_pack(__gen_user_data *data, void * restrict dst,\n%sconst struct %s * restrict values)\n{" %
548 (name, ' ' * (len(name) + 6), name))
549
550 # Cast dst to make header C++ friendly
551 print(" uint32_t * restrict dw = (uint32_t * restrict) dst;")
552
553 group.emit_pack_function(0)
554
555 print("}\n")
556
557 def emit_instruction(self):
558 name = self.instruction
559 if not self.length == None:
560 print('#define %-33s %4d' %
561 (self.gen_prefix(name + "_length"), self.length))
562 print('#define %-33s %4d' %
563 (self.gen_prefix(name + "_length_bias"), self.length_bias))
564
565 default_fields = []
566 for field in self.group.fields:
567 if not type(field) is Field:
568 continue
569 if field.default == None:
570 continue
571 default_fields.append(" .%-35s = %4d" % (field.name, field.default))
572
573 if default_fields:
574 print('#define %-40s\\' % (self.gen_prefix(name + '_header')))
575 print(", \\\n".join(default_fields))
576 print('')
577
578 self.emit_template_struct(self.instruction, self.group)
579
580 self.emit_pack_function(self.instruction, self.group)
581
582 def emit_struct(self):
583 name = self.struct
584 if not self.length == None:
585 print('#define %-33s %4d' %
586 (self.gen_prefix(name + "_length"), self.length))
587
588 self.emit_template_struct(self.struct, self.group)
589 self.emit_pack_function(self.struct, self.group)
590
591 def emit_enum(self):
592 print('/* enum %s */' % self.gen_prefix(self.enum))
593 for value in self.values:
594 if self.prefix:
595 name = self.prefix + "_" + value.name
596 else:
597 name = value.name
598 print('#define %-36s %4d' % (name.upper(), value.value))
599 print('')
600
601 def parse(self, filename):
602 file = open(filename, "rb")
603 self.parser.ParseFile(file)
604 file.close()
605
606 if len(sys.argv) < 2:
607 print("No input xml file specified")
608 sys.exit(1)
609
610 input_file = sys.argv[1]
611
612 p = Parser()
613 p.parse(input_file)