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
29 import xml
.etree
.cElementTree
as et
31 from collections
import OrderedDict
, namedtuple
32 from mako
.template
import Template
34 from anv_extensions
import *
36 # We generate a static hash table for entry point lookup
37 # (vkGetProcAddress). We use a linear congruential generator for our hash
38 # function and a power-of-two size table. The prime numbers are determined
51 TEMPLATE_H
= Template("""\
52 /* This file generated from ${filename}, don't edit directly. */
54 struct anv_dispatch_table {
56 void *entrypoints[${len(entrypoints)}];
58 % for e in entrypoints:
59 % if e.guard is not None:
61 PFN_${e.name} ${e.name};
66 PFN_${e.name} ${e.name};
74 extern const struct anv_dispatch_table ${layer}_dispatch_table;
76 extern const struct anv_dispatch_table anv_tramp_dispatch_table;
78 % for e in entrypoints:
79 % if e.guard is not None:
82 % for layer in LAYERS:
83 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
85 % if e.guard is not None:
89 """, output_encoding
='utf-8')
91 TEMPLATE_C
= Template(u
"""\
93 * Copyright © 2015 Intel Corporation
95 * Permission is hereby granted, free of charge, to any person obtaining a
96 * copy of this software and associated documentation files (the "Software"),
97 * to deal in the Software without restriction, including without limitation
98 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
99 * and/or sell copies of the Software, and to permit persons to whom the
100 * Software is furnished to do so, subject to the following conditions:
102 * The above copyright notice and this permission notice (including the next
103 * paragraph) shall be included in all copies or substantial portions of the
106 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
107 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
108 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
109 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
110 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
111 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
115 /* This file generated from ${filename}, don't edit directly. */
117 #include "anv_private.h"
119 struct string_map_entry {
125 /* We use a big string constant to avoid lots of reloctions from the entry
126 * point table to lots of little strings. The entries in the entry point table
127 * store the index into this big string.
130 static const char strings[] =
131 % for s in strmap.sorted_strings:
136 static const struct string_map_entry string_map_entries[] = {
137 % for s in strmap.sorted_strings:
138 { ${s.offset}, ${'{:0=#8x}'.format(s.hash)}, ${s.num} }, /* ${s.string} */
143 * size ${len(strmap.sorted_strings)} entries
144 * collisions entries:
145 % for i in xrange(10):
146 * ${i}${'+' if i == 9 else ' '} ${strmap.collisions[i]}
151 static const uint16_t string_map[${strmap.hash_size}] = {
152 % for e in strmap.mapping:
153 ${ '{:0=#6x}'.format(e) if e >= 0 else 'none' },
158 string_map_lookup(const char *str)
160 static const uint32_t prime_factor = ${strmap.prime_factor};
161 static const uint32_t prime_step = ${strmap.prime_step};
162 const struct string_map_entry *e;
168 for (p = str; *p; p++)
169 hash = hash * prime_factor + *p;
173 i = string_map[h & ${strmap.hash_mask}];
176 e = &string_map_entries[i];
177 if (e->hash == hash && strcmp(str, strings + e->name) == 0)
185 /* Weak aliases for all potential implementations. These will resolve to
186 * NULL if they're not defined, which lets the resolve_entrypoint() function
187 * either pick the correct entry point.
190 % for layer in LAYERS:
191 % for e in entrypoints:
192 % if e.guard is not None:
195 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
196 % if e.guard is not None:
201 const struct anv_dispatch_table ${layer}_dispatch_table = {
202 % for e in entrypoints:
203 % if e.guard is not None:
206 .${e.name} = ${e.prefixed_name(layer)},
207 % if e.guard is not None:
215 /** Trampoline entrypoints for all device functions */
217 % for e in entrypoints:
218 % if not e.is_device_entrypoint():
221 % if e.guard is not None:
224 static ${e.return_type}
225 ${e.prefixed_name('anv_tramp')}(${e.decl_params()})
227 % if e.params[0].type == 'VkDevice':
228 ANV_FROM_HANDLE(anv_device, anv_device, ${e.params[0].name});
229 return anv_device->dispatch.${e.name}(${e.call_params()});
231 ANV_FROM_HANDLE(anv_cmd_buffer, anv_cmd_buffer, ${e.params[0].name});
232 return anv_cmd_buffer->device->dispatch.${e.name}(${e.call_params()});
235 % if e.guard is not None:
240 const struct anv_dispatch_table anv_tramp_dispatch_table = {
241 % for e in entrypoints:
242 % if not e.is_device_entrypoint():
245 % if e.guard is not None:
248 .${e.name} = ${e.prefixed_name('anv_tramp')},
249 % if e.guard is not None:
256 /** Return true if the core version or extension in which the given entrypoint
257 * is defined is enabled.
259 * If device is NULL, all device extensions are considered enabled.
262 anv_entrypoint_is_enabled(int index, uint32_t core_version,
263 const struct anv_instance_extension_table *instance,
264 const struct anv_device_extension_table *device)
267 % for e in entrypoints:
270 return ${e.core_version.c_vk_version()} <= core_version;
272 % if e.extension.type == 'instance':
273 return !device && instance->${e.extension.name[3:]};
275 return !device || device->${e.extension.name[3:]};
286 static void * __attribute__ ((noinline))
287 anv_resolve_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
289 if (devinfo == NULL) {
290 return anv_dispatch_table.entrypoints[index];
293 const struct anv_dispatch_table *genX_table;
294 switch (devinfo->gen) {
296 genX_table = &gen11_dispatch_table;
299 genX_table = &gen10_dispatch_table;
302 genX_table = &gen9_dispatch_table;
305 genX_table = &gen8_dispatch_table;
308 if (devinfo->is_haswell)
309 genX_table = &gen75_dispatch_table;
311 genX_table = &gen7_dispatch_table;
314 unreachable("unsupported gen\\n");
317 if (genX_table->entrypoints[index])
318 return genX_table->entrypoints[index];
320 return anv_dispatch_table.entrypoints[index];
324 anv_get_entrypoint_index(const char *name)
326 return string_map_lookup(name);
330 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
332 int idx = anv_get_entrypoint_index(name);
335 return anv_resolve_entrypoint(devinfo, idx);
336 }""", output_encoding
='utf-8')
340 PRIME_FACTOR
= 5024183
343 class StringIntMapEntry(object):
344 def __init__(self
, string
, num
):
348 # Calculate the same hash value that we will calculate in C.
351 h
= ((h
* PRIME_FACTOR
) + ord(c
)) & U32_MASK
356 def round_to_pow2(x
):
357 return 2**int(math
.ceil(math
.log(x
, 2)))
359 class StringIntMap(object):
362 self
.strings
= dict()
364 def add_string(self
, string
, num
):
365 assert not self
.baked
366 assert string
not in self
.strings
367 assert num
>= 0 and num
< 2**31
368 self
.strings
[string
] = StringIntMapEntry(string
, num
)
371 self
.sorted_strings
= \
372 sorted(self
.strings
.values(), key
=lambda x
: x
.string
)
374 for entry
in self
.sorted_strings
:
375 entry
.offset
= offset
376 offset
+= len(entry
.string
) + 1
378 # Save off some values that we'll need in C
379 self
.hash_size
= round_to_pow2(len(self
.strings
) * 1.25)
380 self
.hash_mask
= self
.hash_size
- 1
381 self
.prime_factor
= PRIME_FACTOR
382 self
.prime_step
= PRIME_STEP
384 self
.mapping
= [-1] * self
.hash_size
385 self
.collisions
= [0] * 10
386 for idx
, s
in enumerate(self
.sorted_strings
):
389 while self
.mapping
[h
& self
.hash_mask
] >= 0:
392 self
.collisions
[min(level
, 9)] += 1
393 self
.mapping
[h
& self
.hash_mask
] = idx
395 EntrypointParam
= namedtuple('EntrypointParam', 'type name decl')
397 class Entrypoint(object):
398 def __init__(self
, name
, return_type
, params
, guard
= None):
400 self
.return_type
= return_type
405 # Extensions which require this entrypoint
406 self
.core_version
= None
407 self
.extension
= None
409 def is_device_entrypoint(self
):
410 return self
.params
[0].type in ('VkDevice', 'VkCommandBuffer')
412 def prefixed_name(self
, prefix
):
413 assert self
.name
.startswith('vk')
414 return prefix
+ '_' + self
.name
[2:]
416 def decl_params(self
):
417 return ', '.join(p
.decl
for p
in self
.params
)
419 def call_params(self
):
420 return ', '.join(p
.name
for p
in self
.params
)
422 def get_entrypoints(doc
, entrypoints_to_defines
, start_index
):
423 """Extract the entry points from the registry."""
424 entrypoints
= OrderedDict()
426 for command
in doc
.findall('./commands/command'):
427 ret_type
= command
.find('./proto/type').text
428 fullname
= command
.find('./proto/name').text
429 params
= [EntrypointParam(
430 type = p
.find('./type').text
,
431 name
= p
.find('./name').text
,
432 decl
= ''.join(p
.itertext())
433 ) for p
in command
.findall('./param')]
434 guard
= entrypoints_to_defines
.get(fullname
)
435 # They really need to be unique
436 assert fullname
not in entrypoints
437 entrypoints
[fullname
] = Entrypoint(fullname
, ret_type
, params
, guard
)
439 enabled_commands
= set()
440 for feature
in doc
.findall('./feature'):
441 assert feature
.attrib
['api'] == 'vulkan'
442 version
= VkVersion(feature
.attrib
['number'])
443 if version
> MAX_API_VERSION
:
446 for command
in feature
.findall('./require/command'):
447 e
= entrypoints
[command
.attrib
['name']]
449 assert e
.core_version
is None
450 e
.core_version
= version
452 supported_exts
= dict((ext
.name
, ext
) for ext
in EXTENSIONS
)
453 for extension
in doc
.findall('.extensions/extension'):
454 ext_name
= extension
.attrib
['name']
455 if ext_name
not in supported_exts
:
458 if extension
.attrib
['supported'] != 'vulkan':
461 ext
= supported_exts
[ext_name
]
462 ext
.type = extension
.attrib
['type']
464 for command
in extension
.findall('./require/command'):
465 e
= entrypoints
[command
.attrib
['name']]
467 assert e
.core_version
is None
468 assert e
.extension
is None
471 return [e
for e
in entrypoints
.itervalues() if e
.enabled
]
474 def get_entrypoints_defines(doc
):
475 """Maps entry points to extension defines."""
476 entrypoints_to_defines
= {}
478 for extension
in doc
.findall('./extensions/extension[@protect]'):
479 define
= extension
.attrib
['protect']
481 for entrypoint
in extension
.findall('./require/command'):
482 fullname
= entrypoint
.attrib
['name']
483 entrypoints_to_defines
[fullname
] = define
485 return entrypoints_to_defines
489 parser
= argparse
.ArgumentParser()
490 parser
.add_argument('--outdir', help='Where to write the files.',
492 parser
.add_argument('--xml',
493 help='Vulkan API XML file.',
497 args
= parser
.parse_args()
501 for filename
in args
.xml_files
:
502 doc
= et
.parse(filename
)
503 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
),
504 start_index
=len(entrypoints
))
506 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
508 entrypoints
.append(Entrypoint('vkCreateDmaBufImageINTEL', 'VkResult', [
509 EntrypointParam('VkDevice', 'device', 'VkDevice device'),
510 EntrypointParam('VkDmaBufImageCreateInfo', 'pCreateInfo',
511 'const VkDmaBufImageCreateInfo* pCreateInfo'),
512 EntrypointParam('VkAllocationCallbacks', 'pAllocator',
513 'const VkAllocationCallbacks* pAllocator'),
514 EntrypointParam('VkDeviceMemory', 'pMem', 'VkDeviceMemory* pMem'),
515 EntrypointParam('VkImage', 'pImage', 'VkImage* pImage')
518 strmap
= StringIntMap()
519 for num
, e
in enumerate(entrypoints
):
520 strmap
.add_string(e
.name
, num
)
524 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
527 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.h'), 'wb') as f
:
528 f
.write(TEMPLATE_H
.render(entrypoints
=entrypoints
,
530 filename
=os
.path
.basename(__file__
)))
531 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.c'), 'wb') as f
:
532 f
.write(TEMPLATE_C
.render(entrypoints
=entrypoints
,
535 filename
=os
.path
.basename(__file__
)))
537 # In the even there's an error this imports some helpers from mako
538 # to print a useful stack trace and prints it, then exits with
539 # status 1, if python is run with debug; otherwise it just raises
543 from mako
import exceptions
544 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
549 if __name__
== '__main__':