23bc8542184ba8f2e1d6a07f0a2db4b5a11b067f
[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 argparse
26 import functools
27 import os
28 import xml.etree.cElementTree as et
29
30 from mako.template import Template
31
32 from anv_extensions import *
33
34 # We generate a static hash table for entry point lookup
35 # (vkGetProcAddress). We use a linear congruential generator for our hash
36 # function and a power-of-two size table. The prime numbers are determined
37 # experimentally.
38
39 TEMPLATE_H = Template("""\
40 /* This file generated from ${filename}, don't edit directly. */
41
42 struct anv_dispatch_table {
43 union {
44 void *entrypoints[${len(entrypoints)}];
45 struct {
46 % for _, name, _, _, _, guard in entrypoints:
47 % if guard is not None:
48 #ifdef ${guard}
49 PFN_vk${name} ${name};
50 #else
51 void *${name};
52 # endif
53 % else:
54 PFN_vk${name} ${name};
55 % endif
56 % endfor
57 };
58 };
59 };
60
61 % for type_, name, args, num, h, guard in entrypoints:
62 % if guard is not None:
63 #ifdef ${guard}
64 % endif
65 ${type_} anv_${name}(${args});
66 ${type_} gen7_${name}(${args});
67 ${type_} gen75_${name}(${args});
68 ${type_} gen8_${name}(${args});
69 ${type_} gen9_${name}(${args});
70 ${type_} gen10_${name}(${args});
71 % if guard is not None:
72 #endif // ${guard}
73 % endif
74 % endfor
75 """, output_encoding='utf-8')
76
77 TEMPLATE_C = Template(u"""\
78 /*
79 * Copyright © 2015 Intel Corporation
80 *
81 * Permission is hereby granted, free of charge, to any person obtaining a
82 * copy of this software and associated documentation files (the "Software"),
83 * to deal in the Software without restriction, including without limitation
84 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
85 * and/or sell copies of the Software, and to permit persons to whom the
86 * Software is furnished to do so, subject to the following conditions:
87 *
88 * The above copyright notice and this permission notice (including the next
89 * paragraph) shall be included in all copies or substantial portions of the
90 * Software.
91 *
92 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
93 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
94 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
95 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
96 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
97 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
98 * IN THE SOFTWARE.
99 */
100
101 /* This file generated from ${filename}, don't edit directly. */
102
103 #include "anv_private.h"
104
105 struct anv_entrypoint {
106 uint32_t name;
107 uint32_t hash;
108 };
109
110 /* We use a big string constant to avoid lots of reloctions from the entry
111 * point table to lots of little strings. The entries in the entry point table
112 * store the index into this big string.
113 */
114
115 static const char strings[] =
116 % for _, name, _, _, _, _ in entrypoints:
117 "vk${name}\\0"
118 % endfor
119 ;
120
121 static const struct anv_entrypoint entrypoints[] = {
122 % for _, name, _, num, h, _ in entrypoints:
123 [${num}] = { ${offsets[num]}, ${'{:0=#8x}'.format(h)} }, /* vk${name} */
124 % endfor
125 };
126
127 /* Weak aliases for all potential implementations. These will resolve to
128 * NULL if they're not defined, which lets the resolve_entrypoint() function
129 * either pick the correct entry point.
130 */
131
132 % for layer in ['anv', 'gen7', 'gen75', 'gen8', 'gen9', 'gen10']:
133 % for type_, name, args, _, _, guard in entrypoints:
134 % if guard is not None:
135 #ifdef ${guard}
136 % endif
137 ${type_} ${layer}_${name}(${args}) __attribute__ ((weak));
138 % if guard is not None:
139 #endif // ${guard}
140 % endif
141 % endfor
142
143 const struct anv_dispatch_table ${layer}_layer = {
144 % for _, name, args, _, _, guard in entrypoints:
145 % if guard is not None:
146 #ifdef ${guard}
147 % endif
148 .${name} = ${layer}_${name},
149 % if guard is not None:
150 #endif // ${guard}
151 % endif
152 % endfor
153 };
154 % endfor
155
156 static void * __attribute__ ((noinline))
157 anv_resolve_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
158 {
159 if (devinfo == NULL) {
160 return anv_layer.entrypoints[index];
161 }
162
163 const struct anv_dispatch_table *genX_table;
164 switch (devinfo->gen) {
165 case 10:
166 genX_table = &gen10_layer;
167 break;
168 case 9:
169 genX_table = &gen9_layer;
170 break;
171 case 8:
172 genX_table = &gen8_layer;
173 break;
174 case 7:
175 if (devinfo->is_haswell)
176 genX_table = &gen75_layer;
177 else
178 genX_table = &gen7_layer;
179 break;
180 default:
181 unreachable("unsupported gen\\n");
182 }
183
184 if (genX_table->entrypoints[index])
185 return genX_table->entrypoints[index];
186 else
187 return anv_layer.entrypoints[index];
188 }
189
190 /* Hash table stats:
191 * size ${hash_size} entries
192 * collisions entries:
193 % for i in xrange(10):
194 * ${i}${'+' if i == 9 else ''} ${collisions[i]}
195 % endfor
196 */
197
198 #define none ${'{:#x}'.format(none)}
199 static const uint16_t map[] = {
200 % for i in xrange(0, hash_size, 8):
201 % for j in xrange(i, i + 8):
202 ## This is 6 because the 0x is counted in the length
203 % if mapping[j] & 0xffff == 0xffff:
204 none,
205 % else:
206 ${'{:0=#6x}'.format(mapping[j] & 0xffff)},
207 % endif
208 % endfor
209 % endfor
210 };
211
212 void *
213 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
214 {
215 static const uint32_t prime_factor = ${prime_factor};
216 static const uint32_t prime_step = ${prime_step};
217 const struct anv_entrypoint *e;
218 uint32_t hash, h, i;
219 const char *p;
220
221 hash = 0;
222 for (p = name; *p; p++)
223 hash = hash * prime_factor + *p;
224
225 h = hash;
226 do {
227 i = map[h & ${hash_mask}];
228 if (i == none)
229 return NULL;
230 e = &entrypoints[i];
231 h += prime_step;
232 } while (e->hash != hash);
233
234 if (strcmp(name, strings + e->name) != 0)
235 return NULL;
236
237 return anv_resolve_entrypoint(devinfo, i);
238 }""", output_encoding='utf-8')
239
240 NONE = 0xffff
241 HASH_SIZE = 256
242 U32_MASK = 2**32 - 1
243 HASH_MASK = HASH_SIZE - 1
244
245 PRIME_FACTOR = 5024183
246 PRIME_STEP = 19
247
248
249 def cal_hash(name):
250 """Calculate the same hash value that Mesa will calculate in C."""
251 return functools.reduce(
252 lambda h, c: (h * PRIME_FACTOR + ord(c)) & U32_MASK, name, 0)
253
254
255 def get_entrypoints(doc, entrypoints_to_defines, start_index):
256 """Extract the entry points from the registry."""
257 entrypoints = []
258
259 enabled_commands = set()
260 for feature in doc.findall('./feature'):
261 assert feature.attrib['api'] == 'vulkan'
262 if VkVersion(feature.attrib['number']) > MAX_API_VERSION:
263 continue
264
265 for command in feature.findall('./require/command'):
266 enabled_commands.add(command.attrib['name'])
267
268 supported = set(ext.name for ext in EXTENSIONS)
269 for extension in doc.findall('.extensions/extension'):
270 if extension.attrib['name'] not in supported:
271 continue
272
273 if extension.attrib['supported'] != 'vulkan':
274 continue
275
276 for command in extension.findall('./require/command'):
277 enabled_commands.add(command.attrib['name'])
278
279 index = start_index
280 for command in doc.findall('./commands/command'):
281 type = command.find('./proto/type').text
282 fullname = command.find('./proto/name').text
283
284 if fullname not in enabled_commands:
285 continue
286
287 shortname = fullname[2:]
288 params = (''.join(p.itertext()) for p in command.findall('./param'))
289 params = ', '.join(params)
290 guard = entrypoints_to_defines.get(fullname)
291 entrypoints.append((type, shortname, params, index, cal_hash(fullname), guard))
292 index += 1
293
294 return entrypoints
295
296
297 def get_entrypoints_defines(doc):
298 """Maps entry points to extension defines."""
299 entrypoints_to_defines = {}
300
301 for extension in doc.findall('./extensions/extension[@protect]'):
302 define = extension.attrib['protect']
303
304 for entrypoint in extension.findall('./require/command'):
305 fullname = entrypoint.attrib['name']
306 entrypoints_to_defines[fullname] = define
307
308 return entrypoints_to_defines
309
310
311 def gen_code(entrypoints):
312 """Generate the C code."""
313 i = 0
314 offsets = []
315 for _, name, _, _, _, _ in entrypoints:
316 offsets.append(i)
317 i += 2 + len(name) + 1
318
319 mapping = [NONE] * HASH_SIZE
320 collisions = [0] * 10
321 for _, name, _, num, h, _ in entrypoints:
322 level = 0
323 while mapping[h & HASH_MASK] != NONE:
324 h = h + PRIME_STEP
325 level = level + 1
326 if level > 9:
327 collisions[9] += 1
328 else:
329 collisions[level] += 1
330 mapping[h & HASH_MASK] = num
331
332 return TEMPLATE_C.render(entrypoints=entrypoints,
333 offsets=offsets,
334 collisions=collisions,
335 mapping=mapping,
336 hash_mask=HASH_MASK,
337 prime_step=PRIME_STEP,
338 prime_factor=PRIME_FACTOR,
339 none=NONE,
340 hash_size=HASH_SIZE,
341 filename=os.path.basename(__file__))
342
343
344 def main():
345 parser = argparse.ArgumentParser()
346 parser.add_argument('--outdir', help='Where to write the files.',
347 required=True)
348 parser.add_argument('--xml',
349 help='Vulkan API XML file.',
350 required=True,
351 action='append',
352 dest='xml_files')
353 args = parser.parse_args()
354
355 entrypoints = []
356
357 for filename in args.xml_files:
358 doc = et.parse(filename)
359 entrypoints += get_entrypoints(doc, get_entrypoints_defines(doc),
360 start_index=len(entrypoints))
361
362 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
363 # defined.
364 entrypoints.append(('VkResult', 'CreateDmaBufImageINTEL',
365 'VkDevice device, ' +
366 'const VkDmaBufImageCreateInfo* pCreateInfo, ' +
367 'const VkAllocationCallbacks* pAllocator,' +
368 'VkDeviceMemory* pMem,' +
369 'VkImage* pImage', len(entrypoints),
370 cal_hash('vkCreateDmaBufImageINTEL'), None))
371
372 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
373 # per entry point.
374 try:
375 with open(os.path.join(args.outdir, 'anv_entrypoints.h'), 'wb') as f:
376 f.write(TEMPLATE_H.render(entrypoints=entrypoints,
377 filename=os.path.basename(__file__)))
378 with open(os.path.join(args.outdir, 'anv_entrypoints.c'), 'wb') as f:
379 f.write(gen_code(entrypoints))
380 except Exception:
381 # In the even there's an error this imports some helpers from mako
382 # to print a useful stack trace and prints it, then exits with
383 # status 1, if python is run with debug; otherwise it just raises
384 # the exception
385 if __debug__:
386 import sys
387 from mako import exceptions
388 sys.stderr.write(exceptions.text_error_template().render() + '\n')
389 sys.exit(1)
390 raise
391
392
393 if __name__ == '__main__':
394 main()