v3d: Pass the version being generated to the pack generator script.
[mesa.git] / src / broadcom / cle / gen_pack_header.py
1 #encoding=utf-8
2
3 # Copyright (C) 2016 Intel Corporation
4 # Copyright (C) 2016 Broadcom
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a
7 # copy of this software and associated documentation files (the "Software"),
8 # to deal in the Software without restriction, including without limitation
9 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 # and/or sell copies of the Software, and to permit persons to whom the
11 # Software is furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice (including the next
14 # paragraph) shall be included in all copies or substantial portions of the
15 # Software.
16 #
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23 # IN THE SOFTWARE.
24
25 from __future__ import (
26 absolute_import, division, print_function, unicode_literals
27 )
28 import xml.parsers.expat
29 import re
30 import sys
31 import copy
32
33 license = """/* Generated code, see packets.xml and gen_packet_header.py */
34 """
35
36 pack_header = """%(license)s
37
38 /* Packets, enums and structures for %(platform)s.
39 *
40 * This file has been generated, do not hand edit.
41 */
42
43 #ifndef %(guard)s
44 #define %(guard)s
45
46 #include "cle/v3d_packet_helpers.h"
47
48 """
49
50 def to_alphanum(name):
51 substitutions = {
52 ' ': '_',
53 '/': '_',
54 '[': '',
55 ']': '',
56 '(': '',
57 ')': '',
58 '-': '_',
59 ':': '',
60 '.': '',
61 ',': '',
62 '=': '',
63 '>': '',
64 '#': '',
65 'α': 'alpha',
66 '&': '',
67 '*': '',
68 '"': '',
69 '+': '',
70 '\'': '',
71 }
72
73 for i, j in substitutions.items():
74 name = name.replace(i, j)
75
76 return name
77
78 def safe_name(name):
79 name = to_alphanum(name)
80 if not name[0].isalpha():
81 name = '_' + name
82
83 return name
84
85 def prefixed_upper_name(prefix, name):
86 if prefix:
87 name = prefix + "_" + name
88 return safe_name(name).upper()
89
90 def num_from_str(num_str):
91 if num_str.lower().startswith('0x'):
92 return int(num_str, base=16)
93 else:
94 assert(not num_str.startswith('0') and 'octals numbers not allowed')
95 return int(num_str)
96
97 class Field(object):
98 ufixed_pattern = re.compile(r"u(\d+)\.(\d+)")
99 sfixed_pattern = re.compile(r"s(\d+)\.(\d+)")
100
101 def __init__(self, parser, attrs):
102 self.parser = parser
103 if "name" in attrs:
104 self.name = safe_name(attrs["name"]).lower()
105
106 if str(attrs["start"]).endswith("b"):
107 self.start = int(attrs["start"][:-1]) * 8
108 else:
109 self.start = int(attrs["start"])
110 # packet <field> entries in XML start from the bit after the
111 # opcode, so shift everything up by 8 since we'll also have a
112 # Field for the opcode.
113 if not parser.struct:
114 self.start += 8
115
116 self.end = self.start + int(attrs["size"]) - 1
117 self.type = attrs["type"]
118
119 if self.type == 'bool' and self.start != self.end:
120 print("#error Field {} has bool type but more than one bit of size".format(self.name));
121
122 if "prefix" in attrs:
123 self.prefix = safe_name(attrs["prefix"]).upper()
124 else:
125 self.prefix = None
126
127 if "default" in attrs:
128 self.default = int(attrs["default"])
129 else:
130 self.default = None
131
132 if "minus_one" in attrs:
133 assert(attrs["minus_one"] == "true")
134 self.minus_one = True
135 else:
136 self.minus_one = False
137
138 ufixed_match = Field.ufixed_pattern.match(self.type)
139 if ufixed_match:
140 self.type = 'ufixed'
141 self.fractional_size = int(ufixed_match.group(2))
142
143 sfixed_match = Field.sfixed_pattern.match(self.type)
144 if sfixed_match:
145 self.type = 'sfixed'
146 self.fractional_size = int(sfixed_match.group(2))
147
148 def emit_template_struct(self, dim):
149 if self.type == 'address':
150 type = '__gen_address_type'
151 elif self.type == 'bool':
152 type = 'bool'
153 elif self.type == 'float':
154 type = 'float'
155 elif self.type == 'ufixed':
156 type = 'float'
157 elif self.type == 'sfixed':
158 type = 'float'
159 elif self.type == 'uint' and self.end - self.start > 32:
160 type = 'uint64_t'
161 elif self.type == 'offset':
162 type = 'uint64_t'
163 elif self.type == 'int':
164 type = 'int32_t'
165 elif self.type == 'uint':
166 type = 'uint32_t'
167 elif self.type in self.parser.structs:
168 type = 'struct ' + self.parser.gen_prefix(safe_name(self.type))
169 elif self.type in self.parser.enums:
170 type = 'enum ' + self.parser.gen_prefix(safe_name(self.type))
171 elif self.type == 'mbo':
172 return
173 else:
174 print("#error unhandled type: %s" % self.type)
175 type = "uint32_t"
176
177 print(" %-36s %s%s;" % (type, self.name, dim))
178
179 for value in self.values:
180 name = prefixed_upper_name(self.prefix, value.name)
181 print("#define %-40s %d" % (name, value.value))
182
183 def overlaps(self, field):
184 return self != field and max(self.start, field.start) <= min(self.end, field.end)
185
186
187 class Group(object):
188 def __init__(self, parser, parent, start, count):
189 self.parser = parser
190 self.parent = parent
191 self.start = start
192 self.count = count
193 self.size = 0
194 self.fields = []
195
196 def emit_template_struct(self, dim):
197 if self.count == 0:
198 print(" /* variable length fields follow */")
199 else:
200 if self.count > 1:
201 dim = "%s[%d]" % (dim, self.count)
202
203 for field in self.fields:
204 field.emit_template_struct(dim)
205
206 class Byte:
207 def __init__(self):
208 self.size = 8
209 self.fields = []
210 self.address = None
211
212 def collect_bytes(self, bytes):
213 for field in self.fields:
214 first_byte = field.start // 8
215 last_byte = field.end // 8
216
217 for b in xrange(first_byte, last_byte + 1):
218 if not b in bytes:
219 bytes[b] = self.Byte()
220
221 bytes[b].fields.append(field)
222
223 if field.type == "address":
224 # assert bytes[index].address == None
225 bytes[b].address = field
226
227 def emit_pack_function(self, start):
228 # Determine number of bytes in this group.
229 self.length = max(field.end // 8 for field in self.fields) + 1
230
231 bytes = {}
232 self.collect_bytes(bytes)
233
234 relocs_emitted = set()
235 memcpy_fields = set()
236
237 for field in self.fields:
238 if field.minus_one:
239 print(" assert(values->%s >= 1);" % field.name)
240
241 for index in range(self.length):
242 # Handle MBZ bytes
243 if not index in bytes:
244 print(" cl[%2d] = 0;" % index)
245 continue
246 byte = bytes[index]
247
248 # Call out to the driver to note our relocations. Inside of the
249 # packet we only store offsets within the BOs, and we store the
250 # handle to the packet outside. Unlike Intel genxml, we don't
251 # need to have the other bits that will be stored together with
252 # the address during the reloc process, so there's no need for the
253 # complicated combine_address() function.
254 if byte.address and byte.address not in relocs_emitted:
255 print(" __gen_emit_reloc(data, &values->%s);" % byte.address.name)
256 relocs_emitted.add(byte.address)
257
258 # Special case: floats can't have any other fields packed into
259 # them (since they'd change the meaning of the float), and the
260 # per-byte bitshifting math below bloats the pack code for floats,
261 # so just copy them directly here. Also handle 16/32-bit
262 # uints/ints with no merged fields.
263 if len(byte.fields) == 1:
264 field = byte.fields[0]
265 if field.type in ["float", "uint", "int"] and field.start % 8 == 0 and field.end - field.start == 31 and not field.minus_one:
266 if field in memcpy_fields:
267 continue
268
269 if not any(field.overlaps(scan_field) for scan_field in self.fields):
270 assert(field.start == index * 8)
271 print("")
272 print(" memcpy(&cl[%d], &values->%s, sizeof(values->%s));" %
273 (index, field.name, field.name))
274 memcpy_fields.add(field)
275 continue
276
277 byte_start = index * 8
278
279 v = None
280 prefix = " cl[%2d] =" % index
281
282 field_index = 0
283 for field in byte.fields:
284 if field.type != "mbo":
285 name = field.name
286
287 start = field.start
288 end = field.end
289 field_byte_start = (field.start // 8) * 8
290 start -= field_byte_start
291 end -= field_byte_start
292 extra_shift = 0
293
294 value = "values->%s" % name
295 if field.minus_one:
296 value = "%s - 1" % value
297
298 if field.type == "mbo":
299 s = "__gen_mbo(%d, %d)" % \
300 (start, end)
301 elif field.type == "address":
302 extra_shift = (31 - (end - start)) // 8 * 8
303 s = "__gen_address_offset(&values->%s)" % byte.address.name
304 elif field.type == "uint":
305 s = "__gen_uint(%s, %d, %d)" % \
306 (value, start, end)
307 elif field.type in self.parser.enums:
308 s = "__gen_uint(%s, %d, %d)" % \
309 (value, start, end)
310 elif field.type == "int":
311 s = "__gen_sint(%s, %d, %d)" % \
312 (value, start, end)
313 elif field.type == "bool":
314 s = "__gen_uint(%s, %d, %d)" % \
315 (value, start, end)
316 elif field.type == "float":
317 s = "#error %s float value mixed in with other fields" % name
318 elif field.type == "offset":
319 s = "__gen_offset(%s, %d, %d)" % \
320 (value, start, end)
321 elif field.type == 'ufixed':
322 s = "__gen_ufixed(%s, %d, %d, %d)" % \
323 (value, start, end, field.fractional_size)
324 elif field.type == 'sfixed':
325 s = "__gen_sfixed(%s, %d, %d, %d)" % \
326 (value, start, end, field.fractional_size)
327 elif field.type in self.parser.structs:
328 s = "__gen_uint(v%d_%d, %d, %d)" % \
329 (index, field_index, start, end)
330 field_index = field_index + 1
331 else:
332 print("/* unhandled field %s, type %s */\n" % (name, field.type))
333 s = None
334
335 if not s == None:
336 shift = byte_start - field_byte_start + extra_shift
337 if shift:
338 s = "%s >> %d" % (s, shift)
339
340 if field == byte.fields[-1]:
341 print("%s %s;" % (prefix, s))
342 else:
343 print("%s %s |" % (prefix, s))
344 prefix = " "
345
346 print("")
347 continue
348
349 def emit_unpack_function(self, start):
350 for field in self.fields:
351 if field.type != "mbo":
352 convert = None
353
354 args = []
355 args.append('cl')
356 args.append(str(start + field.start))
357 args.append(str(start + field.end))
358
359 if field.type == "address":
360 convert = "__gen_unpack_address"
361 elif field.type == "uint":
362 convert = "__gen_unpack_uint"
363 elif field.type in self.parser.enums:
364 convert = "__gen_unpack_uint"
365 elif field.type == "int":
366 convert = "__gen_unpack_sint"
367 elif field.type == "bool":
368 convert = "__gen_unpack_uint"
369 elif field.type == "float":
370 convert = "__gen_unpack_float"
371 elif field.type == "offset":
372 convert = "__gen_unpack_offset"
373 elif field.type == 'ufixed':
374 args.append(str(field.fractional_size))
375 convert = "__gen_unpack_ufixed"
376 elif field.type == 'sfixed':
377 args.append(str(field.fractional_size))
378 convert = "__gen_unpack_sfixed"
379 else:
380 print("/* unhandled field %s, type %s */\n" % (field.name, field.type))
381 s = None
382
383 plusone = ""
384 if field.minus_one:
385 plusone = " + 1"
386 print(" values->%s = %s(%s)%s;" % \
387 (field.name, convert, ', '.join(args), plusone))
388
389 class Value(object):
390 def __init__(self, attrs):
391 self.name = attrs["name"]
392 self.value = int(attrs["value"])
393
394 class Parser(object):
395 def __init__(self, ver):
396 self.parser = xml.parsers.expat.ParserCreate()
397 self.parser.StartElementHandler = self.start_element
398 self.parser.EndElementHandler = self.end_element
399
400 self.packet = None
401 self.struct = None
402 self.structs = {}
403 # Set of enum names we've seen.
404 self.enums = set()
405 self.registers = {}
406 self.ver = ver
407
408 def gen_prefix(self, name):
409 if name[0] == "_":
410 return 'V3D%s%s' % (self.ver, name)
411 else:
412 return 'V3D%s_%s' % (self.ver, name)
413
414 def gen_guard(self):
415 return self.gen_prefix("PACK_H")
416
417 def start_element(self, name, attrs):
418 if name == "vcxml":
419 self.platform = "V3D {}.{}".format(self.ver[0], self.ver[1])
420 print(pack_header % {'license': license, 'platform': self.platform, 'guard': self.gen_guard()})
421 elif name in ("packet", "struct", "register"):
422 default_field = None
423
424 object_name = self.gen_prefix(safe_name(attrs["name"].upper()))
425 if name == "packet":
426 self.packet = object_name
427
428 # Add a fixed Field for the opcode. We only make <field>s in
429 # the XML for the fields listed in the spec, and all of those
430 # start from bit 0 after of the opcode.
431 default_field = {
432 "name" : "opcode",
433 "default" : attrs["code"],
434 "type" : "uint",
435 "start" : -8,
436 "size" : 8,
437 }
438 elif name == "struct":
439 self.struct = object_name
440 self.structs[attrs["name"]] = 1
441 elif name == "register":
442 self.register = object_name
443 self.reg_num = num_from_str(attrs["num"])
444 self.registers[attrs["name"]] = 1
445
446 self.group = Group(self, None, 0, 1)
447 if default_field:
448 field = Field(self, default_field)
449 field.values = []
450 self.group.fields.append(field)
451
452 elif name == "field":
453 self.group.fields.append(Field(self, attrs))
454 self.values = []
455 elif name == "enum":
456 self.values = []
457 self.enum = safe_name(attrs["name"])
458 self.enums.add(attrs["name"])
459 if "prefix" in attrs:
460 self.prefix = attrs["prefix"]
461 else:
462 self.prefix= None
463 elif name == "value":
464 self.values.append(Value(attrs))
465
466 def end_element(self, name):
467 if name == "packet":
468 self.emit_packet()
469 self.packet = None
470 self.group = None
471 elif name == "struct":
472 self.emit_struct()
473 self.struct = None
474 self.group = None
475 elif name == "register":
476 self.emit_register()
477 self.register = None
478 self.reg_num = None
479 self.group = None
480 elif name == "field":
481 self.group.fields[-1].values = self.values
482 elif name == "enum":
483 self.emit_enum()
484 self.enum = None
485 elif name == "vcxml":
486 print('#endif /* %s */' % self.gen_guard())
487
488 def emit_template_struct(self, name, group):
489 print("struct %s {" % name)
490 group.emit_template_struct("")
491 print("};\n")
492
493 def emit_pack_function(self, name, group):
494 print("static inline void\n%s_pack(__gen_user_data *data, uint8_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
495 (name, ' ' * (len(name) + 6), name))
496
497 group.emit_pack_function(0)
498
499 print("}\n")
500
501 print('#define %-33s %6d' %
502 (name + "_length", self.group.length))
503
504 def emit_unpack_function(self, name, group):
505 print("#ifdef __gen_unpack_address")
506 print("static inline void")
507 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
508 (name, ' ' * (len(name) + 8), name))
509
510 group.emit_unpack_function(0)
511
512 print("}\n#endif\n")
513
514 def emit_header(self, name):
515 default_fields = []
516 for field in self.group.fields:
517 if not type(field) is Field:
518 continue
519 if field.default == None:
520 continue
521 default_fields.append(" .%-35s = %6d" % (field.name, field.default))
522
523 print('#define %-40s\\' % (name + '_header'))
524 print(", \\\n".join(default_fields))
525 print('')
526
527 def emit_packet(self):
528 name = self.packet
529
530 assert(self.group.fields[0].name == "opcode")
531 print('#define %-33s %6d' %
532 (name + "_opcode", self.group.fields[0].default))
533
534 self.emit_header(name)
535 self.emit_template_struct(self.packet, self.group)
536 self.emit_pack_function(self.packet, self.group)
537 self.emit_unpack_function(self.packet, self.group)
538
539 print('')
540
541 def emit_register(self):
542 name = self.register
543 if not self.reg_num == None:
544 print('#define %-33s 0x%04x' %
545 (self.gen_prefix(name + "_num"), self.reg_num))
546
547 self.emit_template_struct(self.register, self.group)
548 self.emit_pack_function(self.register, self.group)
549 self.emit_unpack_function(self.register, self.group)
550
551 def emit_struct(self):
552 name = self.struct
553
554 self.emit_header(name)
555 self.emit_template_struct(self.struct, self.group)
556 self.emit_pack_function(self.struct, self.group)
557 self.emit_unpack_function(self.struct, self.group)
558
559 print('')
560
561 def emit_enum(self):
562 print('enum %s {' % self.gen_prefix(self.enum))
563 for value in self.values:
564 name = value.name
565 if self.prefix:
566 name = self.prefix + "_" + name
567 name = safe_name(name).upper()
568 print(' % -36s = %6d,' % (name, value.value))
569 print('};\n')
570
571 def parse(self, filename):
572 file = open(filename, "rb")
573 self.parser.ParseFile(file)
574 file.close()
575
576 if len(sys.argv) < 2:
577 print("No input xml file specified")
578 sys.exit(1)
579
580 input_file = sys.argv[1]
581
582 p = Parser(sys.argv[2])
583 p.parse(input_file)