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