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 collections
import OrderedDict
, namedtuple
31 from mako
.template
import Template
33 from anv_extensions
import *
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
50 TEMPLATE_H
= Template("""\
51 /* This file generated from ${filename}, don't edit directly. */
53 struct anv_dispatch_table {
55 void *entrypoints[${len(entrypoints)}];
57 % for e in entrypoints:
58 % if e.guard is not None:
60 PFN_${e.name} ${e.name};
65 PFN_${e.name} ${e.name};
73 extern const struct anv_dispatch_table ${layer}_dispatch_table;
75 extern const struct anv_dispatch_table anv_tramp_dispatch_table;
77 % for e in entrypoints:
78 % if e.guard is not None:
81 % for layer in LAYERS:
82 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
84 % if e.guard is not None:
88 """, output_encoding
='utf-8')
90 TEMPLATE_C
= Template(u
"""\
92 * Copyright © 2015 Intel Corporation
94 * Permission is hereby granted, free of charge, to any person obtaining a
95 * copy of this software and associated documentation files (the "Software"),
96 * to deal in the Software without restriction, including without limitation
97 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
98 * and/or sell copies of the Software, and to permit persons to whom the
99 * Software is furnished to do so, subject to the following conditions:
101 * The above copyright notice and this permission notice (including the next
102 * paragraph) shall be included in all copies or substantial portions of the
105 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
106 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
107 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
108 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
109 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
110 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
114 /* This file generated from ${filename}, don't edit directly. */
116 #include "anv_private.h"
118 struct string_map_entry {
124 /* We use a big string constant to avoid lots of reloctions from the entry
125 * point table to lots of little strings. The entries in the entry point table
126 * store the index into this big string.
129 static const char strings[] =
130 % for s in strmap.sorted_strings:
135 static const struct string_map_entry string_map_entries[] = {
136 % for s in strmap.sorted_strings:
137 { ${s.offset}, ${'{:0=#8x}'.format(s.hash)}, ${s.num} }, /* ${s.string} */
142 * size ${len(strmap.sorted_strings)} entries
143 * collisions entries:
144 % for i in xrange(10):
145 * ${i}${'+' if i == 9 else ' '} ${strmap.collisions[i]}
150 static const uint16_t string_map[${strmap.hash_size}] = {
151 % for e in strmap.mapping:
152 ${ '{:0=#6x}'.format(e) if e >= 0 else 'none' },
157 string_map_lookup(const char *str)
159 static const uint32_t prime_factor = ${strmap.prime_factor};
160 static const uint32_t prime_step = ${strmap.prime_step};
161 const struct string_map_entry *e;
167 for (p = str; *p; p++)
168 hash = hash * prime_factor + *p;
172 i = string_map[h & ${strmap.hash_mask}];
175 e = &string_map_entries[i];
176 if (e->hash == hash && strcmp(str, strings + e->name) == 0)
184 /* Weak aliases for all potential implementations. These will resolve to
185 * NULL if they're not defined, which lets the resolve_entrypoint() function
186 * either pick the correct entry point.
189 % for layer in LAYERS:
190 % for e in entrypoints:
191 % if e.guard is not None:
194 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
195 % if e.guard is not None:
200 const struct anv_dispatch_table ${layer}_dispatch_table = {
201 % for e in entrypoints:
202 % if e.guard is not None:
205 .${e.name} = ${e.prefixed_name(layer)},
206 % if e.guard is not None:
214 /** Trampoline entrypoints for all device functions */
216 % for e in entrypoints:
217 % if e.params[0].type not in ('VkDevice', 'VkCommandBuffer'):
220 % if e.guard is not None:
223 static ${e.return_type}
224 ${e.prefixed_name('anv_tramp')}(${e.decl_params()})
226 % if e.params[0].type == 'VkDevice':
227 ANV_FROM_HANDLE(anv_device, anv_device, ${e.params[0].name});
228 return anv_device->dispatch.${e.name}(${e.call_params()});
230 ANV_FROM_HANDLE(anv_cmd_buffer, anv_cmd_buffer, ${e.params[0].name});
231 return anv_cmd_buffer->device->dispatch.${e.name}(${e.call_params()});
234 % if e.guard is not None:
239 const struct anv_dispatch_table anv_tramp_dispatch_table = {
240 % for e in entrypoints:
241 % if e.params[0].type not in ('VkDevice', 'VkCommandBuffer'):
244 % if e.guard is not None:
247 .${e.name} = ${e.prefixed_name('anv_tramp')},
248 % if e.guard is not None:
255 /** Return true if the core version or extension in which the given entrypoint
256 * is defined is enabled.
258 * If device is NULL, all device extensions are considered enabled.
261 anv_entrypoint_is_enabled(int index, uint32_t core_version,
262 const struct anv_instance_extension_table *instance,
263 const struct anv_device_extension_table *device)
266 % for e in entrypoints:
269 return ${e.core_version.c_vk_version()} <= core_version;
271 % if e.extension.type == 'instance':
272 return !device && instance->${e.extension.name[3:]};
274 return !device || device->${e.extension.name[3:]};
285 static void * __attribute__ ((noinline))
286 anv_resolve_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
288 if (devinfo == NULL) {
289 return anv_dispatch_table.entrypoints[index];
292 const struct anv_dispatch_table *genX_table;
293 switch (devinfo->gen) {
295 genX_table = &gen11_dispatch_table;
298 genX_table = &gen10_dispatch_table;
301 genX_table = &gen9_dispatch_table;
304 genX_table = &gen8_dispatch_table;
307 if (devinfo->is_haswell)
308 genX_table = &gen75_dispatch_table;
310 genX_table = &gen7_dispatch_table;
313 unreachable("unsupported gen\\n");
316 if (genX_table->entrypoints[index])
317 return genX_table->entrypoints[index];
319 return anv_dispatch_table.entrypoints[index];
323 anv_get_entrypoint_index(const char *name)
325 return string_map_lookup(name);
329 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
331 int idx = anv_get_entrypoint_index(name);
334 return anv_resolve_entrypoint(devinfo, idx);
335 }""", output_encoding
='utf-8')
339 HASH_MASK
= HASH_SIZE
- 1
341 PRIME_FACTOR
= 5024183
344 class StringIntMapEntry(object):
345 def __init__(self
, string
, num
):
349 # Calculate the same hash value that we will calculate in C.
352 h
= ((h
* PRIME_FACTOR
) + ord(c
)) & U32_MASK
357 class StringIntMap(object):
360 self
.strings
= dict()
362 def add_string(self
, string
, num
):
363 assert not self
.baked
364 assert string
not in self
.strings
365 assert num
>= 0 and num
< 2**31
366 self
.strings
[string
] = StringIntMapEntry(string
, num
)
369 self
.sorted_strings
= \
370 sorted(self
.strings
.values(), key
=lambda x
: x
.string
)
372 for entry
in self
.sorted_strings
:
373 entry
.offset
= offset
374 offset
+= len(entry
.string
) + 1
376 # Save off some values that we'll need in C
377 self
.hash_size
= HASH_SIZE
378 self
.hash_mask
= HASH_SIZE
- 1
379 self
.prime_factor
= PRIME_FACTOR
380 self
.prime_step
= PRIME_STEP
382 self
.mapping
= [-1] * self
.hash_size
383 self
.collisions
= [0] * 10
384 for idx
, s
in enumerate(self
.sorted_strings
):
387 while self
.mapping
[h
& self
.hash_mask
] >= 0:
390 self
.collisions
[min(level
, 9)] += 1
391 self
.mapping
[h
& self
.hash_mask
] = idx
393 EntrypointParam
= namedtuple('EntrypointParam', 'type name decl')
395 class Entrypoint(object):
396 def __init__(self
, name
, return_type
, params
, guard
= None):
398 self
.return_type
= return_type
403 # Extensions which require this entrypoint
404 self
.core_version
= None
405 self
.extension
= None
407 def prefixed_name(self
, prefix
):
408 assert self
.name
.startswith('vk')
409 return prefix
+ '_' + self
.name
[2:]
411 def decl_params(self
):
412 return ', '.join(p
.decl
for p
in self
.params
)
414 def call_params(self
):
415 return ', '.join(p
.name
for p
in self
.params
)
417 def get_entrypoints(doc
, entrypoints_to_defines
, start_index
):
418 """Extract the entry points from the registry."""
419 entrypoints
= OrderedDict()
421 for command
in doc
.findall('./commands/command'):
422 ret_type
= command
.find('./proto/type').text
423 fullname
= command
.find('./proto/name').text
424 params
= [EntrypointParam(
425 type = p
.find('./type').text
,
426 name
= p
.find('./name').text
,
427 decl
= ''.join(p
.itertext())
428 ) for p
in command
.findall('./param')]
429 guard
= entrypoints_to_defines
.get(fullname
)
430 # They really need to be unique
431 assert fullname
not in entrypoints
432 entrypoints
[fullname
] = Entrypoint(fullname
, ret_type
, params
, guard
)
434 enabled_commands
= set()
435 for feature
in doc
.findall('./feature'):
436 assert feature
.attrib
['api'] == 'vulkan'
437 version
= VkVersion(feature
.attrib
['number'])
438 if version
> MAX_API_VERSION
:
441 for command
in feature
.findall('./require/command'):
442 e
= entrypoints
[command
.attrib
['name']]
444 assert e
.core_version
is None
445 e
.core_version
= version
447 supported_exts
= dict((ext
.name
, ext
) for ext
in EXTENSIONS
)
448 for extension
in doc
.findall('.extensions/extension'):
449 ext_name
= extension
.attrib
['name']
450 if ext_name
not in supported_exts
:
453 if extension
.attrib
['supported'] != 'vulkan':
456 ext
= supported_exts
[ext_name
]
457 ext
.type = extension
.attrib
['type']
459 for command
in extension
.findall('./require/command'):
460 e
= entrypoints
[command
.attrib
['name']]
462 assert e
.core_version
is None
463 assert e
.extension
is None
466 return [e
for e
in entrypoints
.itervalues() if e
.enabled
]
469 def get_entrypoints_defines(doc
):
470 """Maps entry points to extension defines."""
471 entrypoints_to_defines
= {}
473 for extension
in doc
.findall('./extensions/extension[@protect]'):
474 define
= extension
.attrib
['protect']
476 for entrypoint
in extension
.findall('./require/command'):
477 fullname
= entrypoint
.attrib
['name']
478 entrypoints_to_defines
[fullname
] = define
480 return entrypoints_to_defines
484 parser
= argparse
.ArgumentParser()
485 parser
.add_argument('--outdir', help='Where to write the files.',
487 parser
.add_argument('--xml',
488 help='Vulkan API XML file.',
492 args
= parser
.parse_args()
496 for filename
in args
.xml_files
:
497 doc
= et
.parse(filename
)
498 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
),
499 start_index
=len(entrypoints
))
501 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
503 entrypoints
.append(Entrypoint('vkCreateDmaBufImageINTEL', 'VkResult', [
504 EntrypointParam('VkDevice', 'device', 'VkDevice device'),
505 EntrypointParam('VkDmaBufImageCreateInfo', 'pCreateInfo',
506 'const VkDmaBufImageCreateInfo* pCreateInfo'),
507 EntrypointParam('VkAllocationCallbacks', 'pAllocator',
508 'const VkAllocationCallbacks* pAllocator'),
509 EntrypointParam('VkDeviceMemory', 'pMem', 'VkDeviceMemory* pMem'),
510 EntrypointParam('VkImage', 'pImage', 'VkImage* pImage')
513 strmap
= StringIntMap()
514 for num
, e
in enumerate(entrypoints
):
515 strmap
.add_string(e
.name
, num
)
519 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
522 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.h'), 'wb') as f
:
523 f
.write(TEMPLATE_H
.render(entrypoints
=entrypoints
,
525 filename
=os
.path
.basename(__file__
)))
526 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.c'), 'wb') as f
:
527 f
.write(TEMPLATE_C
.render(entrypoints
=entrypoints
,
530 filename
=os
.path
.basename(__file__
)))
532 # In the even there's an error this imports some helpers from mako
533 # to print a useful stack trace and prints it, then exits with
534 # status 1, if python is run with debug; otherwise it just raises
538 from mako
import exceptions
539 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
544 if __name__
== '__main__':