anv: fix up dynamic clip emission
[mesa.git] / src / intel / genxml / gen_bits_header.py
1 #encoding=utf-8
2 # Copyright © 2017 Intel Corporation
3
4 # Permission is hereby granted, free of charge, to any person obtaining a copy
5 # of this software and associated documentation files (the "Software"), to deal
6 # in the Software without restriction, including without limitation the rights
7 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 # copies of the Software, and to permit persons to whom the Software is
9 # furnished to do so, subject to the following conditions:
10
11 # The above copyright notice and this permission notice shall be included in
12 # all copies or substantial portions of the Software.
13
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 # SOFTWARE.
21
22 from __future__ import (
23 absolute_import, division, print_function, unicode_literals
24 )
25
26 import argparse
27 import os
28 import xml.parsers.expat
29
30 from mako.template import Template
31 from util import *
32
33 TEMPLATE = Template("""\
34 <%!
35 from operator import itemgetter
36 %>\
37 /*
38 * Copyright © 2017 Intel Corporation
39 *
40 * Permission is hereby granted, free of charge, to any person obtaining a
41 * copy of this software and associated documentation files (the "Software"),
42 * to deal in the Software without restriction, including without limitation
43 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
44 * and/or sell copies of the Software, and to permit persons to whom the
45 * Software is furnished to do so, subject to the following conditions:
46 *
47 * The above copyright notice and this permission notice (including the next
48 * paragraph) shall be included in all copies or substantial portions of the
49 * Software.
50 *
51 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
52 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
53 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
54 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
55 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
56 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
57 * IN THE SOFTWARE.
58 */
59
60 /* THIS FILE HAS BEEN GENERATED, DO NOT HAND EDIT.
61 *
62 * Sizes of bitfields in genxml instructions, structures, and registers.
63 */
64
65 #ifndef ${guard}
66 #define ${guard}
67
68 #include <stdint.h>
69
70 #include "dev/gen_device_info.h"
71 #include "util/macros.h"
72
73 <%def name="emit_per_gen_prop_func(item, prop)">
74 %if item.has_prop(prop):
75 % for gen, value in sorted(item.iter_prop(prop), reverse=True):
76 #define ${gen.prefix(item.token_name)}_${prop} ${value}
77 % endfor
78
79 static inline uint32_t ATTRIBUTE_PURE
80 ${item.token_name}_${prop}(const struct gen_device_info *devinfo)
81 {
82 switch (devinfo->gen) {
83 case 12: return ${item.get_prop(prop, 12)};
84 case 11: return ${item.get_prop(prop, 11)};
85 case 10: return ${item.get_prop(prop, 10)};
86 case 9: return ${item.get_prop(prop, 9)};
87 case 8: return ${item.get_prop(prop, 8)};
88 case 7:
89 if (devinfo->is_haswell) {
90 return ${item.get_prop(prop, 7.5)};
91 } else {
92 return ${item.get_prop(prop, 7)};
93 }
94 case 6: return ${item.get_prop(prop, 6)};
95 case 5: return ${item.get_prop(prop, 5)};
96 case 4:
97 if (devinfo->is_g4x) {
98 return ${item.get_prop(prop, 4.5)};
99 } else {
100 return ${item.get_prop(prop, 4)};
101 }
102 default:
103 unreachable("Invalid hardware generation");
104 }
105 }
106 %endif
107 </%def>
108
109 #ifdef __cplusplus
110 extern "C" {
111 #endif
112 % for _, container in sorted(containers.items(), key=itemgetter(0)):
113
114 /* ${container.name} */
115
116 ${emit_per_gen_prop_func(container, 'length')}
117
118 % for _, field in sorted(container.fields.items(), key=itemgetter(0)):
119
120 /* ${container.name}::${field.name} */
121
122 ${emit_per_gen_prop_func(field, 'bits')}
123
124 ${emit_per_gen_prop_func(field, 'start')}
125
126 % endfor
127 % endfor
128
129 #ifdef __cplusplus
130 }
131 #endif
132
133 #endif /* ${guard} */""", output_encoding='utf-8')
134
135 class Gen(object):
136
137 def __init__(self, z):
138 # Convert potential "major.minor" string
139 self.tenx = int(float(z) * 10)
140
141 def __lt__(self, other):
142 return self.tenx < other.tenx
143
144 def __hash__(self):
145 return hash(self.tenx)
146
147 def __eq__(self, other):
148 return self.tenx == other.tenx
149
150 def prefix(self, token):
151 gen = self.tenx
152
153 if gen % 10 == 0:
154 gen //= 10
155
156 if token[0] == '_':
157 token = token[1:]
158
159 return 'GEN{}_{}'.format(gen, token)
160
161 class Container(object):
162
163 def __init__(self, name):
164 self.name = name
165 self.token_name = safe_name(name)
166 self.length_by_gen = {}
167 self.fields = {}
168
169 def add_gen(self, gen, xml_attrs):
170 assert isinstance(gen, Gen)
171 if 'length' in xml_attrs:
172 self.length_by_gen[gen] = xml_attrs['length']
173
174 def get_field(self, field_name, create=False):
175 key = to_alphanum(field_name)
176 if key not in self.fields:
177 if create:
178 self.fields[key] = Field(self, field_name)
179 else:
180 return None
181 return self.fields[key]
182
183 def has_prop(self, prop):
184 if prop == 'length':
185 return bool(self.length_by_gen)
186 else:
187 raise ValueError('Invalid property: "{0}"'.format(prop))
188
189 def iter_prop(self, prop):
190 if prop == 'length':
191 return self.length_by_gen.items()
192 else:
193 raise ValueError('Invalid property: "{0}"'.format(prop))
194
195 def get_prop(self, prop, gen):
196 if not isinstance(gen, Gen):
197 gen = Gen(gen)
198
199 if prop == 'length':
200 return self.length_by_gen.get(gen, 0)
201 else:
202 raise ValueError('Invalid property: "{0}"'.format(prop))
203
204 class Field(object):
205
206 def __init__(self, container, name):
207 self.name = name
208 self.token_name = safe_name('_'.join([container.name, self.name]))
209 self.bits_by_gen = {}
210 self.start_by_gen = {}
211
212 def add_gen(self, gen, xml_attrs):
213 assert isinstance(gen, Gen)
214 start = int(xml_attrs['start'])
215 end = int(xml_attrs['end'])
216 self.start_by_gen[gen] = start
217 self.bits_by_gen[gen] = 1 + end - start
218
219 def has_prop(self, prop):
220 return True
221
222 def iter_prop(self, prop):
223 if prop == 'bits':
224 return self.bits_by_gen.items()
225 elif prop == 'start':
226 return self.start_by_gen.items()
227 else:
228 raise ValueError('Invalid property: "{0}"'.format(prop))
229
230 def get_prop(self, prop, gen):
231 if not isinstance(gen, Gen):
232 gen = Gen(gen)
233
234 if prop == 'bits':
235 return self.bits_by_gen.get(gen, 0)
236 elif prop == 'start':
237 return self.start_by_gen.get(gen, 0)
238 else:
239 raise ValueError('Invalid property: "{0}"'.format(prop))
240
241 class XmlParser(object):
242
243 def __init__(self, containers):
244 self.parser = xml.parsers.expat.ParserCreate()
245 self.parser.StartElementHandler = self.start_element
246 self.parser.EndElementHandler = self.end_element
247
248 self.gen = None
249 self.containers = containers
250 self.container_stack = []
251 self.container_stack.append(None)
252
253 def parse(self, filename):
254 with open(filename, 'rb') as f:
255 self.parser.ParseFile(f)
256
257 def start_element(self, name, attrs):
258 if name == 'genxml':
259 self.gen = Gen(attrs['gen'])
260 elif name in ('instruction', 'struct', 'register'):
261 if name == 'instruction' and 'engine' in attrs:
262 engines = set(attrs['engine'].split('|'))
263 if not engines & self.engines:
264 self.container_stack.append(None)
265 return
266 self.start_container(attrs)
267 elif name == 'group':
268 self.container_stack.append(None)
269 elif name == 'field':
270 self.start_field(attrs)
271 else:
272 pass
273
274 def end_element(self, name):
275 if name == 'genxml':
276 self.gen = None
277 elif name in ('instruction', 'struct', 'register', 'group'):
278 self.container_stack.pop()
279 else:
280 pass
281
282 def start_container(self, attrs):
283 assert self.container_stack[-1] is None
284 name = attrs['name']
285 if name not in self.containers:
286 self.containers[name] = Container(name)
287 self.container_stack.append(self.containers[name])
288 self.container_stack[-1].add_gen(self.gen, attrs)
289
290 def start_field(self, attrs):
291 if self.container_stack[-1] is None:
292 return
293
294 field_name = attrs.get('name', None)
295 if not field_name:
296 return
297
298 self.container_stack[-1].get_field(field_name, True).add_gen(self.gen, attrs)
299
300 def parse_args():
301 p = argparse.ArgumentParser()
302 p.add_argument('-o', '--output', type=str,
303 help="If OUTPUT is unset or '-', then it defaults to '/dev/stdout'")
304 p.add_argument('--cpp-guard', type=str,
305 help='If unset, then CPP_GUARD is derived from OUTPUT.')
306 p.add_argument('--engines', nargs='?', type=str, default='render',
307 help="Comma-separated list of engines whose instructions should be parsed (default: %(default)s)")
308 p.add_argument('xml_sources', metavar='XML_SOURCE', nargs='+')
309
310 pargs = p.parse_args()
311
312 if pargs.output in (None, '-'):
313 pargs.output = '/dev/stdout'
314
315 if pargs.cpp_guard is None:
316 pargs.cpp_guard = os.path.basename(pargs.output).upper().replace('.', '_')
317
318 return pargs
319
320 def main():
321 pargs = parse_args()
322
323 engines = pargs.engines.split(',')
324 valid_engines = [ 'render', 'blitter', 'video' ]
325 if set(engines) - set(valid_engines):
326 print("Invalid engine specified, valid engines are:\n")
327 for e in valid_engines:
328 print("\t%s" % e)
329 sys.exit(1)
330
331 # Maps name => Container
332 containers = {}
333
334 for source in pargs.xml_sources:
335 p = XmlParser(containers)
336 p.engines = set(engines)
337 p.parse(source)
338
339 with open(pargs.output, 'wb') as f:
340 f.write(TEMPLATE.render(containers=containers, guard=pargs.cpp_guard))
341
342 if __name__ == '__main__':
343 main()