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