anv: Use python style in anv_entrypoints_gen.py
[mesa.git] / src / intel / vulkan / anv_entrypoints_gen.py
1 # coding=utf-8
2 #
3 # Copyright © 2015, 2017 Intel Corporation
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a
6 # copy of this software and associated documentation files (the "Software"),
7 # to deal in the Software without restriction, including without limitation
8 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 # and/or sell copies of the Software, and to permit persons to whom the
10 # Software is furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice (including the next
13 # paragraph) shall be included in all copies or substantial portions of the
14 # Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 # IN THE SOFTWARE.
23 #
24
25 import sys
26 import textwrap
27 import xml.etree.ElementTree as et
28
29 max_api_version = 1.0
30
31 supported_extensions = [
32 'VK_KHR_descriptor_update_template',
33 'VK_KHR_get_physical_device_properties2',
34 'VK_KHR_maintenance1',
35 'VK_KHR_push_descriptor',
36 'VK_KHR_sampler_mirror_clamp_to_edge',
37 'VK_KHR_shader_draw_parameters',
38 'VK_KHR_surface',
39 'VK_KHR_swapchain',
40 'VK_KHR_wayland_surface',
41 'VK_KHR_xcb_surface',
42 'VK_KHR_xlib_surface',
43 ]
44
45 # We generate a static hash table for entry point lookup
46 # (vkGetProcAddress). We use a linear congruential generator for our hash
47 # function and a power-of-two size table. The prime numbers are determined
48 # experimentally.
49
50 none = 0xffff
51 hash_size = 256
52 u32_mask = 2**32 - 1
53 hash_mask = hash_size - 1
54
55 prime_factor = 5024183
56 prime_step = 19
57
58 opt_header = False
59 opt_code = False
60
61 if sys.argv[1] == "header":
62 opt_header = True
63 sys.argv.pop()
64 elif sys.argv[1] == "code":
65 opt_code = True
66 sys.argv.pop()
67
68
69 def hash(name):
70 h = 0
71 for c in name:
72 h = (h * prime_factor + ord(c)) & u32_mask
73
74 return h
75
76
77 def print_guard_start(guard):
78 if guard is not None:
79 print "#ifdef {0}".format(guard)
80
81
82 def print_guard_end(guard):
83 if guard is not None:
84 print "#endif // {0}".format(guard)
85
86
87 def get_entrypoints(doc, entrypoints_to_defines):
88 """Extract the entry points from the registry."""
89 entrypoints = []
90
91 enabled_commands = set()
92 for feature in doc.findall('./feature'):
93 assert feature.attrib['api'] == 'vulkan'
94 if float(feature.attrib['number']) > max_api_version:
95 continue
96
97 for command in feature.findall('./require/command'):
98 enabled_commands.add(command.attrib['name'])
99
100 for extension in doc.findall('.extensions/extension'):
101 if extension.attrib['name'] not in supported_extensions:
102 continue
103
104 assert extension.attrib['supported'] == 'vulkan'
105 for command in extension.findall('./require/command'):
106 enabled_commands.add(command.attrib['name'])
107
108 index = 0
109 for command in doc.findall('./commands/command'):
110 type = command.find('./proto/type').text
111 fullname = command.find('./proto/name').text
112
113 if fullname not in enabled_commands:
114 continue
115
116 shortname = fullname[2:]
117 params = (''.join(p.itertext()) for p in command.findall('./param'))
118 params = ', '.join(params)
119 if fullname in entrypoints_to_defines:
120 guard = entrypoints_to_defines[fullname]
121 else:
122 guard = None
123 entrypoints.append((type, shortname, params, index, hash(fullname), guard))
124 index += 1
125
126 return entrypoints
127
128
129 def get_entrypoints_defines(doc):
130 """Maps entry points to extension defines."""
131 entrypoints_to_defines = {}
132 extensions = doc.findall('./extensions/extension')
133 for extension in extensions:
134 define = extension.get('protect')
135 entrypoints = extension.findall('./require/command')
136 for entrypoint in entrypoints:
137 fullname = entrypoint.get('name')
138 entrypoints_to_defines[fullname] = define
139 return entrypoints_to_defines
140
141
142 def main():
143 doc = et.parse(sys.stdin)
144 entrypoints = get_entrypoints(doc, get_entrypoints_defines(doc))
145
146 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
147 # defined.
148 entrypoints.append(('VkResult', 'CreateDmaBufImageINTEL',
149 'VkDevice device, ' +
150 'const VkDmaBufImageCreateInfo* pCreateInfo, ' +
151 'const VkAllocationCallbacks* pAllocator,' +
152 'VkDeviceMemory* pMem,' +
153 'VkImage* pImage', len(entrypoints),
154 hash('vkCreateDmaBufImageINTEL'), None))
155
156 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
157 # per entry point.
158
159 if opt_header:
160 print "/* This file generated from vk_gen.py, don't edit directly. */\n"
161
162 print "struct anv_dispatch_table {"
163 print " union {"
164 print " void *entrypoints[%d];" % len(entrypoints)
165 print " struct {"
166
167 for type, name, args, num, h, guard in entrypoints:
168 if guard is not None:
169 print "#ifdef {0}".format(guard)
170 print " PFN_vk{0} {0};".format(name)
171 print "#else"
172 print " void *{0};".format(name)
173 print "#endif"
174 else:
175 print " PFN_vk{0} {0};".format(name)
176 print " };\n"
177 print " };\n"
178 print "};\n"
179
180 print "void anv_set_dispatch_devinfo(const struct gen_device_info *info);\n"
181
182 for type, name, args, num, h, guard in entrypoints:
183 print_guard_start(guard)
184 print "%s anv_%s(%s);" % (type, name, args)
185 print "%s gen7_%s(%s);" % (type, name, args)
186 print "%s gen75_%s(%s);" % (type, name, args)
187 print "%s gen8_%s(%s);" % (type, name, args)
188 print "%s gen9_%s(%s);" % (type, name, args)
189 print_guard_end(guard)
190 exit()
191
192
193
194 print textwrap.dedent("""\
195 /*
196 * Copyright © 2015 Intel Corporation
197 *
198 * Permission is hereby granted, free of charge, to any person obtaining a
199 * copy of this software and associated documentation files (the "Software"),
200 * to deal in the Software without restriction, including without limitation
201 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
202 * and/or sell copies of the Software, and to permit persons to whom the
203 * Software is furnished to do so, subject to the following conditions:
204 *
205 * The above copyright notice and this permission notice (including the next
206 * paragraph) shall be included in all copies or substantial portions of the
207 * Software.
208 *
209 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
210 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
211 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
212 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
213 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
214 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
215 * IN THE SOFTWARE.
216 */
217
218 /* DO NOT EDIT! This is a generated file. */
219
220 #include "anv_private.h"
221
222 struct anv_entrypoint {
223 uint32_t name;
224 uint32_t hash;
225 };
226
227 /* We use a big string constant to avoid lots of reloctions from the entry
228 * point table to lots of little strings. The entries in the entry point table
229 * store the index into this big string.
230 */
231
232 static const char strings[] =""")
233
234 offsets = []
235 i = 0
236 for type, name, args, num, h, guard in entrypoints:
237 print " \"vk%s\\0\"" % name
238 offsets.append(i)
239 i += 2 + len(name) + 1
240 print " ;"
241
242 # Now generate the table of all entry points
243
244 print "\nstatic const struct anv_entrypoint entrypoints[] = {"
245 for type, name, args, num, h, guard in entrypoints:
246 print " { %5d, 0x%08x }," % (offsets[num], h)
247 print "};\n"
248
249 print textwrap.dedent("""
250
251 /* Weak aliases for all potential implementations. These will resolve to
252 * NULL if they're not defined, which lets the resolve_entrypoint() function
253 * either pick the correct entry point.
254 */
255 """)
256
257 for layer in ["anv", "gen7", "gen75", "gen8", "gen9"]:
258 for type, name, args, num, h, guard in entrypoints:
259 print_guard_start(guard)
260 print "%s %s_%s(%s) __attribute__ ((weak));" % (type, layer, name, args)
261 print_guard_end(guard)
262 print "\nconst struct anv_dispatch_table %s_layer = {" % layer
263 for type, name, args, num, h, guard in entrypoints:
264 print_guard_start(guard)
265 print " .%s = %s_%s," % (name, layer, name)
266 print_guard_end(guard)
267 print "};\n"
268
269 print textwrap.dedent("""
270 static void * __attribute__ ((noinline))
271 anv_resolve_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
272 {
273 if (devinfo == NULL) {
274 return anv_layer.entrypoints[index];
275 }
276
277 switch (devinfo->gen) {
278 case 9:
279 if (gen9_layer.entrypoints[index])
280 return gen9_layer.entrypoints[index];
281 /* fall through */
282 case 8:
283 if (gen8_layer.entrypoints[index])
284 return gen8_layer.entrypoints[index];
285 /* fall through */
286 case 7:
287 if (devinfo->is_haswell && gen75_layer.entrypoints[index])
288 return gen75_layer.entrypoints[index];
289
290 if (gen7_layer.entrypoints[index])
291 return gen7_layer.entrypoints[index];
292 /* fall through */
293 case 0:
294 return anv_layer.entrypoints[index];
295 default:
296 unreachable("unsupported gen\\n");
297 }
298 }
299 """)
300
301 # Now generate the hash table used for entry point look up. This is a
302 # uint16_t table of entry point indices. We use 0xffff to indicate an entry
303 # in the hash table is empty.
304
305 map = [none] * hash_size
306 collisions = [0] * 10
307 for type, name, args, num, h, guard in entrypoints:
308 level = 0
309 while map[h & hash_mask] != none:
310 h = h + prime_step
311 level = level + 1
312 if level > 9:
313 collisions[9] += 1
314 else:
315 collisions[level] += 1
316 map[h & hash_mask] = num
317
318 print "/* Hash table stats:"
319 print " * size %d entries" % hash_size
320 print " * collisions entries"
321 for i in xrange(10):
322 if i == 9:
323 plus = "+"
324 else:
325 plus = " "
326
327 print " * %2d%s %4d" % (i, plus, collisions[i])
328 print " */\n"
329
330 print "#define none 0x%04x\n" % none
331
332 print "static const uint16_t map[] = {"
333 for i in xrange(0, hash_size, 8):
334 print " ",
335 for j in xrange(i, i + 8):
336 if map[j] & 0xffff == 0xffff:
337 print " none,",
338 else:
339 print "0x%04x," % (map[j] & 0xffff),
340 print
341
342 print "};"
343
344 # Finally we generate the hash table lookup function. The hash function and
345 # linear probing algorithm matches the hash table generated above.
346
347 print textwrap.dedent("""
348 void *
349 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
350 {
351 static const uint32_t prime_factor = %d;
352 static const uint32_t prime_step = %d;
353 const struct anv_entrypoint *e;
354 uint32_t hash, h, i;
355 const char *p;
356
357 hash = 0;
358 for (p = name; *p; p++)
359 hash = hash * prime_factor + *p;
360
361 h = hash;
362 do {
363 i = map[h & %d];
364 if (i == none)
365 return NULL;
366 e = &entrypoints[i];
367 h += prime_step;
368 } while (e->hash != hash);
369
370 if (strcmp(name, strings + e->name) != 0)
371 return NULL;
372
373 return anv_resolve_entrypoint(devinfo, i);
374 }
375 """) % (prime_factor, prime_step, hash_mask)
376
377
378 if __name__ == '__main__':
379 main()