3 # Copyright © 2015, 2017 Intel Corporation
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:
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
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
28 import xml
.etree
.cElementTree
as et
30 from mako
.template
import Template
32 from anv_extensions
import *
34 # We generate a static hash table for entry point lookup
35 # (vkGetProcAddress). We use a linear congruential generator for our hash
36 # function and a power-of-two size table. The prime numbers are determined
48 TEMPLATE_H
= Template("""\
49 /* This file generated from ${filename}, don't edit directly. */
51 struct anv_dispatch_table {
53 void *entrypoints[${len(entrypoints)}];
55 % for e in entrypoints:
56 % if e.guard is not None:
58 PFN_${e.name} ${e.name};
63 PFN_${e.name} ${e.name};
70 % for e in entrypoints:
71 % if e.guard is not None:
74 % for layer in LAYERS:
75 ${e.return_type} ${e.prefixed_name(layer)}(${e.params});
77 % if e.guard is not None:
81 """, output_encoding
='utf-8')
83 TEMPLATE_C
= Template(u
"""\
85 * Copyright © 2015 Intel Corporation
87 * Permission is hereby granted, free of charge, to any person obtaining a
88 * copy of this software and associated documentation files (the "Software"),
89 * to deal in the Software without restriction, including without limitation
90 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
91 * and/or sell copies of the Software, and to permit persons to whom the
92 * Software is furnished to do so, subject to the following conditions:
94 * The above copyright notice and this permission notice (including the next
95 * paragraph) shall be included in all copies or substantial portions of the
98 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
99 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
100 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
101 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
102 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
103 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
107 /* This file generated from ${filename}, don't edit directly. */
109 #include "anv_private.h"
111 struct anv_entrypoint {
116 /* We use a big string constant to avoid lots of reloctions from the entry
117 * point table to lots of little strings. The entries in the entry point table
118 * store the index into this big string.
121 static const char strings[] =
122 % for e in entrypoints:
127 static const struct anv_entrypoint entrypoints[] = {
128 % for e in entrypoints:
129 [${e.num}] = { ${offsets[e.num]}, ${'{:0=#8x}'.format(e.get_c_hash())} }, /* ${e.name} */
133 /* Weak aliases for all potential implementations. These will resolve to
134 * NULL if they're not defined, which lets the resolve_entrypoint() function
135 * either pick the correct entry point.
138 % for layer in LAYERS:
139 % for e in entrypoints:
140 % if e.guard is not None:
143 ${e.return_type} ${e.prefixed_name(layer)}(${e.params}) __attribute__ ((weak));
144 % if e.guard is not None:
149 const struct anv_dispatch_table ${layer}_layer = {
150 % for e in entrypoints:
151 % if e.guard is not None:
154 .${e.name} = ${e.prefixed_name(layer)},
155 % if e.guard is not None:
162 static void * __attribute__ ((noinline))
163 anv_resolve_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
165 if (devinfo == NULL) {
166 return anv_layer.entrypoints[index];
169 const struct anv_dispatch_table *genX_table;
170 switch (devinfo->gen) {
172 genX_table = &gen10_layer;
175 genX_table = &gen9_layer;
178 genX_table = &gen8_layer;
181 if (devinfo->is_haswell)
182 genX_table = &gen75_layer;
184 genX_table = &gen7_layer;
187 unreachable("unsupported gen\\n");
190 if (genX_table->entrypoints[index])
191 return genX_table->entrypoints[index];
193 return anv_layer.entrypoints[index];
197 * size ${hash_size} entries
198 * collisions entries:
199 % for i in xrange(10):
200 * ${i}${'+' if i == 9 else ''} ${collisions[i]}
204 #define none ${'{:#x}'.format(none)}
205 static const uint16_t map[] = {
206 % for i in xrange(0, hash_size, 8):
207 % for j in xrange(i, i + 8):
208 ## This is 6 because the 0x is counted in the length
209 % if mapping[j] & 0xffff == 0xffff:
212 ${'{:0=#6x}'.format(mapping[j] & 0xffff)},
219 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
221 static const uint32_t prime_factor = ${prime_factor};
222 static const uint32_t prime_step = ${prime_step};
223 const struct anv_entrypoint *e;
228 for (p = name; *p; p++)
229 hash = hash * prime_factor + *p;
233 i = map[h & ${hash_mask}];
238 } while (e->hash != hash);
240 if (strcmp(name, strings + e->name) != 0)
243 return anv_resolve_entrypoint(devinfo, i);
244 }""", output_encoding
='utf-8')
249 HASH_MASK
= HASH_SIZE
- 1
251 PRIME_FACTOR
= 5024183
256 """Calculate the same hash value that Mesa will calculate in C."""
257 return functools
.reduce(
258 lambda h
, c
: (h
* PRIME_FACTOR
+ ord(c
)) & U32_MASK
, name
, 0)
260 class Entrypoint(object):
261 def __init__(self
, name
, return_type
, params
, guard
= None):
263 self
.return_type
= return_type
264 self
.params
= ', '.join(params
)
268 def prefixed_name(self
, prefix
):
269 assert self
.name
.startswith('vk')
270 return prefix
+ '_' + self
.name
[2:]
272 def get_c_hash(self
):
273 return cal_hash(self
.name
)
275 def get_entrypoints(doc
, entrypoints_to_defines
, start_index
):
276 """Extract the entry points from the registry."""
279 enabled_commands
= set()
280 for feature
in doc
.findall('./feature'):
281 assert feature
.attrib
['api'] == 'vulkan'
282 if VkVersion(feature
.attrib
['number']) > MAX_API_VERSION
:
285 for command
in feature
.findall('./require/command'):
286 enabled_commands
.add(command
.attrib
['name'])
288 supported
= set(ext
.name
for ext
in EXTENSIONS
)
289 for extension
in doc
.findall('.extensions/extension'):
290 if extension
.attrib
['name'] not in supported
:
293 if extension
.attrib
['supported'] != 'vulkan':
296 for command
in extension
.findall('./require/command'):
297 enabled_commands
.add(command
.attrib
['name'])
299 for command
in doc
.findall('./commands/command'):
300 ret_type
= command
.find('./proto/type').text
301 fullname
= command
.find('./proto/name').text
303 if fullname
not in enabled_commands
:
306 params
= (''.join(p
.itertext()) for p
in command
.findall('./param'))
307 guard
= entrypoints_to_defines
.get(fullname
)
308 entrypoints
.append(Entrypoint(fullname
, ret_type
, params
, guard
))
313 def get_entrypoints_defines(doc
):
314 """Maps entry points to extension defines."""
315 entrypoints_to_defines
= {}
317 for extension
in doc
.findall('./extensions/extension[@protect]'):
318 define
= extension
.attrib
['protect']
320 for entrypoint
in extension
.findall('./require/command'):
321 fullname
= entrypoint
.attrib
['name']
322 entrypoints_to_defines
[fullname
] = define
324 return entrypoints_to_defines
327 def gen_code(entrypoints
):
328 """Generate the C code."""
331 for e
in entrypoints
:
335 mapping
= [NONE
] * HASH_SIZE
336 collisions
= [0] * 10
337 for e
in entrypoints
:
340 while mapping
[h
& HASH_MASK
] != NONE
:
346 collisions
[level
] += 1
347 mapping
[h
& HASH_MASK
] = e
.num
349 return TEMPLATE_C
.render(entrypoints
=entrypoints
,
352 collisions
=collisions
,
355 prime_step
=PRIME_STEP
,
356 prime_factor
=PRIME_FACTOR
,
359 filename
=os
.path
.basename(__file__
))
363 parser
= argparse
.ArgumentParser()
364 parser
.add_argument('--outdir', help='Where to write the files.',
366 parser
.add_argument('--xml',
367 help='Vulkan API XML file.',
371 args
= parser
.parse_args()
375 for filename
in args
.xml_files
:
376 doc
= et
.parse(filename
)
377 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
),
378 start_index
=len(entrypoints
))
380 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
382 entrypoints
.append(Entrypoint('vkCreateDmaBufImageINTEL', 'VkResult',
384 'const VkDmaBufImageCreateInfo* pCreateInfo',
385 'const VkAllocationCallbacks* pAllocator',
386 'VkDeviceMemory* pMem',
389 for num
, e
in enumerate(entrypoints
):
392 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
395 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.h'), 'wb') as f
:
396 f
.write(TEMPLATE_H
.render(entrypoints
=entrypoints
,
398 filename
=os
.path
.basename(__file__
)))
399 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.c'), 'wb') as f
:
400 f
.write(gen_code(entrypoints
))
402 # In the even there's an error this imports some helpers from mako
403 # to print a useful stack trace and prints it, then exits with
404 # status 1, if python is run with debug; otherwise it just raises
408 from mako
import exceptions
409 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
414 if __name__
== '__main__':