blob: 6663df0b701f6bd58e3fba8e563b163fd8414102 [file] [log] [blame]
Mark Lobodzinskia509c292016-10-11 14:33:07 -06001#!/usr/bin/python3 -i
2#
3# Copyright (c) 2015-2016 The Khronos Group Inc.
4# Copyright (c) 2015-2016 Valve Corporation
5# Copyright (c) 2015-2016 LunarG, Inc.
6# Copyright (c) 2015-2016 Google Inc.
7#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19#
20# Author: Tobin Ehlis <tobine@google.com>
21# Author: Mark Lobodzinski <mark@lunarg.com>
22
23import os,re,sys
24import xml.etree.ElementTree as etree
25from generator import *
26from collections import namedtuple
27
28# UniqueObjectsGeneratorOptions - subclass of GeneratorOptions.
29#
30# Adds options used by UniqueObjectsOutputGenerator objects during
31# unique objects layer generation.
32#
33# Additional members
34# prefixText - list of strings to prefix generated header with
35# (usually a copyright statement + calling convention macros).
36# protectFile - True if multiple inclusion protection should be
37# generated (based on the filename) around the entire header.
38# protectFeature - True if #ifndef..#endif protection should be
39# generated around a feature interface in the header file.
40# genFuncPointers - True if function pointer typedefs should be
41# generated
42# protectProto - If conditional protection should be generated
43# around prototype declarations, set to either '#ifdef'
44# to require opt-in (#ifdef protectProtoStr) or '#ifndef'
45# to require opt-out (#ifndef protectProtoStr). Otherwise
46# set to None.
47# protectProtoStr - #ifdef/#ifndef symbol to use around prototype
48# declarations, if protectProto is set
49# apicall - string to use for the function declaration prefix,
50# such as APICALL on Windows.
51# apientry - string to use for the calling convention macro,
52# in typedefs, such as APIENTRY.
53# apientryp - string to use for the calling convention macro
54# in function pointer typedefs, such as APIENTRYP.
55# indentFuncProto - True if prototype declarations should put each
56# parameter on a separate line
57# indentFuncPointer - True if typedefed function pointers should put each
58# parameter on a separate line
59# alignFuncParam - if nonzero and parameters are being put on a
60# separate line, align parameter names at the specified column
61class UniqueObjectsGeneratorOptions(GeneratorOptions):
62 def __init__(self,
63 filename = None,
64 directory = '.',
65 apiname = None,
66 profile = None,
67 versions = '.*',
68 emitversions = '.*',
69 defaultExtensions = None,
70 addExtensions = None,
71 removeExtensions = None,
72 sortProcedure = regSortFeatures,
73 prefixText = "",
74 genFuncPointers = True,
75 protectFile = True,
76 protectFeature = True,
77 protectProto = None,
78 protectProtoStr = None,
79 apicall = '',
80 apientry = '',
81 apientryp = '',
82 indentFuncProto = True,
83 indentFuncPointer = False,
84 alignFuncParam = 0):
85 GeneratorOptions.__init__(self, filename, directory, apiname, profile,
86 versions, emitversions, defaultExtensions,
87 addExtensions, removeExtensions, sortProcedure)
88 self.prefixText = prefixText
89 self.genFuncPointers = genFuncPointers
90 self.protectFile = protectFile
91 self.protectFeature = protectFeature
92 self.protectProto = protectProto
93 self.protectProtoStr = protectProtoStr
94 self.apicall = apicall
95 self.apientry = apientry
96 self.apientryp = apientryp
97 self.indentFuncProto = indentFuncProto
98 self.indentFuncPointer = indentFuncPointer
99 self.alignFuncParam = alignFuncParam
100
101# UniqueObjectsOutputGenerator - subclass of OutputGenerator.
102# Generates unique objects layer non-dispatchable handle-wrapping code.
103#
104# ---- methods ----
105# UniqueObjectsOutputGenerator(errFile, warnFile, diagFile) - args as for OutputGenerator. Defines additional internal state.
106# ---- methods overriding base class ----
107# beginFile(genOpts)
108# endFile()
109# beginFeature(interface, emit)
110# endFeature()
111# genCmd(cmdinfo)
112# genStruct()
113# genType()
114class UniqueObjectsOutputGenerator(OutputGenerator):
115 """Generate UniqueObjects code based on XML element attributes"""
116 # This is an ordered list of sections in the header file.
117 ALL_SECTIONS = ['command']
118 def __init__(self,
119 errFile = sys.stderr,
120 warnFile = sys.stderr,
121 diagFile = sys.stdout):
122 OutputGenerator.__init__(self, errFile, warnFile, diagFile)
123 self.INDENT_SPACES = 4
124 # Commands to ignore
125 self.intercepts = []
126 # Commands which are not autogenerated but still intercepted
127 self.no_autogen_list = [
Jamie Madill24aa9742016-12-13 17:02:57 -0500128 'vkGetDeviceProcAddr',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600129 'vkGetInstanceProcAddr',
130 'vkCreateInstance',
131 'vkDestroyInstance',
132 'vkCreateDevice',
133 'vkDestroyDevice',
134 'vkAllocateMemory',
135 'vkCreateComputePipelines',
136 'vkCreateGraphicsPipelines',
137 'vkCreateSwapchainKHR',
138 'vkGetSwapchainImagesKHR',
139 'vkEnumerateInstanceLayerProperties',
140 'vkEnumerateDeviceLayerProperties',
141 'vkEnumerateInstanceExtensionProperties',
142 ]
143 # Commands shadowed by interface functions and are not implemented
144 self.interface_functions = [
145 'vkGetPhysicalDeviceDisplayPropertiesKHR',
146 'vkGetPhysicalDeviceDisplayPlanePropertiesKHR',
147 'vkGetDisplayPlaneSupportedDisplaysKHR',
148 'vkGetDisplayModePropertiesKHR',
Norbert Nopper1dec9a52016-11-25 07:55:13 +0100149 'vkGetDisplayPlaneCapabilitiesKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600150 # DebugReport APIs are hooked, but handled separately in the source file
151 'vkCreateDebugReportCallbackEXT',
152 'vkDestroyDebugReportCallbackEXT',
153 'vkDebugReportMessageEXT',
154 ]
155 self.headerVersion = None
156 # Internal state - accumulators for different inner block text
157 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
158 self.structNames = [] # List of Vulkan struct typenames
159 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
160 self.handleTypes = set() # Set of handle type names
161 self.commands = [] # List of CommandData records for all Vulkan commands
162 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
163 self.flags = set() # Map of flags typenames
164 # Named tuples to store struct and command data
165 self.StructType = namedtuple('StructType', ['name', 'value'])
166 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy'])
167 self.CommandData = namedtuple('CommandData', ['name', 'return_type', 'params', 'cdecl'])
168 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
169 #
170 def incIndent(self, indent):
171 inc = ' ' * self.INDENT_SPACES
172 if indent:
173 return indent + inc
174 return inc
175 #
176 def decIndent(self, indent):
177 if indent and (len(indent) > self.INDENT_SPACES):
178 return indent[:-self.INDENT_SPACES]
179 return ''
180 #
181 # Override makeProtoName to drop the "vk" prefix
182 def makeProtoName(self, name, tail):
183 return self.genOpts.apientry + name[2:] + tail
184 #
185 # Check if the parameter passed in is a pointer to an array
186 def paramIsArray(self, param):
187 return param.attrib.get('len') is not None
188 #
189 def beginFile(self, genOpts):
190 OutputGenerator.beginFile(self, genOpts)
191 # User-supplied prefix text, if any (list of strings)
192 if (genOpts.prefixText):
193 for s in genOpts.prefixText:
194 write(s, file=self.outFile)
195 # Namespace
196 self.newline()
197 write('namespace unique_objects {', file = self.outFile)
198 #
199 def endFile(self):
200 self.newline()
201 # Record intercepted procedures
202 write('// intercepts', file=self.outFile)
203 write('struct { const char* name; PFN_vkVoidFunction pFunc;} procmap[] = {', file=self.outFile)
204 write('\n'.join(self.intercepts), file=self.outFile)
205 write('};\n', file=self.outFile)
206 self.newline()
207 write('} // namespace unique_objects', file=self.outFile)
208 # Finish processing in superclass
209 OutputGenerator.endFile(self)
210 #
211 def beginFeature(self, interface, emit):
212 # Start processing in superclass
213 OutputGenerator.beginFeature(self, interface, emit)
214 self.headerVersion = None
215 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
216 self.structNames = []
217 self.structTypes = dict()
218 self.handleTypes = set()
219 self.commands = []
220 self.structMembers = []
221 self.cmdMembers = []
222 self.flags = set()
223 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
224 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
225 #
226 def endFeature(self):
227 # Actually write the interface to the output file.
228 if (self.emit):
229 self.newline()
230 if (self.featureExtraProtect != None):
231 write('#ifdef', self.featureExtraProtect, file=self.outFile)
232 # Write the unique_objects code to the file
233 if (self.sections['command']):
234 if (self.genOpts.protectProto):
235 write(self.genOpts.protectProto,
236 self.genOpts.protectProtoStr, file=self.outFile)
Jamie Madill24aa9742016-12-13 17:02:57 -0500237 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600238 if (self.featureExtraProtect != None):
239 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
240 else:
241 self.newline()
242 # Finish processing in superclass
243 OutputGenerator.endFeature(self)
244 #
245 def genType(self, typeinfo, name):
246 OutputGenerator.genType(self, typeinfo, name)
247 typeElem = typeinfo.elem
248 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
249 # Otherwise, emit the tag text.
250 category = typeElem.get('category')
251 if (category == 'struct' or category == 'union'):
252 self.structNames.append(name)
253 self.genStruct(typeinfo, name)
254 #
255 # Append a definition to the specified section
256 def appendSection(self, section, text):
257 # self.sections[section].append('SECTION: ' + section + '\n')
258 self.sections[section].append(text)
259 #
260 # Check if the parameter passed in is a pointer
261 def paramIsPointer(self, param):
262 ispointer = False
263 for elem in param:
264 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
265 ispointer = True
266 return ispointer
267 #
268 # Get the category of a type
269 def getTypeCategory(self, typename):
270 types = self.registry.tree.findall("types/type")
271 for elem in types:
272 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
273 return elem.attrib.get('category')
274 #
275 # Check if a parent object is dispatchable or not
276 def isHandleTypeNonDispatchable(self, handletype):
277 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
278 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
279 return True
280 else:
281 return False
282 #
283 # Retrieve the type and name for a parameter
284 def getTypeNameTuple(self, param):
285 type = ''
286 name = ''
287 for elem in param:
288 if elem.tag == 'type':
289 type = noneStr(elem.text)
290 elif elem.tag == 'name':
291 name = noneStr(elem.text)
292 return (type, name)
293 #
294 # Retrieve the value of the len tag
295 def getLen(self, param):
296 result = None
297 len = param.attrib.get('len')
298 if len and len != 'null-terminated':
299 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
300 # have a null terminated array of strings. We strip the null-terminated from the
301 # 'len' field and only return the parameter specifying the string count
302 if 'null-terminated' in len:
303 result = len.split(',')[0]
304 else:
305 result = len
306 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
307 result = str(result).replace('::', '->')
308 return result
309 #
310 # Generate a VkStructureType based on a structure typename
311 def genVkStructureType(self, typename):
312 # Add underscore between lowercase then uppercase
313 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
314 # Change to uppercase
315 value = value.upper()
316 # Add STRUCTURE_TYPE_
317 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
318 #
319 # Struct parameter check generation.
320 # This is a special case of the <type> tag where the contents are interpreted as a set of
321 # <member> tags instead of freeform C type declarations. The <member> tags are just like
322 # <param> tags - they are a declaration of a struct or union member. Only simple member
323 # declarations are supported (no nested structs etc.)
324 def genStruct(self, typeinfo, typeName):
325 OutputGenerator.genStruct(self, typeinfo, typeName)
326 members = typeinfo.elem.findall('.//member')
327 # Iterate over members once to get length parameters for arrays
328 lens = set()
329 for member in members:
330 len = self.getLen(member)
331 if len:
332 lens.add(len)
333 # Generate member info
334 membersInfo = []
335 for member in members:
336 # Get the member's type and name
337 info = self.getTypeNameTuple(member)
338 type = info[0]
339 name = info[1]
340 cdecl = self.makeCParamDecl(member, 0)
341 # Process VkStructureType
342 if type == 'VkStructureType':
343 # Extract the required struct type value from the comments
344 # embedded in the original text defining the 'typeinfo' element
345 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
346 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
347 if result:
348 value = result.group(0)
349 else:
350 value = self.genVkStructureType(typeName)
351 # Store the required type value
352 self.structTypes[typeName] = self.StructType(name=name, value=value)
353 # Store pointer/array/string info
354 membersInfo.append(self.CommandParam(type=type,
355 name=name,
356 ispointer=self.paramIsPointer(member),
357 isconst=True if 'const' in cdecl else False,
358 iscount=True if name in lens else False,
359 len=self.getLen(member),
360 extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None,
361 cdecl=cdecl,
362 islocal=False,
363 iscreate=False,
364 isdestroy=False))
365 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
366 #
367 # Insert a lock_guard line
368 def lock_guard(self, indent):
369 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
370 #
371 # Determine if a struct has an NDO as a member or an embedded member
372 def struct_contains_ndo(self, struct_item):
373 struct_member_dict = dict(self.structMembers)
374 struct_members = struct_member_dict[struct_item]
375
376 for member in struct_members:
377 if self.isHandleTypeNonDispatchable(member.type):
378 return True
379 elif member.type in struct_member_dict:
380 if self.struct_contains_ndo(member.type) == True:
381 return True
382 return False
383 #
384 # Return list of struct members which contain, or which sub-structures contain
385 # an NDO in a given list of parameters or members
386 def getParmeterStructsWithNdos(self, item_list):
387 struct_list = set()
388 for item in item_list:
389 paramtype = item.find('type')
390 typecategory = self.getTypeCategory(paramtype.text)
391 if typecategory == 'struct':
392 if self.struct_contains_ndo(paramtype.text) == True:
393 struct_list.add(item)
394 return struct_list
395 #
396 # Return list of non-dispatchable objects from a given list of parameters or members
397 def getNdosInParameterList(self, item_list, create_func):
398 ndo_list = set()
399 if create_func == True:
400 member_list = item_list[0:-1]
401 else:
402 member_list = item_list
403 for item in member_list:
404 if self.isHandleTypeNonDispatchable(paramtype.text):
405 ndo_list.add(item)
406 return ndo_list
407 #
408 # Generate source for creating a non-dispatchable object
409 def generate_create_ndo_code(self, indent, proto, params, cmd_info):
410 create_ndo_code = ''
Mark Young39389872017-01-19 21:10:49 -0700411 handle_type = params[-1].find('type')
412 if self.isHandleTypeNonDispatchable(handle_type.text):
413 # Check for special case where multiple handles are returned
414 ndo_array = False
415 if cmd_info[-1].len is not None:
416 ndo_array = True;
417 handle_name = params[-1].find('name')
418 create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
419 indent = self.incIndent(indent)
420 create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
421 ndo_dest = '*%s' % handle_name.text
422 if ndo_array == True:
423 create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600424 indent = self.incIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700425 ndo_dest = '%s[index0]' % cmd_info[-1].name
426 create_ndo_code += '%suint64_t unique_id = global_unique_id++;\n' % (indent)
427 create_ndo_code += '%sdev_data->unique_id_mapping[unique_id] = reinterpret_cast<uint64_t &>(%s);\n' % (indent, ndo_dest)
428 create_ndo_code += '%s%s = reinterpret_cast<%s&>(unique_id);\n' % (indent, ndo_dest, handle_type.text)
429 if ndo_array == True:
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600430 indent = self.decIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700431 create_ndo_code += '%s}\n' % indent
432 indent = self.decIndent(indent)
433 create_ndo_code += '%s}\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600434 return create_ndo_code
435 #
436 # Generate source for destroying a non-dispatchable object
437 def generate_destroy_ndo_code(self, indent, proto, cmd_info):
438 destroy_ndo_code = ''
439 ndo_array = False
440 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
441 # Check for special case where multiple handles are returned
442 if cmd_info[-1].len is not None:
443 ndo_array = True;
444 param = -1
445 else:
446 param = -2
447 if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True:
448 if ndo_array == True:
449 # This API is freeing an array of handles. Remove them from the unique_id map.
450 destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name)
451 indent = self.incIndent(indent)
452 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
453 destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len)
454 indent = self.incIndent(indent)
455 destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name)
456 destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent)
457 destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(unique_id);\n' % (indent)
458 indent = self.decIndent(indent);
459 destroy_ndo_code += '%s}\n' % indent
460 indent = self.decIndent(indent);
461 destroy_ndo_code += '%s}\n' % indent
462 else:
463 # Remove a single handle from the map
464 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
465 destroy_ndo_code += '%suint64_t %s_id = reinterpret_cast<uint64_t &>(%s);\n' % (indent, cmd_info[param].name, cmd_info[param].name)
466 destroy_ndo_code += '%s%s = (%s)dev_data->unique_id_mapping[%s_id];\n' % (indent, cmd_info[param].name, cmd_info[param].type, cmd_info[param].name)
467 destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name)
468 destroy_ndo_code += '%slock.unlock();\n' % (indent)
469 return ndo_array, destroy_ndo_code
470
471 #
472 # Clean up local declarations
473 def cleanUpLocalDeclarations(self, indent, prefix, name, len):
474 cleanup = '%sif (local_%s%s)\n' % (indent, prefix, name)
475 if len is not None:
476 cleanup += '%s delete[] local_%s%s;\n' % (indent, prefix, name)
477 else:
478 cleanup += '%s delete local_%s%s;\n' % (indent, prefix, name)
479 return cleanup
480 #
481 # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs
482 def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level):
483 decl_code = ''
484 pre_call_code = ''
485 post_call_code = ''
486 if ndo_count is not None:
487 if top_level == True:
488 decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name)
489 pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, ndo_name)
490 indent = self.incIndent(indent)
491 if top_level == True:
492 pre_call_code += '%s local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count)
493 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
494 indent = self.incIndent(indent)
495 pre_call_code += '%s local_%s%s[%s] = (%s)dev_data->unique_id_mapping[reinterpret_cast<const uint64_t &>(%s[%s])];\n' % (indent, prefix, ndo_name, index, ndo_type, ndo_name, index)
496 else:
497 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
498 indent = self.incIndent(indent)
499 pre_call_code += '%s %s%s[%s] = (%s)dev_data->unique_id_mapping[reinterpret_cast<const uint64_t &>(%s%s[%s])];\n' % (indent, prefix, ndo_name, index, ndo_type, prefix, ndo_name, index)
500 indent = self.decIndent(indent)
501 pre_call_code += '%s }\n' % indent
502 indent = self.decIndent(indent)
503 pre_call_code += '%s }\n' % indent
504 if top_level == True:
505 post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name)
506 indent = self.incIndent(indent)
507 post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name)
508 else:
509 if top_level == True:
510 if (destroy_func == False) or (destroy_array == True): #### LUGMAL This line needs to be skipped for destroy_ndo and not destroy_array
511 pre_call_code += '%s %s = (%s)dev_data->unique_id_mapping[reinterpret_cast<uint64_t &>(%s)];\n' % (indent, ndo_name, ndo_type, ndo_name)
512 else:
513 # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_'
514 # as part of the string and explicitly print it
515 fix = str(prefix).strip('local_');
516 pre_call_code += '%s if (%s%s) {\n' % (indent, fix, ndo_name)
517 indent = self.incIndent(indent)
518 pre_call_code += '%s %s%s = (%s)dev_data->unique_id_mapping[reinterpret_cast<const uint64_t &>(%s%s)];\n' % (indent, prefix, ndo_name, ndo_type, fix, ndo_name)
519 indent = self.decIndent(indent)
520 pre_call_code += '%s }\n' % indent
521 return decl_code, pre_call_code, post_call_code
522 #
523 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
524 # create_func means that this is API creates or allocates NDOs
525 # destroy_func indicates that this API destroys or frees NDOs
526 # destroy_array means that the destroy_func operated on an array of NDOs
527 def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param):
528 decls = ''
529 pre_code = ''
530 post_code = ''
531 struct_member_dict = dict(self.structMembers)
532 index = 'index%s' % str(array_index)
533 array_index += 1
534 # Process any NDOs in this structure and recurse for any sub-structs in this struct
535 for member in members:
536 # Handle NDOs
537 if self.isHandleTypeNonDispatchable(member.type) == True:
Jamie Madill24aa9742016-12-13 17:02:57 -0500538 count_name = member.len
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600539 if (count_name is not None):
540 if first_level_param == False:
541 count_name = '%s%s' % (prefix, member.len)
542
543 if (first_level_param == False) or (create_func == False):
544 (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param)
545 decls += tmp_decl
546 pre_code += tmp_pre
547 post_code += tmp_post
548 # Handle Structs that contain NDOs at some level
549 elif member.type in struct_member_dict:
550 # All structs at first level will have an NDO
551 if self.struct_contains_ndo(member.type) == True:
552 struct_info = struct_member_dict[member.type]
553 # Struct Array
554 if member.len is not None:
555 # Update struct prefix
556 if first_level_param == True:
557 new_prefix = 'local_%s' % member.name
558 # Declare safe_VarType for struct
559 decls += '%ssafe_%s *%s = NULL;\n' % (indent, member.type, new_prefix)
560 else:
561 new_prefix = '%s%s' % (prefix, member.name)
562 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
563 indent = self.incIndent(indent)
564 if first_level_param == True:
565 pre_code += '%s %s = new safe_%s[%s];\n' % (indent, new_prefix, member.type, member.len)
566 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
567 indent = self.incIndent(indent)
568 if first_level_param == True:
569 pre_code += '%s %s[%s].initialize(&%s[%s]);\n' % (indent, new_prefix, index, member.name, index)
570 local_prefix = '%s[%s].' % (new_prefix, index)
571 # Process sub-structs in this struct
572 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, False)
573 decls += tmp_decl
574 pre_code += tmp_pre
575 post_code += tmp_post
576 indent = self.decIndent(indent)
577 pre_code += '%s }\n' % indent
578 indent = self.decIndent(indent)
579 pre_code += '%s }\n' % indent
580 if first_level_param == True:
581 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len)
582 # Single Struct
583 else:
584 # Update struct prefix
585 if first_level_param == True:
586 new_prefix = 'local_%s->' % member.name
587 decls += '%ssafe_%s *local_%s%s = NULL;\n' % (indent, member.type, prefix, member.name)
588 else:
589 new_prefix = '%s%s->' % (prefix, member.name)
590 # Declare safe_VarType for struct
591 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
592 indent = self.incIndent(indent)
593 if first_level_param == True:
594 pre_code += '%s local_%s%s = new safe_%s(%s);\n' % (indent, prefix, member.name, member.type, member.name)
595 # Process sub-structs in this struct
596 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False)
597 decls += tmp_decl
598 pre_code += tmp_pre
599 post_code += tmp_post
600 indent = self.decIndent(indent)
601 pre_code += '%s }\n' % indent
602 if first_level_param == True:
603 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len)
604 return decls, pre_code, post_code
605 #
606 # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code
607 def generate_wrapping_code(self, cmd):
608 indent = ' '
609 proto = cmd.find('proto/name')
610 params = cmd.findall('param')
611 if proto.text is not None:
612 cmd_member_dict = dict(self.cmdMembers)
613 cmd_info = cmd_member_dict[proto.text]
614 # Handle ndo create/allocate operations
615 if cmd_info[0].iscreate:
616 create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info)
617 else:
618 create_ndo_code = ''
619 # Handle ndo destroy/free operations
620 if cmd_info[0].isdestroy:
621 (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info)
622 else:
623 destroy_array = False
624 destroy_ndo_code = ''
625 paramdecl = ''
626 param_pre_code = ''
627 param_post_code = ''
628 create_func = True if create_ndo_code else False
629 destroy_func = True if destroy_ndo_code else False
630 (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True)
631 param_post_code += create_ndo_code
632 if destroy_ndo_code:
633 if destroy_array == True:
634 param_post_code += destroy_ndo_code
635 else:
636 param_pre_code += destroy_ndo_code
637 if param_pre_code:
638 if (not destroy_func) or (destroy_array):
639 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
640 return paramdecl, param_pre_code, param_post_code
641 #
642 # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code
643 def genCmd(self, cmdinfo, cmdname):
644 if cmdname in self.interface_functions:
645 return
646 if cmdname in self.no_autogen_list:
647 decls = self.makeCDecls(cmdinfo.elem)
648 self.appendSection('command', '')
649 self.appendSection('command', '// Declare only')
650 self.appendSection('command', decls[0])
651 self.intercepts += [ ' {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (cmdname,cmdname[2:]) ]
652 return
653 # Add struct-member type information to command parameter information
654 OutputGenerator.genCmd(self, cmdinfo, cmdname)
655 members = cmdinfo.elem.findall('.//param')
656 # Iterate over members once to get length parameters for arrays
657 lens = set()
658 for member in members:
659 len = self.getLen(member)
660 if len:
661 lens.add(len)
662 struct_member_dict = dict(self.structMembers)
663 # Generate member info
664 membersInfo = []
665 for member in members:
666 # Get type and name of member
667 info = self.getTypeNameTuple(member)
668 type = info[0]
669 name = info[1]
670 cdecl = self.makeCParamDecl(member, 0)
671 # Check for parameter name in lens set
672 iscount = True if name in lens else False
673 len = self.getLen(member)
674 isconst = True if 'const' in cdecl else False
675 ispointer = self.paramIsPointer(member)
676 # Mark param as local if it is an array of NDOs
677 islocal = False;
678 if self.isHandleTypeNonDispatchable(type) == True:
679 if (len is not None) and (isconst == True):
680 islocal = True
681 # Or if it's a struct that contains an NDO
682 elif type in struct_member_dict:
683 if self.struct_contains_ndo(type) == True:
684 islocal = True
685
686 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
Mark Young39389872017-01-19 21:10:49 -0700687 iscreate = True if True in [create_txt in cmdname for create_txt in ['Create', 'Allocate', 'GetRandROutputDisplayEXT', 'RegisterDeviceEvent', 'RegisterDisplayEvent']] else False
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600688
689 membersInfo.append(self.CommandParam(type=type,
690 name=name,
691 ispointer=ispointer,
692 isconst=isconst,
693 iscount=iscount,
694 len=len,
695 extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None,
696 cdecl=cdecl,
697 islocal=islocal,
698 iscreate=iscreate,
699 isdestroy=isdestroy))
700 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
701 # Generate NDO wrapping/unwrapping code for all parameters
702 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
703 # If API doesn't contain an NDO's, don't fool with it
704 if not api_decls and not api_pre and not api_post:
705 return
706 # Record that the function will be intercepted
707 if (self.featureExtraProtect != None):
708 self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ]
709 self.intercepts += [ ' {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (cmdname,cmdname[2:]) ]
710 if (self.featureExtraProtect != None):
711 self.intercepts += [ '#endif' ]
712 decls = self.makeCDecls(cmdinfo.elem)
713 self.appendSection('command', '')
714 self.appendSection('command', decls[0][:-1])
715 self.appendSection('command', '{')
716 # Setup common to call wrappers, first parameter is always dispatchable
717 dispatchable_type = cmdinfo.elem.find('param/type').text
718 dispatchable_name = cmdinfo.elem.find('param/name').text
719 # Generate local instance/pdev/device data lookup
720 self.appendSection('command', ' layer_data *dev_data = get_my_data_ptr(get_dispatch_key('+dispatchable_name+'), layer_data_map);')
721 # Handle return values, if any
722 resulttype = cmdinfo.elem.find('proto/type')
723 if (resulttype != None and resulttype.text == 'void'):
724 resulttype = None
725 if (resulttype != None):
726 assignresult = resulttype.text + ' result = '
727 else:
728 assignresult = ''
729 # Pre-pend declarations and pre-api-call codegen
730 if api_decls:
731 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
732 if api_pre:
733 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
734 # Generate the API call itself
735 # Gather the parameter items
736 params = cmdinfo.elem.findall('param/name')
737 # Pull out the text for each of the parameters, separate them by commas in a list
738 paramstext = ', '.join([str(param.text) for param in params])
739 # If any of these paramters has been replaced by a local var, fix up the list
740 cmd_member_dict = dict(self.cmdMembers)
741 params = cmd_member_dict[cmdname]
742 for param in params:
743 if param.islocal == True:
744 if param.ispointer == True:
745 paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name))
746 else:
747 paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name))
748 # Use correct dispatch table
749 if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
750 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->instance_dispatch_table->',1)
751 else:
752 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->device_dispatch_table->',1)
753 # Put all this together for the final down-chain call
754 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
755 # And add the post-API-call codegen
756 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
757 # Handle the return result variable, if any
758 if (resulttype != None):
759 self.appendSection('command', ' return result;')
760 self.appendSection('command', '}')