blob: 5632884a1ad898cc1401f07cd323e371e0f7ddfc [file] [log] [blame]
Tony-LunarGf0634eb2021-01-05 15:11:12 -07001/* Copyright (c) 2020-2021 The Khronos Group Inc.
2 * Copyright (c) 2020-2021 Valve Corporation
3 * Copyright (c) 2020-2021 LunarG, Inc.
Tony-LunarG1dce2392019-10-23 16:49:29 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: Tony Barbour <tony@lunarg.com>
18 */
19
20#include "chassis.h"
21#include "layer_chassis_dispatch.h"
22#include "state_tracker.h"
23#include "shader_validation.h"
24#include "spirv-tools/libspirv.h"
25#include "spirv-tools/optimizer.hpp"
26#include "spirv-tools/instrument.hpp"
Mark Lobodzinski102687e2020-04-28 11:03:28 -060027#include <spirv/unified1/spirv.hpp>
Tony-LunarG1dce2392019-10-23 16:49:29 -060028#include <algorithm>
29#include <regex>
30
31#define VMA_IMPLEMENTATION
32// This define indicates that we will supply Vulkan function pointers at initialization
33#define VMA_STATIC_VULKAN_FUNCTIONS 0
34#include "vk_mem_alloc.h"
35
Tony-LunarGb5fae462020-03-05 12:43:25 -070036class UtilDescriptorSetManager {
Tony-LunarG1dce2392019-10-23 16:49:29 -060037 public:
Tony-LunarGb5fae462020-03-05 12:43:25 -070038 UtilDescriptorSetManager(VkDevice device, uint32_t numBindingsInSet);
39 ~UtilDescriptorSetManager();
Tony-LunarG1dce2392019-10-23 16:49:29 -060040
41 VkResult GetDescriptorSet(VkDescriptorPool *desc_pool, VkDescriptorSetLayout ds_layout, VkDescriptorSet *desc_sets);
42 VkResult GetDescriptorSets(uint32_t count, VkDescriptorPool *pool, VkDescriptorSetLayout ds_layout,
43 std::vector<VkDescriptorSet> *desc_sets);
44 void PutBackDescriptorSet(VkDescriptorPool desc_pool, VkDescriptorSet desc_set);
45
46 private:
47 static const uint32_t kItemsPerChunk = 512;
48 struct PoolTracker {
49 uint32_t size;
50 uint32_t used;
51 };
52 VkDevice device;
53 uint32_t numBindingsInSet;
54 std::unordered_map<VkDescriptorPool, struct PoolTracker> desc_pool_map_;
55};
56
57// Implementation for Descriptor Set Manager class
Tony-LunarGb5fae462020-03-05 12:43:25 -070058UtilDescriptorSetManager::UtilDescriptorSetManager(VkDevice device, uint32_t numBindingsInSet)
Tony-LunarG1dce2392019-10-23 16:49:29 -060059 : device(device), numBindingsInSet(numBindingsInSet) {}
60
Tony-LunarGb5fae462020-03-05 12:43:25 -070061UtilDescriptorSetManager::~UtilDescriptorSetManager() {
Tony-LunarG1dce2392019-10-23 16:49:29 -060062 for (auto &pool : desc_pool_map_) {
63 DispatchDestroyDescriptorPool(device, pool.first, NULL);
64 }
65 desc_pool_map_.clear();
66}
67
Tony-LunarGb5fae462020-03-05 12:43:25 -070068VkResult UtilDescriptorSetManager::GetDescriptorSet(VkDescriptorPool *desc_pool, VkDescriptorSetLayout ds_layout,
69 VkDescriptorSet *desc_set) {
Tony-LunarG1dce2392019-10-23 16:49:29 -060070 std::vector<VkDescriptorSet> desc_sets;
71 VkResult result = GetDescriptorSets(1, desc_pool, ds_layout, &desc_sets);
72 if (result == VK_SUCCESS) {
73 *desc_set = desc_sets[0];
74 }
75 return result;
76}
77
Tony-LunarGb5fae462020-03-05 12:43:25 -070078VkResult UtilDescriptorSetManager::GetDescriptorSets(uint32_t count, VkDescriptorPool *pool, VkDescriptorSetLayout ds_layout,
79 std::vector<VkDescriptorSet> *desc_sets) {
Tony-LunarG1dce2392019-10-23 16:49:29 -060080 const uint32_t default_pool_size = kItemsPerChunk;
81 VkResult result = VK_SUCCESS;
82 VkDescriptorPool pool_to_use = VK_NULL_HANDLE;
83
84 if (0 == count) {
85 return result;
86 }
87 desc_sets->clear();
88 desc_sets->resize(count);
89
90 for (auto &pool : desc_pool_map_) {
91 if (pool.second.used + count < pool.second.size) {
92 pool_to_use = pool.first;
93 break;
94 }
95 }
96 if (VK_NULL_HANDLE == pool_to_use) {
97 uint32_t pool_count = default_pool_size;
98 if (count > default_pool_size) {
99 pool_count = count;
100 }
101 const VkDescriptorPoolSize size_counts = {
102 VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
103 pool_count * numBindingsInSet,
104 };
105 VkDescriptorPoolCreateInfo desc_pool_info = {};
106 desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
107 desc_pool_info.pNext = NULL;
108 desc_pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
109 desc_pool_info.maxSets = pool_count;
110 desc_pool_info.poolSizeCount = 1;
111 desc_pool_info.pPoolSizes = &size_counts;
112 result = DispatchCreateDescriptorPool(device, &desc_pool_info, NULL, &pool_to_use);
113 assert(result == VK_SUCCESS);
114 if (result != VK_SUCCESS) {
115 return result;
116 }
117 desc_pool_map_[pool_to_use].size = desc_pool_info.maxSets;
118 desc_pool_map_[pool_to_use].used = 0;
119 }
120 std::vector<VkDescriptorSetLayout> desc_layouts(count, ds_layout);
121
122 VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, pool_to_use, count,
123 desc_layouts.data()};
124
125 result = DispatchAllocateDescriptorSets(device, &alloc_info, desc_sets->data());
126 assert(result == VK_SUCCESS);
127 if (result != VK_SUCCESS) {
128 return result;
129 }
130 *pool = pool_to_use;
131 desc_pool_map_[pool_to_use].used += count;
132 return result;
133}
134
Tony-LunarGb5fae462020-03-05 12:43:25 -0700135void UtilDescriptorSetManager::PutBackDescriptorSet(VkDescriptorPool desc_pool, VkDescriptorSet desc_set) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600136 auto iter = desc_pool_map_.find(desc_pool);
137 if (iter != desc_pool_map_.end()) {
138 VkResult result = DispatchFreeDescriptorSets(device, desc_pool, 1, &desc_set);
139 assert(result == VK_SUCCESS);
140 if (result != VK_SUCCESS) {
141 return;
142 }
143 desc_pool_map_[desc_pool].used--;
144 if (0 == desc_pool_map_[desc_pool].used) {
145 DispatchDestroyDescriptorPool(device, desc_pool, NULL);
146 desc_pool_map_.erase(desc_pool);
147 }
148 }
149 return;
150}
151
152// Trampolines to make VMA call Dispatch for Vulkan calls
153static VKAPI_ATTR void VKAPI_CALL gpuVkGetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,
154 VkPhysicalDeviceProperties *pProperties) {
155 DispatchGetPhysicalDeviceProperties(physicalDevice, pProperties);
156}
157static VKAPI_ATTR void VKAPI_CALL gpuVkGetPhysicalDeviceMemoryProperties(VkPhysicalDevice physicalDevice,
158 VkPhysicalDeviceMemoryProperties *pMemoryProperties) {
159 DispatchGetPhysicalDeviceMemoryProperties(physicalDevice, pMemoryProperties);
160}
161static VKAPI_ATTR VkResult VKAPI_CALL gpuVkAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo,
162 const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory) {
163 return DispatchAllocateMemory(device, pAllocateInfo, pAllocator, pMemory);
164}
165static VKAPI_ATTR void VKAPI_CALL gpuVkFreeMemory(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks *pAllocator) {
166 DispatchFreeMemory(device, memory, pAllocator);
167}
168static VKAPI_ATTR VkResult VKAPI_CALL gpuVkMapMemory(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size,
169 VkMemoryMapFlags flags, void **ppData) {
170 return DispatchMapMemory(device, memory, offset, size, flags, ppData);
171}
172static VKAPI_ATTR void VKAPI_CALL gpuVkUnmapMemory(VkDevice device, VkDeviceMemory memory) { DispatchUnmapMemory(device, memory); }
173static VKAPI_ATTR VkResult VKAPI_CALL gpuVkFlushMappedMemoryRanges(VkDevice device, uint32_t memoryRangeCount,
174 const VkMappedMemoryRange *pMemoryRanges) {
175 return DispatchFlushMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges);
176}
177static VKAPI_ATTR VkResult VKAPI_CALL gpuVkInvalidateMappedMemoryRanges(VkDevice device, uint32_t memoryRangeCount,
178 const VkMappedMemoryRange *pMemoryRanges) {
179 return DispatchInvalidateMappedMemoryRanges(device, memoryRangeCount, pMemoryRanges);
180}
181static VKAPI_ATTR VkResult VKAPI_CALL gpuVkBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory memory,
182 VkDeviceSize memoryOffset) {
183 return DispatchBindBufferMemory(device, buffer, memory, memoryOffset);
184}
185static VKAPI_ATTR VkResult VKAPI_CALL gpuVkBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory memory,
186 VkDeviceSize memoryOffset) {
187 return DispatchBindImageMemory(device, image, memory, memoryOffset);
188}
189static VKAPI_ATTR void VKAPI_CALL gpuVkGetBufferMemoryRequirements(VkDevice device, VkBuffer buffer,
190 VkMemoryRequirements *pMemoryRequirements) {
191 DispatchGetBufferMemoryRequirements(device, buffer, pMemoryRequirements);
192}
193static VKAPI_ATTR void VKAPI_CALL gpuVkGetImageMemoryRequirements(VkDevice device, VkImage image,
194 VkMemoryRequirements *pMemoryRequirements) {
195 DispatchGetImageMemoryRequirements(device, image, pMemoryRequirements);
196}
197static VKAPI_ATTR VkResult VKAPI_CALL gpuVkCreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
198 const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer) {
199 return DispatchCreateBuffer(device, pCreateInfo, pAllocator, pBuffer);
200}
201static VKAPI_ATTR void VKAPI_CALL gpuVkDestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator) {
202 return DispatchDestroyBuffer(device, buffer, pAllocator);
203}
204static VKAPI_ATTR VkResult VKAPI_CALL gpuVkCreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
205 const VkAllocationCallbacks *pAllocator, VkImage *pImage) {
206 return DispatchCreateImage(device, pCreateInfo, pAllocator, pImage);
207}
208static VKAPI_ATTR void VKAPI_CALL gpuVkDestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator) {
209 DispatchDestroyImage(device, image, pAllocator);
210}
211static VKAPI_ATTR void VKAPI_CALL gpuVkCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
212 uint32_t regionCount, const VkBufferCopy *pRegions) {
213 DispatchCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, regionCount, pRegions);
214}
215
Tony-LunarGb5fae462020-03-05 12:43:25 -0700216VkResult UtilInitializeVma(VkPhysicalDevice physical_device, VkDevice device, VmaAllocator *pAllocator) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600217 VmaVulkanFunctions functions;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700218 VmaAllocatorCreateInfo allocator_info = {};
219 allocator_info.device = device;
220 allocator_info.physicalDevice = physical_device;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600221
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700222 functions.vkGetPhysicalDeviceProperties = static_cast<PFN_vkGetPhysicalDeviceProperties>(gpuVkGetPhysicalDeviceProperties);
223 functions.vkGetPhysicalDeviceMemoryProperties =
224 static_cast<PFN_vkGetPhysicalDeviceMemoryProperties>(gpuVkGetPhysicalDeviceMemoryProperties);
225 functions.vkAllocateMemory = static_cast<PFN_vkAllocateMemory>(gpuVkAllocateMemory);
226 functions.vkFreeMemory = static_cast<PFN_vkFreeMemory>(gpuVkFreeMemory);
227 functions.vkMapMemory = static_cast<PFN_vkMapMemory>(gpuVkMapMemory);
228 functions.vkUnmapMemory = static_cast<PFN_vkUnmapMemory>(gpuVkUnmapMemory);
229 functions.vkFlushMappedMemoryRanges = static_cast<PFN_vkFlushMappedMemoryRanges>(gpuVkFlushMappedMemoryRanges);
230 functions.vkInvalidateMappedMemoryRanges = static_cast<PFN_vkInvalidateMappedMemoryRanges>(gpuVkInvalidateMappedMemoryRanges);
231 functions.vkBindBufferMemory = static_cast<PFN_vkBindBufferMemory>(gpuVkBindBufferMemory);
232 functions.vkBindImageMemory = static_cast<PFN_vkBindImageMemory>(gpuVkBindImageMemory);
233 functions.vkGetBufferMemoryRequirements = static_cast<PFN_vkGetBufferMemoryRequirements>(gpuVkGetBufferMemoryRequirements);
234 functions.vkGetImageMemoryRequirements = static_cast<PFN_vkGetImageMemoryRequirements>(gpuVkGetImageMemoryRequirements);
235 functions.vkCreateBuffer = static_cast<PFN_vkCreateBuffer>(gpuVkCreateBuffer);
236 functions.vkDestroyBuffer = static_cast<PFN_vkDestroyBuffer>(gpuVkDestroyBuffer);
237 functions.vkCreateImage = static_cast<PFN_vkCreateImage>(gpuVkCreateImage);
238 functions.vkDestroyImage = static_cast<PFN_vkDestroyImage>(gpuVkDestroyImage);
239 functions.vkCmdCopyBuffer = static_cast<PFN_vkCmdCopyBuffer>(gpuVkCmdCopyBuffer);
240 allocator_info.pVulkanFunctions = &functions;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600241
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700242 return vmaCreateAllocator(&allocator_info, pAllocator);
Tony-LunarG1dce2392019-10-23 16:49:29 -0600243}
244
Tony-LunarGb5fae462020-03-05 12:43:25 -0700245void UtilPreCallRecordCreateDevice(VkPhysicalDevice gpu, safe_VkDeviceCreateInfo *modified_create_info,
246 VkPhysicalDeviceFeatures supported_features, VkPhysicalDeviceFeatures desired_features) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600247 VkPhysicalDeviceFeatures *features = nullptr;
248 if (modified_create_info->pEnabledFeatures) {
249 // If pEnabledFeatures, VkPhysicalDeviceFeatures2 in pNext chain is not allowed
250 features = const_cast<VkPhysicalDeviceFeatures *>(modified_create_info->pEnabledFeatures);
251 } else {
252 VkPhysicalDeviceFeatures2 *features2 = nullptr;
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700253 features2 = const_cast<VkPhysicalDeviceFeatures2 *>(LvlFindInChain<VkPhysicalDeviceFeatures2>(modified_create_info->pNext));
Tony-LunarG1dce2392019-10-23 16:49:29 -0600254 if (features2) features = &features2->features;
255 }
Tony-LunarGf0634eb2021-01-05 15:11:12 -0700256 VkPhysicalDeviceFeatures new_features = {};
257 VkBool32 *desired = reinterpret_cast<VkBool32 *>(&desired_features);
258 VkBool32 *feature_ptr;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600259 if (features) {
Tony-LunarGf0634eb2021-01-05 15:11:12 -0700260 feature_ptr = reinterpret_cast<VkBool32 *>(features);
Tony-LunarG1dce2392019-10-23 16:49:29 -0600261 } else {
Tony-LunarGf0634eb2021-01-05 15:11:12 -0700262 feature_ptr = reinterpret_cast<VkBool32 *>(&new_features);
263 }
264 VkBool32 *supported = reinterpret_cast<VkBool32 *>(&supported_features);
265 for (size_t i = 0; i < sizeof(VkPhysicalDeviceFeatures); i += (sizeof(VkBool32))) {
266 if (*supported && *desired) {
267 *feature_ptr = true;
268 }
269 supported++;
270 desired++;
271 feature_ptr++;
272 }
273 if (!features) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600274 delete modified_create_info->pEnabledFeatures;
275 modified_create_info->pEnabledFeatures = new VkPhysicalDeviceFeatures(new_features);
276 }
277}
278
279// Generate the stage-specific part of the message.
Tony-LunarGb5fae462020-03-05 12:43:25 -0700280void UtilGenerateStageMessage(const uint32_t *debug_record, std::string &msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600281 using namespace spvtools;
282 std::ostringstream strm;
283 switch (debug_record[kInstCommonOutStageIdx]) {
284 case spv::ExecutionModelVertex: {
285 strm << "Stage = Vertex. Vertex Index = " << debug_record[kInstVertOutVertexIndex]
286 << " Instance Index = " << debug_record[kInstVertOutInstanceIndex] << ". ";
287 } break;
288 case spv::ExecutionModelTessellationControl: {
289 strm << "Stage = Tessellation Control. Invocation ID = " << debug_record[kInstTessCtlOutInvocationId]
290 << ", Primitive ID = " << debug_record[kInstTessCtlOutPrimitiveId];
291 } break;
292 case spv::ExecutionModelTessellationEvaluation: {
293 strm << "Stage = Tessellation Eval. Primitive ID = " << debug_record[kInstTessEvalOutPrimitiveId]
294 << ", TessCoord (u, v) = (" << debug_record[kInstTessEvalOutTessCoordU] << ", "
295 << debug_record[kInstTessEvalOutTessCoordV] << "). ";
296 } break;
297 case spv::ExecutionModelGeometry: {
298 strm << "Stage = Geometry. Primitive ID = " << debug_record[kInstGeomOutPrimitiveId]
299 << " Invocation ID = " << debug_record[kInstGeomOutInvocationId] << ". ";
300 } break;
301 case spv::ExecutionModelFragment: {
302 strm << "Stage = Fragment. Fragment coord (x,y) = ("
303 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordX]) << ", "
304 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordY]) << "). ";
305 } break;
306 case spv::ExecutionModelGLCompute: {
307 strm << "Stage = Compute. Global invocation ID (x, y, z) = (" << debug_record[kInstCompOutGlobalInvocationIdX] << ", "
308 << debug_record[kInstCompOutGlobalInvocationIdY] << ", " << debug_record[kInstCompOutGlobalInvocationIdZ] << " )";
309 } break;
310 case spv::ExecutionModelRayGenerationNV: {
311 strm << "Stage = Ray Generation. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
312 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
313 } break;
314 case spv::ExecutionModelIntersectionNV: {
315 strm << "Stage = Intersection. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
316 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
317 } break;
318 case spv::ExecutionModelAnyHitNV: {
319 strm << "Stage = Any Hit. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
320 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
321 } break;
322 case spv::ExecutionModelClosestHitNV: {
323 strm << "Stage = Closest Hit. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
324 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
325 } break;
326 case spv::ExecutionModelMissNV: {
327 strm << "Stage = Miss. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
328 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
329 } break;
330 case spv::ExecutionModelCallableNV: {
331 strm << "Stage = Callable. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
332 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
333 } break;
Tony-LunarGc7ed2082020-06-11 14:00:04 -0600334 case spv::ExecutionModelTaskNV: {
335 strm << "Stage = Task. Global invocation ID (x, y, z) = (" << debug_record[kInstTaskOutGlobalInvocationIdX] << ", "
336 << debug_record[kInstTaskOutGlobalInvocationIdY] << ", " << debug_record[kInstTaskOutGlobalInvocationIdZ] << " )";
337 } break;
338 case spv::ExecutionModelMeshNV: {
339 strm << "Stage = Mesh.Global invocation ID (x, y, z) = (" << debug_record[kInstMeshOutGlobalInvocationIdX] << ", "
340 << debug_record[kInstMeshOutGlobalInvocationIdY] << ", " << debug_record[kInstMeshOutGlobalInvocationIdZ] << " )";
341 } break;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600342 default: {
343 strm << "Internal Error (unexpected stage = " << debug_record[kInstCommonOutStageIdx] << "). ";
344 assert(false);
345 } break;
346 }
347 msg = strm.str();
348}
349
350std::string LookupDebugUtilsName(const debug_report_data *report_data, const uint64_t object) {
351 auto object_label = report_data->DebugReportGetUtilsObjectName(object);
352 if (object_label != "") {
353 object_label = "(" + object_label + ")";
354 }
355 return object_label;
356}
357
358// Generate message from the common portion of the debug report record.
Tony-LunarGb5fae462020-03-05 12:43:25 -0700359void UtilGenerateCommonMessage(const debug_report_data *report_data, const VkCommandBuffer commandBuffer,
360 const uint32_t *debug_record, const VkShaderModule shader_module_handle,
361 const VkPipeline pipeline_handle, const VkPipelineBindPoint pipeline_bind_point,
362 const uint32_t operation_index, std::string &msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600363 using namespace spvtools;
364 std::ostringstream strm;
365 if (shader_module_handle == VK_NULL_HANDLE) {
366 strm << std::hex << std::showbase << "Internal Error: Unable to locate information for shader used in command buffer "
367 << LookupDebugUtilsName(report_data, HandleToUint64(commandBuffer)) << "(" << HandleToUint64(commandBuffer) << "). ";
368 assert(true);
369 } else {
370 strm << std::hex << std::showbase << "Command buffer " << LookupDebugUtilsName(report_data, HandleToUint64(commandBuffer))
371 << "(" << HandleToUint64(commandBuffer) << "). ";
372 if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS) {
373 strm << "Draw ";
374 } else if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_COMPUTE) {
375 strm << "Compute ";
376 } else if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_RAY_TRACING_NV) {
377 strm << "Ray Trace ";
378 } else {
379 assert(false);
380 strm << "Unknown Pipeline Operation ";
381 }
382 strm << "Index " << operation_index << ". "
383 << "Pipeline " << LookupDebugUtilsName(report_data, HandleToUint64(pipeline_handle)) << "("
384 << HandleToUint64(pipeline_handle) << "). "
385 << "Shader Module " << LookupDebugUtilsName(report_data, HandleToUint64(shader_module_handle)) << "("
386 << HandleToUint64(shader_module_handle) << "). ";
387 }
388 strm << std::dec << std::noshowbase;
389 strm << "Shader Instruction Index = " << debug_record[kInstCommonOutInstructionIdx] << ". ";
390 msg = strm.str();
391}
392
393// Read the contents of the SPIR-V OpSource instruction and any following continuation instructions.
394// Split the single string into a vector of strings, one for each line, for easier processing.
395void ReadOpSource(const SHADER_MODULE_STATE &shader, const uint32_t reported_file_id, std::vector<std::string> &opsource_lines) {
396 for (auto insn : shader) {
397 if ((insn.opcode() == spv::OpSource) && (insn.len() >= 5) && (insn.word(3) == reported_file_id)) {
398 std::istringstream in_stream;
399 std::string cur_line;
400 in_stream.str((char *)&insn.word(4));
401 while (std::getline(in_stream, cur_line)) {
402 opsource_lines.push_back(cur_line);
403 }
404 while ((++insn).opcode() == spv::OpSourceContinued) {
405 in_stream.str((char *)&insn.word(1));
406 while (std::getline(in_stream, cur_line)) {
407 opsource_lines.push_back(cur_line);
408 }
409 }
410 break;
411 }
412 }
413}
414
415// The task here is to search the OpSource content to find the #line directive with the
416// line number that is closest to, but still prior to the reported error line number and
417// still within the reported filename.
418// From this known position in the OpSource content we can add the difference between
419// the #line line number and the reported error line number to determine the location
420// in the OpSource content of the reported error line.
421//
422// Considerations:
423// - Look only at #line directives that specify the reported_filename since
424// the reported error line number refers to its location in the reported filename.
425// - If a #line directive does not have a filename, the file is the reported filename, or
426// the filename found in a prior #line directive. (This is C-preprocessor behavior)
427// - It is possible (e.g., inlining) for blocks of code to get shuffled out of their
428// original order and the #line directives are used to keep the numbering correct. This
429// is why we need to examine the entire contents of the source, instead of leaving early
430// when finding a #line line number larger than the reported error line number.
431//
432
433// GCC 4.8 has a problem with std::regex that is fixed in GCC 4.9. Provide fallback code for 4.8
434#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
435
436#if defined(__GNUC__) && GCC_VERSION < 40900
437bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
438 // # line <linenumber> "<filename>" or
439 // #line <linenumber> "<filename>"
440 std::vector<std::string> tokens;
441 std::stringstream stream(string);
442 std::string temp;
443 uint32_t line_index = 0;
444
445 while (stream >> temp) tokens.push_back(temp);
446 auto size = tokens.size();
447 if (size > 1) {
448 if (tokens[0] == "#" && tokens[1] == "line") {
449 line_index = 2;
450 } else if (tokens[0] == "#line") {
451 line_index = 1;
452 }
453 }
454 if (0 == line_index) return false;
Mark Young0ec6b062020-11-19 15:32:17 -0700455 *linenumber = static_cast<uint32_t>(std::stoul(tokens[line_index]));
Tony-LunarG1dce2392019-10-23 16:49:29 -0600456 uint32_t filename_index = line_index + 1;
457 // Remove enclosing double quotes around filename
458 if (size > filename_index) filename = tokens[filename_index].substr(1, tokens[filename_index].size() - 2);
459 return true;
460}
461#else
462bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
463 static const std::regex line_regex( // matches #line directives
464 "^" // beginning of line
465 "\\s*" // optional whitespace
466 "#" // required text
467 "\\s*" // optional whitespace
468 "line" // required text
469 "\\s+" // required whitespace
470 "([0-9]+)" // required first capture - line number
471 "(\\s+)?" // optional second capture - whitespace
472 "(\".+\")?" // optional third capture - quoted filename with at least one char inside
473 ".*"); // rest of line (needed when using std::regex_match since the entire line is tested)
474
475 std::smatch captures;
476
477 bool found_line = std::regex_match(string, captures, line_regex);
478 if (!found_line) return false;
479
480 // filename is optional and considered found only if the whitespace and the filename are captured
481 if (captures[2].matched && captures[3].matched) {
482 // Remove enclosing double quotes. The regex guarantees the quotes and at least one char.
483 filename = captures[3].str().substr(1, captures[3].str().size() - 2);
484 }
485 *linenumber = std::stoul(captures[1]);
486 return true;
487}
488#endif // GCC_VERSION
489
490// Extract the filename, line number, and column number from the correct OpLine and build a message string from it.
491// Scan the source (from OpSource) to find the line of source at the reported line number and place it in another message string.
Tony-LunarGb5fae462020-03-05 12:43:25 -0700492void UtilGenerateSourceMessages(const std::vector<unsigned int> &pgm, const uint32_t *debug_record, bool from_printf,
493 std::string &filename_msg, std::string &source_msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600494 using namespace spvtools;
495 std::ostringstream filename_stream;
496 std::ostringstream source_stream;
497 SHADER_MODULE_STATE shader;
498 shader.words = pgm;
499 // Find the OpLine just before the failing instruction indicated by the debug info.
500 // SPIR-V can only be iterated in the forward direction due to its opcode/length encoding.
501 uint32_t instruction_index = 0;
502 uint32_t reported_file_id = 0;
503 uint32_t reported_line_number = 0;
504 uint32_t reported_column_number = 0;
505 if (shader.words.size() > 0) {
506 for (auto insn : shader) {
507 if (insn.opcode() == spv::OpLine) {
508 reported_file_id = insn.word(1);
509 reported_line_number = insn.word(2);
510 reported_column_number = insn.word(3);
511 }
512 if (instruction_index == debug_record[kInstCommonOutInstructionIdx]) {
513 break;
514 }
515 instruction_index++;
516 }
517 }
518 // Create message with file information obtained from the OpString pointed to by the discovered OpLine.
519 std::string reported_filename;
520 if (reported_file_id == 0) {
521 filename_stream
522 << "Unable to find SPIR-V OpLine for source information. Build shader with debug info to get source information.";
523 } else {
524 bool found_opstring = false;
525 std::string prefix;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700526 if (from_printf) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600527 prefix = "Debug shader printf message generated ";
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700528 } else {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600529 prefix = "Shader validation error occurred ";
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700530 }
Tony-LunarG1dce2392019-10-23 16:49:29 -0600531 for (auto insn : shader) {
532 if ((insn.opcode() == spv::OpString) && (insn.len() >= 3) && (insn.word(1) == reported_file_id)) {
533 found_opstring = true;
534 reported_filename = (char *)&insn.word(2);
535 if (reported_filename.empty()) {
536 filename_stream << prefix << "at line " << reported_line_number;
537 } else {
538 filename_stream << prefix << "in file " << reported_filename << " at line " << reported_line_number;
539 }
540 if (reported_column_number > 0) {
541 filename_stream << ", column " << reported_column_number;
542 }
543 filename_stream << ".";
544 break;
545 }
546 }
547 if (!found_opstring) {
Tony-LunarG6d195e12020-10-27 16:54:14 -0600548 filename_stream << "Unable to find SPIR-V OpString for file id " << reported_file_id << " from OpLine instruction."
549 << std::endl;
550 filename_stream << "File ID = " << reported_file_id << ", Line Number = " << reported_line_number
551 << ", Column = " << reported_column_number << std::endl;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600552 }
553 }
554 filename_msg = filename_stream.str();
555
556 // Create message to display source code line containing error.
557 if ((reported_file_id != 0)) {
558 // Read the source code and split it up into separate lines.
559 std::vector<std::string> opsource_lines;
560 ReadOpSource(shader, reported_file_id, opsource_lines);
561 // Find the line in the OpSource content that corresponds to the reported error file and line.
562 if (!opsource_lines.empty()) {
563 uint32_t saved_line_number = 0;
564 std::string current_filename = reported_filename; // current "preprocessor" filename state.
565 std::vector<std::string>::size_type saved_opsource_offset = 0;
566 bool found_best_line = false;
567 for (auto it = opsource_lines.begin(); it != opsource_lines.end(); ++it) {
568 uint32_t parsed_line_number;
569 std::string parsed_filename;
570 bool found_line = GetLineAndFilename(*it, &parsed_line_number, parsed_filename);
571 if (!found_line) continue;
572
573 bool found_filename = parsed_filename.size() > 0;
574 if (found_filename) {
575 current_filename = parsed_filename;
576 }
577 if ((!found_filename) || (current_filename == reported_filename)) {
578 // Update the candidate best line directive, if the current one is prior and closer to the reported line
579 if (reported_line_number >= parsed_line_number) {
580 if (!found_best_line ||
581 (reported_line_number - parsed_line_number <= reported_line_number - saved_line_number)) {
582 saved_line_number = parsed_line_number;
583 saved_opsource_offset = std::distance(opsource_lines.begin(), it);
584 found_best_line = true;
585 }
586 }
587 }
588 }
589 if (found_best_line) {
590 assert(reported_line_number >= saved_line_number);
591 std::vector<std::string>::size_type opsource_index =
592 (reported_line_number - saved_line_number) + 1 + saved_opsource_offset;
593 if (opsource_index < opsource_lines.size()) {
594 source_stream << "\n" << reported_line_number << ": " << opsource_lines[opsource_index].c_str();
595 } else {
596 source_stream << "Internal error: calculated source line of " << opsource_index << " for source size of "
597 << opsource_lines.size() << " lines.";
598 }
599 } else {
600 source_stream << "Unable to find suitable #line directive in SPIR-V OpSource.";
601 }
602 } else {
603 source_stream << "Unable to find SPIR-V OpSource.";
604 }
605 }
606 source_msg = source_stream.str();
607}