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