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