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