blob: a6dae647d38803715507ac76a7ebfa3f229a41cb [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
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600124 self.intercepts = []
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700125 self.instance_extensions = []
126 self.device_extensions = []
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600127 # Commands which are not autogenerated but still intercepted
128 self.no_autogen_list = [
Jamie Madill24aa9742016-12-13 17:02:57 -0500129 'vkGetDeviceProcAddr',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600130 'vkGetInstanceProcAddr',
131 'vkCreateInstance',
132 'vkDestroyInstance',
133 'vkCreateDevice',
134 'vkDestroyDevice',
135 'vkAllocateMemory',
136 'vkCreateComputePipelines',
137 'vkCreateGraphicsPipelines',
138 'vkCreateSwapchainKHR',
139 'vkGetSwapchainImagesKHR',
140 'vkEnumerateInstanceLayerProperties',
141 'vkEnumerateDeviceLayerProperties',
142 'vkEnumerateInstanceExtensionProperties',
Mark Lobodzinski71703a52017-03-03 08:40:16 -0700143 'vkCreateDescriptorUpdateTemplateKHR',
144 'vkDestroyDescriptorUpdateTemplateKHR',
145 'vkUpdateDescriptorSetWithTemplateKHR',
146 'vkCmdPushDescriptorSetWithTemplateKHR',
Mark Lobodzinskia096c122017-03-16 11:54:35 -0600147 'vkDebugMarkerSetObjectTagEXT',
148 'vkDebugMarkerSetObjectNameEXT',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600149 ]
150 # Commands shadowed by interface functions and are not implemented
151 self.interface_functions = [
152 'vkGetPhysicalDeviceDisplayPropertiesKHR',
153 'vkGetPhysicalDeviceDisplayPlanePropertiesKHR',
154 'vkGetDisplayPlaneSupportedDisplaysKHR',
155 'vkGetDisplayModePropertiesKHR',
Norbert Nopper1dec9a52016-11-25 07:55:13 +0100156 'vkGetDisplayPlaneCapabilitiesKHR',
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600157 # DebugReport APIs are hooked, but handled separately in the source file
158 'vkCreateDebugReportCallbackEXT',
159 'vkDestroyDebugReportCallbackEXT',
160 'vkDebugReportMessageEXT',
161 ]
162 self.headerVersion = None
163 # Internal state - accumulators for different inner block text
164 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
165 self.structNames = [] # List of Vulkan struct typenames
166 self.structTypes = dict() # Map of Vulkan struct typename to required VkStructureType
167 self.handleTypes = set() # Set of handle type names
168 self.commands = [] # List of CommandData records for all Vulkan commands
169 self.structMembers = [] # List of StructMemberData records for all Vulkan structs
170 self.flags = set() # Map of flags typenames
171 # Named tuples to store struct and command data
172 self.StructType = namedtuple('StructType', ['name', 'value'])
173 self.CommandParam = namedtuple('CommandParam', ['type', 'name', 'ispointer', 'isconst', 'iscount', 'len', 'extstructs', 'cdecl', 'islocal', 'iscreate', 'isdestroy'])
174 self.CommandData = namedtuple('CommandData', ['name', 'return_type', 'params', 'cdecl'])
175 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
176 #
177 def incIndent(self, indent):
178 inc = ' ' * self.INDENT_SPACES
179 if indent:
180 return indent + inc
181 return inc
182 #
183 def decIndent(self, indent):
184 if indent and (len(indent) > self.INDENT_SPACES):
185 return indent[:-self.INDENT_SPACES]
186 return ''
187 #
188 # Override makeProtoName to drop the "vk" prefix
189 def makeProtoName(self, name, tail):
190 return self.genOpts.apientry + name[2:] + tail
191 #
192 # Check if the parameter passed in is a pointer to an array
193 def paramIsArray(self, param):
194 return param.attrib.get('len') is not None
195 #
196 def beginFile(self, genOpts):
197 OutputGenerator.beginFile(self, genOpts)
198 # User-supplied prefix text, if any (list of strings)
199 if (genOpts.prefixText):
200 for s in genOpts.prefixText:
201 write(s, file=self.outFile)
202 # Namespace
203 self.newline()
204 write('namespace unique_objects {', file = self.outFile)
205 #
206 def endFile(self):
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700207 # Write out device extension white list
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600208 self.newline()
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700209 write('// Layer Device Extension Whitelist', file=self.outFile)
210 write('static const char *kUniqueObjectsSupportedDeviceExtensions =', file=self.outFile)
211 for line in self.device_extensions:
212 write('%s' % line, file=self.outFile)
213 write(';\n', file=self.outFile)
214
215 # Write out instance extension white list
216 self.newline()
217 write('// Layer Instance Extension Whitelist', file=self.outFile)
218 write('static const char *kUniqueObjectsSupportedInstanceExtensions =', file=self.outFile)
219 for line in self.instance_extensions:
220 write('%s' % line, file=self.outFile)
221 write(';\n', file=self.outFile)
222 self.newline()
223
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600224 # Record intercepted procedures
225 write('// intercepts', file=self.outFile)
226 write('struct { const char* name; PFN_vkVoidFunction pFunc;} procmap[] = {', file=self.outFile)
227 write('\n'.join(self.intercepts), file=self.outFile)
228 write('};\n', file=self.outFile)
229 self.newline()
230 write('} // namespace unique_objects', file=self.outFile)
231 # Finish processing in superclass
232 OutputGenerator.endFile(self)
233 #
234 def beginFeature(self, interface, emit):
235 # Start processing in superclass
236 OutputGenerator.beginFeature(self, interface, emit)
237 self.headerVersion = None
238 self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
239 self.structNames = []
240 self.structTypes = dict()
241 self.handleTypes = set()
242 self.commands = []
243 self.structMembers = []
244 self.cmdMembers = []
245 self.flags = set()
246 self.StructMemberData = namedtuple('StructMemberData', ['name', 'members'])
247 self.CmdMemberData = namedtuple('CmdMemberData', ['name', 'members'])
Mark Lobodzinski8c375832017-02-09 15:58:14 -0700248 if self.featureName != 'VK_VERSION_1_0':
249 white_list_entry = []
250 if (self.featureExtraProtect != None):
251 white_list_entry += [ '#ifdef %s' % self.featureExtraProtect ]
252 white_list_entry += [ '"%s"' % self.featureName ]
253 if (self.featureExtraProtect != None):
254 white_list_entry += [ '#endif' ]
255 featureType = interface.get('type')
256 if featureType == 'instance':
257 self.instance_extensions += white_list_entry
258 elif featureType == 'device':
259 self.device_extensions += white_list_entry
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600260 #
261 def endFeature(self):
262 # Actually write the interface to the output file.
263 if (self.emit):
264 self.newline()
265 if (self.featureExtraProtect != None):
266 write('#ifdef', self.featureExtraProtect, file=self.outFile)
267 # Write the unique_objects code to the file
268 if (self.sections['command']):
269 if (self.genOpts.protectProto):
270 write(self.genOpts.protectProto,
271 self.genOpts.protectProtoStr, file=self.outFile)
Jamie Madill24aa9742016-12-13 17:02:57 -0500272 write('\n'.join(self.sections['command']), end=u'', file=self.outFile)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600273 if (self.featureExtraProtect != None):
274 write('\n#endif //', self.featureExtraProtect, file=self.outFile)
275 else:
276 self.newline()
277 # Finish processing in superclass
278 OutputGenerator.endFeature(self)
279 #
280 def genType(self, typeinfo, name):
281 OutputGenerator.genType(self, typeinfo, name)
282 typeElem = typeinfo.elem
283 # If the type is a struct type, traverse the imbedded <member> tags generating a structure.
284 # Otherwise, emit the tag text.
285 category = typeElem.get('category')
286 if (category == 'struct' or category == 'union'):
287 self.structNames.append(name)
288 self.genStruct(typeinfo, name)
289 #
290 # Append a definition to the specified section
291 def appendSection(self, section, text):
292 # self.sections[section].append('SECTION: ' + section + '\n')
293 self.sections[section].append(text)
294 #
295 # Check if the parameter passed in is a pointer
296 def paramIsPointer(self, param):
297 ispointer = False
298 for elem in param:
299 if ((elem.tag is not 'type') and (elem.tail is not None)) and '*' in elem.tail:
300 ispointer = True
301 return ispointer
302 #
303 # Get the category of a type
304 def getTypeCategory(self, typename):
305 types = self.registry.tree.findall("types/type")
306 for elem in types:
307 if (elem.find("name") is not None and elem.find('name').text == typename) or elem.attrib.get('name') == typename:
308 return elem.attrib.get('category')
309 #
310 # Check if a parent object is dispatchable or not
311 def isHandleTypeNonDispatchable(self, handletype):
312 handle = self.registry.tree.find("types/type/[name='" + handletype + "'][@category='handle']")
313 if handle is not None and handle.find('type').text == 'VK_DEFINE_NON_DISPATCHABLE_HANDLE':
314 return True
315 else:
316 return False
317 #
318 # Retrieve the type and name for a parameter
319 def getTypeNameTuple(self, param):
320 type = ''
321 name = ''
322 for elem in param:
323 if elem.tag == 'type':
324 type = noneStr(elem.text)
325 elif elem.tag == 'name':
326 name = noneStr(elem.text)
327 return (type, name)
328 #
329 # Retrieve the value of the len tag
330 def getLen(self, param):
331 result = None
332 len = param.attrib.get('len')
333 if len and len != 'null-terminated':
334 # For string arrays, 'len' can look like 'count,null-terminated', indicating that we
335 # have a null terminated array of strings. We strip the null-terminated from the
336 # 'len' field and only return the parameter specifying the string count
337 if 'null-terminated' in len:
338 result = len.split(',')[0]
339 else:
340 result = len
341 # Spec has now notation for len attributes, using :: instead of platform specific pointer symbol
342 result = str(result).replace('::', '->')
343 return result
344 #
345 # Generate a VkStructureType based on a structure typename
346 def genVkStructureType(self, typename):
347 # Add underscore between lowercase then uppercase
348 value = re.sub('([a-z0-9])([A-Z])', r'\1_\2', typename)
349 # Change to uppercase
350 value = value.upper()
351 # Add STRUCTURE_TYPE_
352 return re.sub('VK_', 'VK_STRUCTURE_TYPE_', value)
353 #
354 # Struct parameter check generation.
355 # This is a special case of the <type> tag where the contents are interpreted as a set of
356 # <member> tags instead of freeform C type declarations. The <member> tags are just like
357 # <param> tags - they are a declaration of a struct or union member. Only simple member
358 # declarations are supported (no nested structs etc.)
359 def genStruct(self, typeinfo, typeName):
360 OutputGenerator.genStruct(self, typeinfo, typeName)
361 members = typeinfo.elem.findall('.//member')
362 # Iterate over members once to get length parameters for arrays
363 lens = set()
364 for member in members:
365 len = self.getLen(member)
366 if len:
367 lens.add(len)
368 # Generate member info
369 membersInfo = []
370 for member in members:
371 # Get the member's type and name
372 info = self.getTypeNameTuple(member)
373 type = info[0]
374 name = info[1]
375 cdecl = self.makeCParamDecl(member, 0)
376 # Process VkStructureType
377 if type == 'VkStructureType':
378 # Extract the required struct type value from the comments
379 # embedded in the original text defining the 'typeinfo' element
380 rawXml = etree.tostring(typeinfo.elem).decode('ascii')
381 result = re.search(r'VK_STRUCTURE_TYPE_\w+', rawXml)
382 if result:
383 value = result.group(0)
384 else:
385 value = self.genVkStructureType(typeName)
386 # Store the required type value
387 self.structTypes[typeName] = self.StructType(name=name, value=value)
388 # Store pointer/array/string info
389 membersInfo.append(self.CommandParam(type=type,
390 name=name,
391 ispointer=self.paramIsPointer(member),
392 isconst=True if 'const' in cdecl else False,
393 iscount=True if name in lens else False,
394 len=self.getLen(member),
395 extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None,
396 cdecl=cdecl,
397 islocal=False,
398 iscreate=False,
399 isdestroy=False))
400 self.structMembers.append(self.StructMemberData(name=typeName, members=membersInfo))
401 #
402 # Insert a lock_guard line
403 def lock_guard(self, indent):
404 return '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % indent
405 #
406 # Determine if a struct has an NDO as a member or an embedded member
407 def struct_contains_ndo(self, struct_item):
408 struct_member_dict = dict(self.structMembers)
409 struct_members = struct_member_dict[struct_item]
410
411 for member in struct_members:
412 if self.isHandleTypeNonDispatchable(member.type):
413 return True
414 elif member.type in struct_member_dict:
415 if self.struct_contains_ndo(member.type) == True:
416 return True
417 return False
418 #
419 # Return list of struct members which contain, or which sub-structures contain
420 # an NDO in a given list of parameters or members
421 def getParmeterStructsWithNdos(self, item_list):
422 struct_list = set()
423 for item in item_list:
424 paramtype = item.find('type')
425 typecategory = self.getTypeCategory(paramtype.text)
426 if typecategory == 'struct':
427 if self.struct_contains_ndo(paramtype.text) == True:
428 struct_list.add(item)
429 return struct_list
430 #
431 # Return list of non-dispatchable objects from a given list of parameters or members
432 def getNdosInParameterList(self, item_list, create_func):
433 ndo_list = set()
434 if create_func == True:
435 member_list = item_list[0:-1]
436 else:
437 member_list = item_list
438 for item in member_list:
439 if self.isHandleTypeNonDispatchable(paramtype.text):
440 ndo_list.add(item)
441 return ndo_list
442 #
443 # Generate source for creating a non-dispatchable object
444 def generate_create_ndo_code(self, indent, proto, params, cmd_info):
445 create_ndo_code = ''
Mark Young39389872017-01-19 21:10:49 -0700446 handle_type = params[-1].find('type')
447 if self.isHandleTypeNonDispatchable(handle_type.text):
448 # Check for special case where multiple handles are returned
449 ndo_array = False
450 if cmd_info[-1].len is not None:
451 ndo_array = True;
452 handle_name = params[-1].find('name')
453 create_ndo_code += '%sif (VK_SUCCESS == result) {\n' % (indent)
454 indent = self.incIndent(indent)
455 create_ndo_code += '%sstd::lock_guard<std::mutex> lock(global_lock);\n' % (indent)
456 ndo_dest = '*%s' % handle_name.text
457 if ndo_array == True:
458 create_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[-1].len)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600459 indent = self.incIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700460 ndo_dest = '%s[index0]' % cmd_info[-1].name
461 create_ndo_code += '%suint64_t unique_id = global_unique_id++;\n' % (indent)
462 create_ndo_code += '%sdev_data->unique_id_mapping[unique_id] = reinterpret_cast<uint64_t &>(%s);\n' % (indent, ndo_dest)
463 create_ndo_code += '%s%s = reinterpret_cast<%s&>(unique_id);\n' % (indent, ndo_dest, handle_type.text)
464 if ndo_array == True:
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600465 indent = self.decIndent(indent)
Mark Young39389872017-01-19 21:10:49 -0700466 create_ndo_code += '%s}\n' % indent
467 indent = self.decIndent(indent)
468 create_ndo_code += '%s}\n' % (indent)
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600469 return create_ndo_code
470 #
471 # Generate source for destroying a non-dispatchable object
472 def generate_destroy_ndo_code(self, indent, proto, cmd_info):
473 destroy_ndo_code = ''
474 ndo_array = False
475 if True in [destroy_txt in proto.text for destroy_txt in ['Destroy', 'Free']]:
476 # Check for special case where multiple handles are returned
477 if cmd_info[-1].len is not None:
478 ndo_array = True;
479 param = -1
480 else:
481 param = -2
482 if self.isHandleTypeNonDispatchable(cmd_info[param].type) == True:
483 if ndo_array == True:
484 # This API is freeing an array of handles. Remove them from the unique_id map.
485 destroy_ndo_code += '%sif ((VK_SUCCESS == result) && (%s)) {\n' % (indent, cmd_info[param].name)
486 indent = self.incIndent(indent)
487 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
488 destroy_ndo_code += '%sfor (uint32_t index0 = 0; index0 < %s; index0++) {\n' % (indent, cmd_info[param].len)
489 indent = self.incIndent(indent)
490 destroy_ndo_code += '%s%s handle = %s[index0];\n' % (indent, cmd_info[param].type, cmd_info[param].name)
491 destroy_ndo_code += '%suint64_t unique_id = reinterpret_cast<uint64_t &>(handle);\n' % (indent)
492 destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(unique_id);\n' % (indent)
493 indent = self.decIndent(indent);
494 destroy_ndo_code += '%s}\n' % indent
495 indent = self.decIndent(indent);
496 destroy_ndo_code += '%s}\n' % indent
497 else:
498 # Remove a single handle from the map
499 destroy_ndo_code += '%sstd::unique_lock<std::mutex> lock(global_lock);\n' % (indent)
500 destroy_ndo_code += '%suint64_t %s_id = reinterpret_cast<uint64_t &>(%s);\n' % (indent, cmd_info[param].name, cmd_info[param].name)
501 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)
502 destroy_ndo_code += '%sdev_data->unique_id_mapping.erase(%s_id);\n' % (indent, cmd_info[param].name)
503 destroy_ndo_code += '%slock.unlock();\n' % (indent)
504 return ndo_array, destroy_ndo_code
505
506 #
507 # Clean up local declarations
508 def cleanUpLocalDeclarations(self, indent, prefix, name, len):
509 cleanup = '%sif (local_%s%s)\n' % (indent, prefix, name)
510 if len is not None:
511 cleanup += '%s delete[] local_%s%s;\n' % (indent, prefix, name)
512 else:
513 cleanup += '%s delete local_%s%s;\n' % (indent, prefix, name)
514 return cleanup
515 #
516 # Output UO code for a single NDO (ndo_count is NULL) or a counted list of NDOs
517 def outputNDOs(self, ndo_type, ndo_name, ndo_count, prefix, index, indent, destroy_func, destroy_array, top_level):
518 decl_code = ''
519 pre_call_code = ''
520 post_call_code = ''
521 if ndo_count is not None:
522 if top_level == True:
523 decl_code += '%s%s *local_%s%s = NULL;\n' % (indent, ndo_type, prefix, ndo_name)
524 pre_call_code += '%s if (%s%s) {\n' % (indent, prefix, ndo_name)
525 indent = self.incIndent(indent)
526 if top_level == True:
527 pre_call_code += '%s local_%s%s = new %s[%s];\n' % (indent, prefix, ndo_name, ndo_type, ndo_count)
528 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
529 indent = self.incIndent(indent)
530 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)
531 else:
532 pre_call_code += '%s for (uint32_t %s = 0; %s < %s; ++%s) {\n' % (indent, index, index, ndo_count, index)
533 indent = self.incIndent(indent)
534 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)
535 indent = self.decIndent(indent)
536 pre_call_code += '%s }\n' % indent
537 indent = self.decIndent(indent)
538 pre_call_code += '%s }\n' % indent
539 if top_level == True:
540 post_call_code += '%sif (local_%s%s)\n' % (indent, prefix, ndo_name)
541 indent = self.incIndent(indent)
542 post_call_code += '%sdelete[] local_%s;\n' % (indent, ndo_name)
543 else:
544 if top_level == True:
545 if (destroy_func == False) or (destroy_array == True): #### LUGMAL This line needs to be skipped for destroy_ndo and not destroy_array
546 pre_call_code += '%s %s = (%s)dev_data->unique_id_mapping[reinterpret_cast<uint64_t &>(%s)];\n' % (indent, ndo_name, ndo_type, ndo_name)
547 else:
548 # Make temp copy of this var with the 'local' removed. It may be better to not pass in 'local_'
549 # as part of the string and explicitly print it
550 fix = str(prefix).strip('local_');
551 pre_call_code += '%s if (%s%s) {\n' % (indent, fix, ndo_name)
552 indent = self.incIndent(indent)
553 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)
554 indent = self.decIndent(indent)
555 pre_call_code += '%s }\n' % indent
556 return decl_code, pre_call_code, post_call_code
557 #
558 # first_level_param indicates if elements are passed directly into the function else they're below a ptr/struct
559 # create_func means that this is API creates or allocates NDOs
560 # destroy_func indicates that this API destroys or frees NDOs
561 # destroy_array means that the destroy_func operated on an array of NDOs
562 def uniquify_members(self, members, indent, prefix, array_index, create_func, destroy_func, destroy_array, first_level_param):
563 decls = ''
564 pre_code = ''
565 post_code = ''
566 struct_member_dict = dict(self.structMembers)
567 index = 'index%s' % str(array_index)
568 array_index += 1
569 # Process any NDOs in this structure and recurse for any sub-structs in this struct
570 for member in members:
571 # Handle NDOs
572 if self.isHandleTypeNonDispatchable(member.type) == True:
Jamie Madill24aa9742016-12-13 17:02:57 -0500573 count_name = member.len
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600574 if (count_name is not None):
575 if first_level_param == False:
576 count_name = '%s%s' % (prefix, member.len)
577
578 if (first_level_param == False) or (create_func == False):
579 (tmp_decl, tmp_pre, tmp_post) = self.outputNDOs(member.type, member.name, count_name, prefix, index, indent, destroy_func, destroy_array, first_level_param)
580 decls += tmp_decl
581 pre_code += tmp_pre
582 post_code += tmp_post
583 # Handle Structs that contain NDOs at some level
584 elif member.type in struct_member_dict:
585 # All structs at first level will have an NDO
586 if self.struct_contains_ndo(member.type) == True:
587 struct_info = struct_member_dict[member.type]
588 # Struct Array
589 if member.len is not None:
590 # Update struct prefix
591 if first_level_param == True:
592 new_prefix = 'local_%s' % member.name
593 # Declare safe_VarType for struct
594 decls += '%ssafe_%s *%s = NULL;\n' % (indent, member.type, new_prefix)
595 else:
596 new_prefix = '%s%s' % (prefix, member.name)
597 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
598 indent = self.incIndent(indent)
599 if first_level_param == True:
600 pre_code += '%s %s = new safe_%s[%s];\n' % (indent, new_prefix, member.type, member.len)
601 pre_code += '%s for (uint32_t %s = 0; %s < %s%s; ++%s) {\n' % (indent, index, index, prefix, member.len, index)
602 indent = self.incIndent(indent)
603 if first_level_param == True:
604 pre_code += '%s %s[%s].initialize(&%s[%s]);\n' % (indent, new_prefix, index, member.name, index)
605 local_prefix = '%s[%s].' % (new_prefix, index)
606 # Process sub-structs in this struct
607 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, local_prefix, array_index, create_func, destroy_func, destroy_array, False)
608 decls += tmp_decl
609 pre_code += tmp_pre
610 post_code += tmp_post
611 indent = self.decIndent(indent)
612 pre_code += '%s }\n' % indent
613 indent = self.decIndent(indent)
614 pre_code += '%s }\n' % indent
615 if first_level_param == True:
616 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len)
617 # Single Struct
618 else:
619 # Update struct prefix
620 if first_level_param == True:
621 new_prefix = 'local_%s->' % member.name
622 decls += '%ssafe_%s *local_%s%s = NULL;\n' % (indent, member.type, prefix, member.name)
623 else:
624 new_prefix = '%s%s->' % (prefix, member.name)
625 # Declare safe_VarType for struct
626 pre_code += '%s if (%s%s) {\n' % (indent, prefix, member.name)
627 indent = self.incIndent(indent)
628 if first_level_param == True:
629 pre_code += '%s local_%s%s = new safe_%s(%s);\n' % (indent, prefix, member.name, member.type, member.name)
630 # Process sub-structs in this struct
631 (tmp_decl, tmp_pre, tmp_post) = self.uniquify_members(struct_info, indent, new_prefix, array_index, create_func, destroy_func, destroy_array, False)
632 decls += tmp_decl
633 pre_code += tmp_pre
634 post_code += tmp_post
635 indent = self.decIndent(indent)
636 pre_code += '%s }\n' % indent
637 if first_level_param == True:
638 post_code += self.cleanUpLocalDeclarations(indent, prefix, member.name, member.len)
639 return decls, pre_code, post_code
640 #
641 # For a particular API, generate the non-dispatchable-object wrapping/unwrapping code
642 def generate_wrapping_code(self, cmd):
643 indent = ' '
644 proto = cmd.find('proto/name')
645 params = cmd.findall('param')
646 if proto.text is not None:
647 cmd_member_dict = dict(self.cmdMembers)
648 cmd_info = cmd_member_dict[proto.text]
649 # Handle ndo create/allocate operations
650 if cmd_info[0].iscreate:
651 create_ndo_code = self.generate_create_ndo_code(indent, proto, params, cmd_info)
652 else:
653 create_ndo_code = ''
654 # Handle ndo destroy/free operations
655 if cmd_info[0].isdestroy:
656 (destroy_array, destroy_ndo_code) = self.generate_destroy_ndo_code(indent, proto, cmd_info)
657 else:
658 destroy_array = False
659 destroy_ndo_code = ''
660 paramdecl = ''
661 param_pre_code = ''
662 param_post_code = ''
663 create_func = True if create_ndo_code else False
664 destroy_func = True if destroy_ndo_code else False
665 (paramdecl, param_pre_code, param_post_code) = self.uniquify_members(cmd_info, indent, '', 0, create_func, destroy_func, destroy_array, True)
666 param_post_code += create_ndo_code
667 if destroy_ndo_code:
668 if destroy_array == True:
669 param_post_code += destroy_ndo_code
670 else:
671 param_pre_code += destroy_ndo_code
672 if param_pre_code:
673 if (not destroy_func) or (destroy_array):
674 param_pre_code = '%s{\n%s%s%s%s}\n' % (' ', indent, self.lock_guard(indent), param_pre_code, indent)
675 return paramdecl, param_pre_code, param_post_code
676 #
677 # Capture command parameter info needed to wrap NDOs as well as handling some boilerplate code
678 def genCmd(self, cmdinfo, cmdname):
679 if cmdname in self.interface_functions:
680 return
681 if cmdname in self.no_autogen_list:
682 decls = self.makeCDecls(cmdinfo.elem)
683 self.appendSection('command', '')
684 self.appendSection('command', '// Declare only')
685 self.appendSection('command', decls[0])
686 self.intercepts += [ ' {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (cmdname,cmdname[2:]) ]
687 return
688 # Add struct-member type information to command parameter information
689 OutputGenerator.genCmd(self, cmdinfo, cmdname)
690 members = cmdinfo.elem.findall('.//param')
691 # Iterate over members once to get length parameters for arrays
692 lens = set()
693 for member in members:
694 len = self.getLen(member)
695 if len:
696 lens.add(len)
697 struct_member_dict = dict(self.structMembers)
698 # Generate member info
699 membersInfo = []
700 for member in members:
701 # Get type and name of member
702 info = self.getTypeNameTuple(member)
703 type = info[0]
704 name = info[1]
705 cdecl = self.makeCParamDecl(member, 0)
706 # Check for parameter name in lens set
707 iscount = True if name in lens else False
708 len = self.getLen(member)
709 isconst = True if 'const' in cdecl else False
710 ispointer = self.paramIsPointer(member)
711 # Mark param as local if it is an array of NDOs
712 islocal = False;
713 if self.isHandleTypeNonDispatchable(type) == True:
714 if (len is not None) and (isconst == True):
715 islocal = True
716 # Or if it's a struct that contains an NDO
717 elif type in struct_member_dict:
718 if self.struct_contains_ndo(type) == True:
719 islocal = True
720
721 isdestroy = True if True in [destroy_txt in cmdname for destroy_txt in ['Destroy', 'Free']] else False
Mark Young39389872017-01-19 21:10:49 -0700722 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 -0600723
724 membersInfo.append(self.CommandParam(type=type,
725 name=name,
726 ispointer=ispointer,
727 isconst=isconst,
728 iscount=iscount,
729 len=len,
730 extstructs=member.attrib.get('validextensionstructs') if name == 'pNext' else None,
731 cdecl=cdecl,
732 islocal=islocal,
733 iscreate=iscreate,
734 isdestroy=isdestroy))
735 self.cmdMembers.append(self.CmdMemberData(name=cmdname, members=membersInfo))
736 # Generate NDO wrapping/unwrapping code for all parameters
737 (api_decls, api_pre, api_post) = self.generate_wrapping_code(cmdinfo.elem)
738 # If API doesn't contain an NDO's, don't fool with it
739 if not api_decls and not api_pre and not api_post:
740 return
741 # Record that the function will be intercepted
742 if (self.featureExtraProtect != None):
743 self.intercepts += [ '#ifdef %s' % self.featureExtraProtect ]
744 self.intercepts += [ ' {"%s", reinterpret_cast<PFN_vkVoidFunction>(%s)},' % (cmdname,cmdname[2:]) ]
745 if (self.featureExtraProtect != None):
746 self.intercepts += [ '#endif' ]
747 decls = self.makeCDecls(cmdinfo.elem)
748 self.appendSection('command', '')
749 self.appendSection('command', decls[0][:-1])
750 self.appendSection('command', '{')
751 # Setup common to call wrappers, first parameter is always dispatchable
752 dispatchable_type = cmdinfo.elem.find('param/type').text
753 dispatchable_name = cmdinfo.elem.find('param/name').text
754 # Generate local instance/pdev/device data lookup
Tobin Ehlis8d6acde2017-02-08 07:40:40 -0700755 self.appendSection('command', ' layer_data *dev_data = GetLayerDataPtr(get_dispatch_key('+dispatchable_name+'), layer_data_map);')
Mark Lobodzinskia509c292016-10-11 14:33:07 -0600756 # Handle return values, if any
757 resulttype = cmdinfo.elem.find('proto/type')
758 if (resulttype != None and resulttype.text == 'void'):
759 resulttype = None
760 if (resulttype != None):
761 assignresult = resulttype.text + ' result = '
762 else:
763 assignresult = ''
764 # Pre-pend declarations and pre-api-call codegen
765 if api_decls:
766 self.appendSection('command', "\n".join(str(api_decls).rstrip().split("\n")))
767 if api_pre:
768 self.appendSection('command', "\n".join(str(api_pre).rstrip().split("\n")))
769 # Generate the API call itself
770 # Gather the parameter items
771 params = cmdinfo.elem.findall('param/name')
772 # Pull out the text for each of the parameters, separate them by commas in a list
773 paramstext = ', '.join([str(param.text) for param in params])
774 # If any of these paramters has been replaced by a local var, fix up the list
775 cmd_member_dict = dict(self.cmdMembers)
776 params = cmd_member_dict[cmdname]
777 for param in params:
778 if param.islocal == True:
779 if param.ispointer == True:
780 paramstext = paramstext.replace(param.name, '(%s %s*)local_%s' % ('const', param.type, param.name))
781 else:
782 paramstext = paramstext.replace(param.name, '(%s %s)local_%s' % ('const', param.type, param.name))
783 # Use correct dispatch table
784 if dispatchable_type in ["VkPhysicalDevice", "VkInstance"]:
785 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->instance_dispatch_table->',1)
786 else:
787 API = cmdinfo.elem.attrib.get('name').replace('vk','dev_data->device_dispatch_table->',1)
788 # Put all this together for the final down-chain call
789 self.appendSection('command', ' ' + assignresult + API + '(' + paramstext + ');')
790 # And add the post-API-call codegen
791 self.appendSection('command', "\n".join(str(api_post).rstrip().split("\n")))
792 # Handle the return result variable, if any
793 if (resulttype != None):
794 self.appendSection('command', ' return result;')
795 self.appendSection('command', '}')