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