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 VkVersion
, MAX_API_VERSION
, EXTENSIONS
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_instance_dispatch_table {
55 void *entrypoints[${len(instance_entrypoints)}];
57 % for e in instance_entrypoints:
58 % if e.guard is not None:
60 PFN_${e.name} ${e.name};
65 PFN_${e.name} ${e.name};
72 struct anv_device_dispatch_table {
74 void *entrypoints[${len(device_entrypoints)}];
76 % for e in device_entrypoints:
77 % if e.guard is not None:
79 PFN_${e.name} ${e.name};
84 PFN_${e.name} ${e.name};
91 extern const struct anv_instance_dispatch_table anv_instance_dispatch_table;
93 extern const struct anv_device_dispatch_table ${layer}_device_dispatch_table;
96 % for e in instance_entrypoints:
100 % if e.guard is not None:
103 ${e.return_type} ${e.prefixed_name('anv')}(${e.decl_params()});
104 % if e.guard is not None:
109 % for e in device_entrypoints:
113 % if e.guard is not None:
116 % for layer in LAYERS:
117 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
119 % if e.guard is not None:
123 """, output_encoding
='utf-8')
125 TEMPLATE_C
= Template(u
"""\
127 * Copyright © 2015 Intel Corporation
129 * Permission is hereby granted, free of charge, to any person obtaining a
130 * copy of this software and associated documentation files (the "Software"),
131 * to deal in the Software without restriction, including without limitation
132 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
133 * and/or sell copies of the Software, and to permit persons to whom the
134 * Software is furnished to do so, subject to the following conditions:
136 * The above copyright notice and this permission notice (including the next
137 * paragraph) shall be included in all copies or substantial portions of the
140 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
141 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
142 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
143 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
144 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
145 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
149 /* This file generated from ${filename}, don't edit directly. */
151 #include "anv_private.h"
153 struct string_map_entry {
159 /* We use a big string constant to avoid lots of reloctions from the entry
160 * point table to lots of little strings. The entries in the entry point table
161 * store the index into this big string.
164 <%def name="strmap(strmap, prefix)">
165 static const char ${prefix}_strings[] =
166 % for s in strmap.sorted_strings:
171 static const struct string_map_entry ${prefix}_string_map_entries[] = {
172 % for s in strmap.sorted_strings:
173 { ${s.offset}, ${'{:0=#8x}'.format(s.hash)}, ${s.num} }, /* ${s.string} */
178 * size ${len(strmap.sorted_strings)} entries
179 * collisions entries:
180 % for i in range(10):
181 * ${i}${'+' if i == 9 else ' '} ${strmap.collisions[i]}
186 static const uint16_t ${prefix}_string_map[${strmap.hash_size}] = {
187 % for e in strmap.mapping:
188 ${ '{:0=#6x}'.format(e) if e >= 0 else 'none' },
193 ${prefix}_string_map_lookup(const char *str)
195 static const uint32_t prime_factor = ${strmap.prime_factor};
196 static const uint32_t prime_step = ${strmap.prime_step};
197 const struct string_map_entry *e;
203 for (p = str; *p; p++)
204 hash = hash * prime_factor + *p;
208 i = ${prefix}_string_map[h & ${strmap.hash_mask}];
211 e = &${prefix}_string_map_entries[i];
212 if (e->hash == hash && strcmp(str, ${prefix}_strings + e->name) == 0)
221 ${strmap(instance_strmap, 'instance')}
222 ${strmap(device_strmap, 'device')}
224 /* Weak aliases for all potential implementations. These will resolve to
225 * NULL if they're not defined, which lets the resolve_entrypoint() function
226 * either pick the correct entry point.
229 % for e in instance_entrypoints:
233 % if e.guard is not None:
236 ${e.return_type} ${e.prefixed_name('anv')}(${e.decl_params()}) __attribute__ ((weak));
237 % if e.guard is not None:
242 const struct anv_instance_dispatch_table anv_instance_dispatch_table = {
243 % for e in instance_entrypoints:
244 % if e.guard is not None:
247 .${e.name} = ${e.prefixed_name('anv')},
248 % if e.guard is not None:
254 % for layer in LAYERS:
255 % for e in device_entrypoints:
259 % if e.guard is not None:
263 ${e.return_type} __attribute__ ((weak))
264 ${e.prefixed_name('anv')}(${e.decl_params()})
266 % if e.params[0].type == 'VkDevice':
267 ANV_FROM_HANDLE(anv_device, anv_device, ${e.params[0].name});
268 return anv_device->dispatch.${e.name}(${e.call_params()});
269 % elif e.params[0].type == 'VkCommandBuffer':
270 ANV_FROM_HANDLE(anv_cmd_buffer, anv_cmd_buffer, ${e.params[0].name});
271 return anv_cmd_buffer->device->dispatch.${e.name}(${e.call_params()});
272 % elif e.params[0].type == 'VkQueue':
273 ANV_FROM_HANDLE(anv_queue, anv_queue, ${e.params[0].name});
274 return anv_queue->device->dispatch.${e.name}(${e.call_params()});
276 assert(!"Unhandled device child trampoline case: ${e.params[0].type}");
280 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
282 % if e.guard is not None:
287 const struct anv_device_dispatch_table ${layer}_device_dispatch_table = {
288 % for e in device_entrypoints:
289 % if e.guard is not None:
292 .${e.name} = ${e.prefixed_name(layer)},
293 % if e.guard is not None:
301 /** Return true if the core version or extension in which the given entrypoint
302 * is defined is enabled.
304 * If device is NULL, all device extensions are considered enabled.
307 anv_instance_entrypoint_is_enabled(int index, uint32_t core_version,
308 const struct anv_instance_extension_table *instance)
311 % for e in instance_entrypoints:
315 return ${e.core_version.c_vk_version()} <= core_version;
317 % for ext in e.extensions:
318 % if ext.type == 'instance':
319 if (instance->${ext.name[3:]}) return true;
321 /* All device extensions are considered enabled at the instance level */
335 /** Return true if the core version or extension in which the given entrypoint
336 * is defined is enabled.
338 * If device is NULL, all device extensions are considered enabled.
341 anv_device_entrypoint_is_enabled(int index, uint32_t core_version,
342 const struct anv_instance_extension_table *instance,
343 const struct anv_device_extension_table *device)
346 % for e in device_entrypoints:
350 return ${e.core_version.c_vk_version()} <= core_version;
352 % for ext in e.extensions:
353 % if ext.type == 'instance':
356 if (!device || device->${ext.name[3:]}) return true;
370 anv_get_instance_entrypoint_index(const char *name)
372 return instance_string_map_lookup(name);
376 anv_get_device_entrypoint_index(const char *name)
378 return device_string_map_lookup(name);
381 static void * __attribute__ ((noinline))
382 anv_resolve_device_entrypoint(const struct gen_device_info *devinfo, uint32_t index)
384 const struct anv_device_dispatch_table *genX_table;
385 switch (devinfo->gen) {
387 genX_table = &gen11_device_dispatch_table;
390 genX_table = &gen10_device_dispatch_table;
393 genX_table = &gen9_device_dispatch_table;
396 genX_table = &gen8_device_dispatch_table;
399 if (devinfo->is_haswell)
400 genX_table = &gen75_device_dispatch_table;
402 genX_table = &gen7_device_dispatch_table;
405 unreachable("unsupported gen\\n");
408 if (genX_table->entrypoints[index])
409 return genX_table->entrypoints[index];
411 return anv_device_dispatch_table.entrypoints[index];
415 anv_lookup_entrypoint(const struct gen_device_info *devinfo, const char *name)
417 int idx = anv_get_instance_entrypoint_index(name);
419 return anv_instance_dispatch_table.entrypoints[idx];
421 idx = anv_get_device_entrypoint_index(name);
423 return anv_resolve_device_entrypoint(devinfo, idx);
426 }""", output_encoding
='utf-8')
430 PRIME_FACTOR
= 5024183
433 class StringIntMapEntry(object):
434 def __init__(self
, string
, num
):
438 # Calculate the same hash value that we will calculate in C.
441 h
= ((h
* PRIME_FACTOR
) + ord(c
)) & U32_MASK
446 def round_to_pow2(x
):
447 return 2**int(math
.ceil(math
.log(x
, 2)))
449 class StringIntMap(object):
452 self
.strings
= dict()
454 def add_string(self
, string
, num
):
455 assert not self
.baked
456 assert string
not in self
.strings
457 assert 0 <= num
< 2**31
458 self
.strings
[string
] = StringIntMapEntry(string
, num
)
461 self
.sorted_strings
= \
462 sorted(self
.strings
.values(), key
=lambda x
: x
.string
)
464 for entry
in self
.sorted_strings
:
465 entry
.offset
= offset
466 offset
+= len(entry
.string
) + 1
468 # Save off some values that we'll need in C
469 self
.hash_size
= round_to_pow2(len(self
.strings
) * 1.25)
470 self
.hash_mask
= self
.hash_size
- 1
471 self
.prime_factor
= PRIME_FACTOR
472 self
.prime_step
= PRIME_STEP
474 self
.mapping
= [-1] * self
.hash_size
475 self
.collisions
= [0] * 10
476 for idx
, s
in enumerate(self
.sorted_strings
):
479 while self
.mapping
[h
& self
.hash_mask
] >= 0:
482 self
.collisions
[min(level
, 9)] += 1
483 self
.mapping
[h
& self
.hash_mask
] = idx
485 EntrypointParam
= namedtuple('EntrypointParam', 'type name decl')
487 class EntrypointBase(object):
488 def __init__(self
, name
):
494 # Extensions which require this entrypoint
495 self
.core_version
= None
498 class Entrypoint(EntrypointBase
):
499 def __init__(self
, name
, return_type
, params
, guard
=None):
500 super(Entrypoint
, self
).__init
__(name
)
501 self
.return_type
= return_type
505 def is_device_entrypoint(self
):
506 return self
.params
[0].type in ('VkDevice', 'VkCommandBuffer', 'VkQueue')
508 def prefixed_name(self
, prefix
):
509 assert self
.name
.startswith('vk')
510 return prefix
+ '_' + self
.name
[2:]
512 def decl_params(self
):
513 return ', '.join(p
.decl
for p
in self
.params
)
515 def call_params(self
):
516 return ', '.join(p
.name
for p
in self
.params
)
518 class EntrypointAlias(EntrypointBase
):
519 def __init__(self
, name
, entrypoint
):
520 super(EntrypointAlias
, self
).__init
__(name
)
521 self
.alias
= entrypoint
523 def is_device_entrypoint(self
):
524 return self
.alias
.is_device_entrypoint()
526 def prefixed_name(self
, prefix
):
527 return self
.alias
.prefixed_name(prefix
)
529 def get_entrypoints(doc
, entrypoints_to_defines
):
530 """Extract the entry points from the registry."""
531 entrypoints
= OrderedDict()
533 for command
in doc
.findall('./commands/command'):
534 if 'alias' in command
.attrib
:
535 alias
= command
.attrib
['name']
536 target
= command
.attrib
['alias']
537 entrypoints
[alias
] = EntrypointAlias(alias
, entrypoints
[target
])
539 name
= command
.find('./proto/name').text
540 ret_type
= command
.find('./proto/type').text
541 params
= [EntrypointParam(
542 type=p
.find('./type').text
,
543 name
=p
.find('./name').text
,
544 decl
=''.join(p
.itertext())
545 ) for p
in command
.findall('./param')]
546 guard
= entrypoints_to_defines
.get(name
)
547 # They really need to be unique
548 assert name
not in entrypoints
549 entrypoints
[name
] = Entrypoint(name
, ret_type
, params
, guard
)
551 for feature
in doc
.findall('./feature'):
552 assert feature
.attrib
['api'] == 'vulkan'
553 version
= VkVersion(feature
.attrib
['number'])
554 if version
> MAX_API_VERSION
:
557 for command
in feature
.findall('./require/command'):
558 e
= entrypoints
[command
.attrib
['name']]
560 assert e
.core_version
is None
561 e
.core_version
= version
563 supported_exts
= dict((ext
.name
, ext
) for ext
in EXTENSIONS
)
564 for extension
in doc
.findall('.extensions/extension'):
565 ext_name
= extension
.attrib
['name']
566 if ext_name
not in supported_exts
:
569 ext
= supported_exts
[ext_name
]
570 ext
.type = extension
.attrib
['type']
572 for command
in extension
.findall('./require/command'):
573 e
= entrypoints
[command
.attrib
['name']]
575 assert e
.core_version
is None
576 e
.extensions
.append(ext
)
578 return [e
for e
in entrypoints
.values() if e
.enabled
]
581 def get_entrypoints_defines(doc
):
582 """Maps entry points to extension defines."""
583 entrypoints_to_defines
= {}
586 for platform
in doc
.findall('./platforms/platform'):
587 name
= platform
.attrib
['name']
588 define
= platform
.attrib
['protect']
589 platform_define
[name
] = define
591 for extension
in doc
.findall('./extensions/extension[@platform]'):
592 platform
= extension
.attrib
['platform']
593 define
= platform_define
[platform
]
595 for entrypoint
in extension
.findall('./require/command'):
596 fullname
= entrypoint
.attrib
['name']
597 entrypoints_to_defines
[fullname
] = define
599 return entrypoints_to_defines
603 parser
= argparse
.ArgumentParser()
604 parser
.add_argument('--outdir', help='Where to write the files.',
606 parser
.add_argument('--xml',
607 help='Vulkan API XML file.',
611 args
= parser
.parse_args()
615 for filename
in args
.xml_files
:
616 doc
= et
.parse(filename
)
617 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
))
619 # Manually add CreateDmaBufImageINTEL for which we don't have an extension
621 entrypoints
.append(Entrypoint('vkCreateDmaBufImageINTEL', 'VkResult', [
622 EntrypointParam('VkDevice', 'device', 'VkDevice device'),
623 EntrypointParam('VkDmaBufImageCreateInfo', 'pCreateInfo',
624 'const VkDmaBufImageCreateInfo* pCreateInfo'),
625 EntrypointParam('VkAllocationCallbacks', 'pAllocator',
626 'const VkAllocationCallbacks* pAllocator'),
627 EntrypointParam('VkDeviceMemory', 'pMem', 'VkDeviceMemory* pMem'),
628 EntrypointParam('VkImage', 'pImage', 'VkImage* pImage')
631 device_entrypoints
= []
632 instance_entrypoints
= []
633 for e
in entrypoints
:
634 if e
.is_device_entrypoint():
635 device_entrypoints
.append(e
)
637 instance_entrypoints
.append(e
)
639 device_strmap
= StringIntMap()
640 for num
, e
in enumerate(device_entrypoints
):
641 device_strmap
.add_string(e
.name
, num
)
645 instance_strmap
= StringIntMap()
646 for num
, e
in enumerate(instance_entrypoints
):
647 instance_strmap
.add_string(e
.name
, num
)
649 instance_strmap
.bake()
651 # For outputting entrypoints.h we generate a anv_EntryPoint() prototype
654 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.h'), 'wb') as f
:
655 f
.write(TEMPLATE_H
.render(instance_entrypoints
=instance_entrypoints
,
656 device_entrypoints
=device_entrypoints
,
658 filename
=os
.path
.basename(__file__
)))
659 with
open(os
.path
.join(args
.outdir
, 'anv_entrypoints.c'), 'wb') as f
:
660 f
.write(TEMPLATE_C
.render(instance_entrypoints
=instance_entrypoints
,
661 device_entrypoints
=device_entrypoints
,
663 instance_strmap
=instance_strmap
,
664 device_strmap
=device_strmap
,
665 filename
=os
.path
.basename(__file__
)))
667 # In the event there's an error, this imports some helpers from mako
668 # to print a useful stack trace and prints it, then exits with
669 # status 1, if python is run with debug; otherwise it just raises
673 from mako
import exceptions
674 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
679 if __name__
== '__main__':