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 radv_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
46 TEMPLATE_H
= Template("""\
47 /* This file generated from ${filename}, don't edit directly. */
49 struct radv_instance_dispatch_table {
51 void *entrypoints[${len(instance_entrypoints)}];
53 % for e in instance_entrypoints:
54 % if e.guard is not None:
56 PFN_${e.name} ${e.name};
61 PFN_${e.name} ${e.name};
68 struct radv_physical_device_dispatch_table {
70 void *entrypoints[${len(physical_device_entrypoints)}];
72 % for e in physical_device_entrypoints:
73 % if e.guard is not None:
75 PFN_${e.name} ${e.name};
80 PFN_${e.name} ${e.name};
87 struct radv_device_dispatch_table {
89 void *entrypoints[${len(device_entrypoints)}];
91 % for e in device_entrypoints:
92 % if e.guard is not None:
94 PFN_${e.name} ${e.name};
99 PFN_${e.name} ${e.name};
106 extern const struct radv_instance_dispatch_table radv_instance_dispatch_table;
107 %for layer in LAYERS:
108 extern const struct radv_physical_device_dispatch_table ${layer}_physical_device_dispatch_table;
110 %for layer in LAYERS:
111 extern const struct radv_device_dispatch_table ${layer}_device_dispatch_table;
114 % for e in instance_entrypoints:
115 % if e.alias and e.alias.enabled:
118 % if e.guard is not None:
121 ${e.return_type} ${e.prefixed_name('radv')}(${e.decl_params()});
122 % if e.guard is not None:
127 % for e in physical_device_entrypoints:
131 % if e.guard is not None:
134 % for layer in LAYERS:
135 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
137 % if e.guard is not None:
142 % for e in device_entrypoints:
143 % if e.alias and e.alias.enabled:
146 % if e.guard is not None:
149 % for layer in LAYERS:
150 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()});
152 % if e.guard is not None:
156 """, output_encoding
='utf-8')
158 TEMPLATE_C
= Template(u
"""\
160 * Copyright © 2015 Intel Corporation
162 * Permission is hereby granted, free of charge, to any person obtaining a
163 * copy of this software and associated documentation files (the "Software"),
164 * to deal in the Software without restriction, including without limitation
165 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
166 * and/or sell copies of the Software, and to permit persons to whom the
167 * Software is furnished to do so, subject to the following conditions:
169 * The above copyright notice and this permission notice (including the next
170 * paragraph) shall be included in all copies or substantial portions of the
173 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
174 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
175 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
176 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
177 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
178 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
182 /* This file generated from ${filename}, don't edit directly. */
184 #include "radv_private.h"
186 #include "util/macros.h"
188 struct string_map_entry {
194 /* We use a big string constant to avoid lots of reloctions from the entry
195 * point table to lots of little strings. The entries in the entry point table
196 * store the index into this big string.
199 <%def name="strmap(strmap, prefix)">
200 static const char ${prefix}_strings[] =
201 % for s in strmap.sorted_strings:
206 static const struct string_map_entry ${prefix}_string_map_entries[] = {
207 % for s in strmap.sorted_strings:
208 { ${s.offset}, ${'{:0=#8x}'.format(s.hash)}, ${s.num} }, /* ${s.string} */
213 * size ${len(strmap.sorted_strings)} entries
214 * collisions entries:
215 % for i in range(10):
216 * ${i}${'+' if i == 9 else ' '} ${strmap.collisions[i]}
221 static const uint16_t ${prefix}_string_map[${strmap.hash_size}] = {
222 % for e in strmap.mapping:
223 ${ '{:0=#6x}'.format(e) if e >= 0 else 'none' },
228 ${prefix}_string_map_lookup(const char *str)
230 static const uint32_t prime_factor = ${strmap.prime_factor};
231 static const uint32_t prime_step = ${strmap.prime_step};
232 const struct string_map_entry *e;
238 for (p = str; *p; p++)
239 hash = hash * prime_factor + *p;
243 i = ${prefix}_string_map[h & ${strmap.hash_mask}];
246 e = &${prefix}_string_map_entries[i];
247 if (e->hash == hash && strcmp(str, ${prefix}_strings + e->name) == 0)
256 ${prefix}_entry_name(int num)
258 for (int i = 0; i < ARRAY_SIZE(${prefix}_string_map_entries); i++) {
259 if (${prefix}_string_map_entries[i].num == num)
260 return &${prefix}_strings[${prefix}_string_map_entries[i].name];
266 ${strmap(instance_strmap, 'instance')}
267 ${strmap(physical_device_strmap, 'physical_device')}
268 ${strmap(device_strmap, 'device')}
270 /* Weak aliases for all potential implementations. These will resolve to
271 * NULL if they're not defined, which lets the resolve_entrypoint() function
272 * either pick the correct entry point.
275 % for e in instance_entrypoints:
276 % if e.alias and e.alias.enabled:
279 % if e.guard is not None:
282 ${e.return_type} ${e.prefixed_name('radv')}(${e.decl_params()}) __attribute__ ((weak));
283 % if e.guard is not None:
288 const struct radv_instance_dispatch_table radv_instance_dispatch_table = {
289 % for e in instance_entrypoints:
290 % if e.guard is not None:
293 .${e.name} = ${e.prefixed_name('radv')},
294 % if e.guard is not None:
300 % for e in physical_device_entrypoints:
301 % if e.alias and e.alias.enabled:
304 % if e.guard is not None:
307 ${e.return_type} ${e.prefixed_name('radv')}(${e.decl_params()}) __attribute__ ((weak));
308 % if e.guard is not None:
313 const struct radv_physical_device_dispatch_table radv_physical_device_dispatch_table = {
314 % for e in physical_device_entrypoints:
315 % if e.guard is not None:
318 .${e.name} = ${e.prefixed_name('radv')},
319 % if e.guard is not None:
326 % for layer in LAYERS:
327 % for e in device_entrypoints:
328 % if e.alias and e.alias.enabled:
331 % if e.guard is not None:
334 % if layer == 'radv':
335 ${e.return_type} __attribute__ ((weak))
336 ${e.prefixed_name('radv')}(${e.decl_params()})
338 % if e.params[0].type == 'VkDevice':
339 RADV_FROM_HANDLE(radv_device, radv_device, ${e.params[0].name});
340 return radv_device->dispatch.${e.name}(${e.call_params()});
341 % elif e.params[0].type == 'VkCommandBuffer':
342 RADV_FROM_HANDLE(radv_cmd_buffer, radv_cmd_buffer, ${e.params[0].name});
343 return radv_cmd_buffer->device->dispatch.${e.name}(${e.call_params()});
344 % elif e.params[0].type == 'VkQueue':
345 RADV_FROM_HANDLE(radv_queue, radv_queue, ${e.params[0].name});
346 return radv_queue->device->dispatch.${e.name}(${e.call_params()});
348 assert(!"Unhandled device child trampoline case: ${e.params[0].type}");
352 ${e.return_type} ${e.prefixed_name(layer)}(${e.decl_params()}) __attribute__ ((weak));
354 % if e.guard is not None:
359 const struct radv_device_dispatch_table ${layer}_device_dispatch_table = {
360 % for e in device_entrypoints:
361 % if e.guard is not None:
364 .${e.name} = ${e.prefixed_name(layer)},
365 % if e.guard is not None:
373 /** Return true if the core version or extension in which the given entrypoint
374 * is defined is enabled.
376 * If device is NULL, all device extensions are considered enabled.
379 radv_instance_entrypoint_is_enabled(int index, uint32_t core_version,
380 const struct radv_instance_extension_table *instance)
383 % for e in instance_entrypoints:
387 return ${e.core_version.c_vk_version()} <= core_version;
389 % for ext in e.extensions:
390 % if ext.type == 'instance':
391 if (instance->${ext.name[3:]}) return true;
393 /* All device extensions are considered enabled at the instance level */
407 /** Return true if the core version or extension in which the given entrypoint
408 * is defined is enabled.
410 * If device is NULL, all device extensions are considered enabled.
413 radv_physical_device_entrypoint_is_enabled(int index, uint32_t core_version,
414 const struct radv_instance_extension_table *instance)
417 % for e in physical_device_entrypoints:
421 return ${e.core_version.c_vk_version()} <= core_version;
423 % for ext in e.extensions:
424 % if ext.type == 'instance':
425 if (instance->${ext.name[3:]}) return true;
427 /* All device extensions are considered enabled at the instance level */
441 /** Return true if the core version or extension in which the given entrypoint
442 * is defined is enabled.
444 * If device is NULL, all device extensions are considered enabled.
447 radv_device_entrypoint_is_enabled(int index, uint32_t core_version,
448 const struct radv_instance_extension_table *instance,
449 const struct radv_device_extension_table *device)
452 % for e in device_entrypoints:
456 return ${e.core_version.c_vk_version()} <= core_version;
458 % for ext in e.extensions:
459 % if ext.type == 'instance':
462 if (!device || device->${ext.name[3:]}) return true;
476 radv_get_instance_entrypoint_index(const char *name)
478 return instance_string_map_lookup(name);
482 radv_get_physical_device_entrypoint_index(const char *name)
484 return physical_device_string_map_lookup(name);
488 radv_get_device_entrypoint_index(const char *name)
490 return device_string_map_lookup(name);
494 radv_get_instance_entry_name(int index)
496 return instance_entry_name(index);
500 radv_get_physical_device_entry_name(int index)
502 return physical_device_entry_name(index);
506 radv_get_device_entry_name(int index)
508 return device_entry_name(index);
511 static void * __attribute__ ((noinline))
512 radv_resolve_device_entrypoint(uint32_t index)
514 return radv_device_dispatch_table.entrypoints[index];
518 radv_lookup_entrypoint(const char *name)
520 int idx = radv_get_instance_entrypoint_index(name);
522 return radv_instance_dispatch_table.entrypoints[idx];
524 idx = radv_get_physical_device_entrypoint_index(name);
526 return radv_physical_device_dispatch_table.entrypoints[idx];
528 idx = radv_get_device_entrypoint_index(name);
530 return radv_resolve_device_entrypoint(idx);
533 }""", output_encoding
='utf-8')
537 PRIME_FACTOR
= 5024183
540 def round_to_pow2(x
):
541 return 2**int(math
.ceil(math
.log(x
, 2)))
543 class StringIntMapEntry(object):
544 def __init__(self
, string
, num
):
548 # Calculate the same hash value that we will calculate in C.
551 h
= ((h
* PRIME_FACTOR
) + ord(c
)) & U32_MASK
556 class StringIntMap(object):
559 self
.strings
= dict()
561 def add_string(self
, string
, num
):
562 assert not self
.baked
563 assert string
not in self
.strings
564 assert num
>= 0 and num
< 2**31
565 self
.strings
[string
] = StringIntMapEntry(string
, num
)
568 self
.sorted_strings
= \
569 sorted(self
.strings
.values(), key
=lambda x
: x
.string
)
571 for entry
in self
.sorted_strings
:
572 entry
.offset
= offset
573 offset
+= len(entry
.string
) + 1
575 # Save off some values that we'll need in C
576 self
.hash_size
= round_to_pow2(len(self
.strings
) * 1.25)
577 self
.hash_mask
= self
.hash_size
- 1
578 self
.prime_factor
= PRIME_FACTOR
579 self
.prime_step
= PRIME_STEP
581 self
.mapping
= [-1] * self
.hash_size
582 self
.collisions
= [0] * 10
583 for idx
, s
in enumerate(self
.sorted_strings
):
586 while self
.mapping
[h
& self
.hash_mask
] >= 0:
589 self
.collisions
[min(level
, 9)] += 1
590 self
.mapping
[h
& self
.hash_mask
] = idx
592 EntrypointParam
= namedtuple('EntrypointParam', 'type name decl')
594 class EntrypointBase(object):
595 def __init__(self
, name
):
601 # Extensions which require this entrypoint
602 self
.core_version
= None
605 def prefixed_name(self
, prefix
):
606 assert self
.name
.startswith('vk')
607 return prefix
+ '_' + self
.name
[2:]
609 class Entrypoint(EntrypointBase
):
610 def __init__(self
, name
, return_type
, params
, guard
= None):
611 super(Entrypoint
, self
).__init
__(name
)
612 self
.return_type
= return_type
616 def is_physical_device_entrypoint(self
):
617 return self
.params
[0].type in ('VkPhysicalDevice', )
619 def is_device_entrypoint(self
):
620 return self
.params
[0].type in ('VkDevice', 'VkCommandBuffer', 'VkQueue')
622 def decl_params(self
):
623 return ', '.join(p
.decl
for p
in self
.params
)
625 def call_params(self
):
626 return ', '.join(p
.name
for p
in self
.params
)
628 class EntrypointAlias(EntrypointBase
):
629 def __init__(self
, name
, entrypoint
):
630 super(EntrypointAlias
, self
).__init
__(name
)
631 self
.alias
= entrypoint
633 def is_physical_device_entrypoint(self
):
634 return self
.alias
.is_physical_device_entrypoint()
636 def is_device_entrypoint(self
):
637 return self
.alias
.is_device_entrypoint()
639 def prefixed_name(self
, prefix
):
640 if self
.alias
.enabled
:
641 return self
.alias
.prefixed_name(prefix
)
642 return super(EntrypointAlias
, self
).prefixed_name(prefix
)
646 return self
.alias
.params
649 def return_type(self
):
650 return self
.alias
.return_type
652 def decl_params(self
):
653 return self
.alias
.decl_params()
655 def call_params(self
):
656 return self
.alias
.call_params()
658 def get_entrypoints(doc
, entrypoints_to_defines
):
659 """Extract the entry points from the registry."""
660 entrypoints
= OrderedDict()
662 for command
in doc
.findall('./commands/command'):
663 if 'alias' in command
.attrib
:
664 alias
= command
.attrib
['name']
665 target
= command
.attrib
['alias']
666 entrypoints
[alias
] = EntrypointAlias(alias
, entrypoints
[target
])
668 name
= command
.find('./proto/name').text
669 ret_type
= command
.find('./proto/type').text
670 params
= [EntrypointParam(
671 type = p
.find('./type').text
,
672 name
= p
.find('./name').text
,
673 decl
= ''.join(p
.itertext())
674 ) for p
in command
.findall('./param')]
675 guard
= entrypoints_to_defines
.get(name
)
676 # They really need to be unique
677 assert name
not in entrypoints
678 entrypoints
[name
] = Entrypoint(name
, ret_type
, params
, guard
)
680 for feature
in doc
.findall('./feature'):
681 assert feature
.attrib
['api'] == 'vulkan'
682 version
= VkVersion(feature
.attrib
['number'])
683 if version
> MAX_API_VERSION
:
686 for command
in feature
.findall('./require/command'):
687 e
= entrypoints
[command
.attrib
['name']]
689 assert e
.core_version
is None
690 e
.core_version
= version
692 supported_exts
= dict((ext
.name
, ext
) for ext
in EXTENSIONS
)
693 for extension
in doc
.findall('.extensions/extension'):
694 ext_name
= extension
.attrib
['name']
695 if ext_name
not in supported_exts
:
698 ext
= supported_exts
[ext_name
]
699 ext
.type = extension
.attrib
['type']
701 for command
in extension
.findall('./require/command'):
702 e
= entrypoints
[command
.attrib
['name']]
704 assert e
.core_version
is None
705 e
.extensions
.append(ext
)
707 # if the base command is not supported by the driver yet, don't alias aliases
708 for e
in entrypoints
.values():
709 if e
.alias
and not e
.alias
.enabled
:
710 e_clone
= copy
.deepcopy(e
.alias
)
711 e_clone
.enabled
= True
712 e_clone
.name
= e
.name
713 entrypoints
[e
.name
] = e_clone
715 return [e
for e
in entrypoints
.values() if e
.enabled
]
718 def get_entrypoints_defines(doc
):
719 """Maps entry points to extension defines."""
720 entrypoints_to_defines
= {}
723 for platform
in doc
.findall('./platforms/platform'):
724 name
= platform
.attrib
['name']
725 define
= platform
.attrib
['protect']
726 platform_define
[name
] = define
728 for extension
in doc
.findall('./extensions/extension[@platform]'):
729 platform
= extension
.attrib
['platform']
730 define
= platform_define
[platform
]
732 for entrypoint
in extension
.findall('./require/command'):
733 fullname
= entrypoint
.attrib
['name']
734 entrypoints_to_defines
[fullname
] = define
736 return entrypoints_to_defines
739 parser
= argparse
.ArgumentParser()
740 parser
.add_argument('--outdir', help='Where to write the files.',
742 parser
.add_argument('--xml',
743 help='Vulkan API XML file.',
747 args
= parser
.parse_args()
751 for filename
in args
.xml_files
:
752 doc
= et
.parse(filename
)
753 entrypoints
+= get_entrypoints(doc
, get_entrypoints_defines(doc
))
755 device_entrypoints
= []
756 physical_device_entrypoints
= []
757 instance_entrypoints
= []
758 for e
in entrypoints
:
759 if e
.is_device_entrypoint():
760 device_entrypoints
.append(e
)
761 elif e
.is_physical_device_entrypoint():
762 physical_device_entrypoints
.append(e
)
764 instance_entrypoints
.append(e
)
766 device_strmap
= StringIntMap()
767 for num
, e
in enumerate(device_entrypoints
):
768 device_strmap
.add_string(e
.name
, num
)
772 physical_device_strmap
= StringIntMap()
773 for num
, e
in enumerate(physical_device_entrypoints
):
774 physical_device_strmap
.add_string(e
.name
, num
)
776 physical_device_strmap
.bake()
778 instance_strmap
= StringIntMap()
779 for num
, e
in enumerate(instance_entrypoints
):
780 instance_strmap
.add_string(e
.name
, num
)
782 instance_strmap
.bake()
784 # For outputting entrypoints.h we generate a radv_EntryPoint() prototype
787 with
open(os
.path
.join(args
.outdir
, 'radv_entrypoints.h'), 'wb') as f
:
788 f
.write(TEMPLATE_H
.render(instance_entrypoints
=instance_entrypoints
,
789 physical_device_entrypoints
=physical_device_entrypoints
,
790 device_entrypoints
=device_entrypoints
,
792 filename
=os
.path
.basename(__file__
)))
793 with
open(os
.path
.join(args
.outdir
, 'radv_entrypoints.c'), 'wb') as f
:
794 f
.write(TEMPLATE_C
.render(instance_entrypoints
=instance_entrypoints
,
795 physical_device_entrypoints
=physical_device_entrypoints
,
796 device_entrypoints
=device_entrypoints
,
798 instance_strmap
=instance_strmap
,
799 physical_device_strmap
=physical_device_strmap
,
800 device_strmap
=device_strmap
,
801 filename
=os
.path
.basename(__file__
)))
803 # In the event there's an error, this imports some helpers from mako
804 # to print a useful stack trace and prints it, then exits with
805 # status 1, if python is run with debug; otherwise it just raises
809 from mako
import exceptions
810 sys
.stderr
.write(exceptions
.text_error_template().render() + '\n')
815 if __name__
== '__main__':