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