blob: d5aa95490ecf6d224dc2470efac2341152d76ac9 [file] [log] [blame]
Tony-LunarGb5fae462020-03-05 12:43:25 -07001/* Copyright (c) 2020 The Khronos Group Inc.
2 * Copyright (c) 2020 Valve Corporation
3 * Copyright (c) 2020 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;
218 VmaAllocatorCreateInfo allocatorInfo = {};
219 allocatorInfo.device = device;
220 allocatorInfo.physicalDevice = physical_device;
221
222 functions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)gpuVkGetPhysicalDeviceProperties;
223 functions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)gpuVkGetPhysicalDeviceMemoryProperties;
224 functions.vkAllocateMemory = (PFN_vkAllocateMemory)gpuVkAllocateMemory;
225 functions.vkFreeMemory = (PFN_vkFreeMemory)gpuVkFreeMemory;
226 functions.vkMapMemory = (PFN_vkMapMemory)gpuVkMapMemory;
227 functions.vkUnmapMemory = (PFN_vkUnmapMemory)gpuVkUnmapMemory;
228 functions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)gpuVkFlushMappedMemoryRanges;
229 functions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)gpuVkInvalidateMappedMemoryRanges;
230 functions.vkBindBufferMemory = (PFN_vkBindBufferMemory)gpuVkBindBufferMemory;
231 functions.vkBindImageMemory = (PFN_vkBindImageMemory)gpuVkBindImageMemory;
232 functions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)gpuVkGetBufferMemoryRequirements;
233 functions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)gpuVkGetImageMemoryRequirements;
234 functions.vkCreateBuffer = (PFN_vkCreateBuffer)gpuVkCreateBuffer;
235 functions.vkDestroyBuffer = (PFN_vkDestroyBuffer)gpuVkDestroyBuffer;
236 functions.vkCreateImage = (PFN_vkCreateImage)gpuVkCreateImage;
237 functions.vkDestroyImage = (PFN_vkDestroyImage)gpuVkDestroyImage;
238 functions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)gpuVkCmdCopyBuffer;
239 allocatorInfo.pVulkanFunctions = &functions;
240
241 return vmaCreateAllocator(&allocatorInfo, pAllocator);
242}
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;
252 features2 =
253 const_cast<VkPhysicalDeviceFeatures2 *>(lvl_find_in_chain<VkPhysicalDeviceFeatures2>(modified_create_info->pNext));
254 if (features2) features = &features2->features;
255 }
256 if (features) {
257 VkBool32 *desired = reinterpret_cast<VkBool32 *>(&desired_features);
Tony-LunarG04dc83c2020-07-07 13:53:02 -0600258 VkBool32 *featurePtr = reinterpret_cast<VkBool32 *>(features);
Tony-LunarG1dce2392019-10-23 16:49:29 -0600259 VkBool32 *supported = reinterpret_cast<VkBool32 *>(&supported_features);
260 for (size_t i = 0; i < sizeof(VkPhysicalDeviceFeatures); i += (sizeof(VkBool32))) {
Tony-LunarG04dc83c2020-07-07 13:53:02 -0600261 if (*supported && *desired) {
262 *featurePtr = true;
263 }
264 supported++;
265 desired++;
266 featurePtr++;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600267 }
268 } else {
269 VkPhysicalDeviceFeatures new_features = {};
270 new_features = desired_features;
271 delete modified_create_info->pEnabledFeatures;
272 modified_create_info->pEnabledFeatures = new VkPhysicalDeviceFeatures(new_features);
273 }
274}
275
276// Generate the stage-specific part of the message.
Tony-LunarGb5fae462020-03-05 12:43:25 -0700277void UtilGenerateStageMessage(const uint32_t *debug_record, std::string &msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600278 using namespace spvtools;
279 std::ostringstream strm;
280 switch (debug_record[kInstCommonOutStageIdx]) {
281 case spv::ExecutionModelVertex: {
282 strm << "Stage = Vertex. Vertex Index = " << debug_record[kInstVertOutVertexIndex]
283 << " Instance Index = " << debug_record[kInstVertOutInstanceIndex] << ". ";
284 } break;
285 case spv::ExecutionModelTessellationControl: {
286 strm << "Stage = Tessellation Control. Invocation ID = " << debug_record[kInstTessCtlOutInvocationId]
287 << ", Primitive ID = " << debug_record[kInstTessCtlOutPrimitiveId];
288 } break;
289 case spv::ExecutionModelTessellationEvaluation: {
290 strm << "Stage = Tessellation Eval. Primitive ID = " << debug_record[kInstTessEvalOutPrimitiveId]
291 << ", TessCoord (u, v) = (" << debug_record[kInstTessEvalOutTessCoordU] << ", "
292 << debug_record[kInstTessEvalOutTessCoordV] << "). ";
293 } break;
294 case spv::ExecutionModelGeometry: {
295 strm << "Stage = Geometry. Primitive ID = " << debug_record[kInstGeomOutPrimitiveId]
296 << " Invocation ID = " << debug_record[kInstGeomOutInvocationId] << ". ";
297 } break;
298 case spv::ExecutionModelFragment: {
299 strm << "Stage = Fragment. Fragment coord (x,y) = ("
300 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordX]) << ", "
301 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordY]) << "). ";
302 } break;
303 case spv::ExecutionModelGLCompute: {
304 strm << "Stage = Compute. Global invocation ID (x, y, z) = (" << debug_record[kInstCompOutGlobalInvocationIdX] << ", "
305 << debug_record[kInstCompOutGlobalInvocationIdY] << ", " << debug_record[kInstCompOutGlobalInvocationIdZ] << " )";
306 } break;
307 case spv::ExecutionModelRayGenerationNV: {
308 strm << "Stage = Ray Generation. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
309 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
310 } break;
311 case spv::ExecutionModelIntersectionNV: {
312 strm << "Stage = Intersection. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
313 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
314 } break;
315 case spv::ExecutionModelAnyHitNV: {
316 strm << "Stage = Any Hit. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
317 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
318 } break;
319 case spv::ExecutionModelClosestHitNV: {
320 strm << "Stage = Closest Hit. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
321 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
322 } break;
323 case spv::ExecutionModelMissNV: {
324 strm << "Stage = Miss. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
325 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
326 } break;
327 case spv::ExecutionModelCallableNV: {
328 strm << "Stage = Callable. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
329 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
330 } break;
Tony-LunarGc7ed2082020-06-11 14:00:04 -0600331 case spv::ExecutionModelTaskNV: {
332 strm << "Stage = Task. Global invocation ID (x, y, z) = (" << debug_record[kInstTaskOutGlobalInvocationIdX] << ", "
333 << debug_record[kInstTaskOutGlobalInvocationIdY] << ", " << debug_record[kInstTaskOutGlobalInvocationIdZ] << " )";
334 } break;
335 case spv::ExecutionModelMeshNV: {
336 strm << "Stage = Mesh.Global invocation ID (x, y, z) = (" << debug_record[kInstMeshOutGlobalInvocationIdX] << ", "
337 << debug_record[kInstMeshOutGlobalInvocationIdY] << ", " << debug_record[kInstMeshOutGlobalInvocationIdZ] << " )";
338 } break;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600339 default: {
340 strm << "Internal Error (unexpected stage = " << debug_record[kInstCommonOutStageIdx] << "). ";
341 assert(false);
342 } break;
343 }
344 msg = strm.str();
345}
346
347std::string LookupDebugUtilsName(const debug_report_data *report_data, const uint64_t object) {
348 auto object_label = report_data->DebugReportGetUtilsObjectName(object);
349 if (object_label != "") {
350 object_label = "(" + object_label + ")";
351 }
352 return object_label;
353}
354
355// Generate message from the common portion of the debug report record.
Tony-LunarGb5fae462020-03-05 12:43:25 -0700356void UtilGenerateCommonMessage(const debug_report_data *report_data, const VkCommandBuffer commandBuffer,
357 const uint32_t *debug_record, const VkShaderModule shader_module_handle,
358 const VkPipeline pipeline_handle, const VkPipelineBindPoint pipeline_bind_point,
359 const uint32_t operation_index, std::string &msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600360 using namespace spvtools;
361 std::ostringstream strm;
362 if (shader_module_handle == VK_NULL_HANDLE) {
363 strm << std::hex << std::showbase << "Internal Error: Unable to locate information for shader used in command buffer "
364 << LookupDebugUtilsName(report_data, HandleToUint64(commandBuffer)) << "(" << HandleToUint64(commandBuffer) << "). ";
365 assert(true);
366 } else {
367 strm << std::hex << std::showbase << "Command buffer " << LookupDebugUtilsName(report_data, HandleToUint64(commandBuffer))
368 << "(" << HandleToUint64(commandBuffer) << "). ";
369 if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS) {
370 strm << "Draw ";
371 } else if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_COMPUTE) {
372 strm << "Compute ";
373 } else if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_RAY_TRACING_NV) {
374 strm << "Ray Trace ";
375 } else {
376 assert(false);
377 strm << "Unknown Pipeline Operation ";
378 }
379 strm << "Index " << operation_index << ". "
380 << "Pipeline " << LookupDebugUtilsName(report_data, HandleToUint64(pipeline_handle)) << "("
381 << HandleToUint64(pipeline_handle) << "). "
382 << "Shader Module " << LookupDebugUtilsName(report_data, HandleToUint64(shader_module_handle)) << "("
383 << HandleToUint64(shader_module_handle) << "). ";
384 }
385 strm << std::dec << std::noshowbase;
386 strm << "Shader Instruction Index = " << debug_record[kInstCommonOutInstructionIdx] << ". ";
387 msg = strm.str();
388}
389
390// Read the contents of the SPIR-V OpSource instruction and any following continuation instructions.
391// Split the single string into a vector of strings, one for each line, for easier processing.
392void ReadOpSource(const SHADER_MODULE_STATE &shader, const uint32_t reported_file_id, std::vector<std::string> &opsource_lines) {
393 for (auto insn : shader) {
394 if ((insn.opcode() == spv::OpSource) && (insn.len() >= 5) && (insn.word(3) == reported_file_id)) {
395 std::istringstream in_stream;
396 std::string cur_line;
397 in_stream.str((char *)&insn.word(4));
398 while (std::getline(in_stream, cur_line)) {
399 opsource_lines.push_back(cur_line);
400 }
401 while ((++insn).opcode() == spv::OpSourceContinued) {
402 in_stream.str((char *)&insn.word(1));
403 while (std::getline(in_stream, cur_line)) {
404 opsource_lines.push_back(cur_line);
405 }
406 }
407 break;
408 }
409 }
410}
411
412// The task here is to search the OpSource content to find the #line directive with the
413// line number that is closest to, but still prior to the reported error line number and
414// still within the reported filename.
415// From this known position in the OpSource content we can add the difference between
416// the #line line number and the reported error line number to determine the location
417// in the OpSource content of the reported error line.
418//
419// Considerations:
420// - Look only at #line directives that specify the reported_filename since
421// the reported error line number refers to its location in the reported filename.
422// - If a #line directive does not have a filename, the file is the reported filename, or
423// the filename found in a prior #line directive. (This is C-preprocessor behavior)
424// - It is possible (e.g., inlining) for blocks of code to get shuffled out of their
425// original order and the #line directives are used to keep the numbering correct. This
426// is why we need to examine the entire contents of the source, instead of leaving early
427// when finding a #line line number larger than the reported error line number.
428//
429
430// GCC 4.8 has a problem with std::regex that is fixed in GCC 4.9. Provide fallback code for 4.8
431#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
432
433#if defined(__GNUC__) && GCC_VERSION < 40900
434bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
435 // # line <linenumber> "<filename>" or
436 // #line <linenumber> "<filename>"
437 std::vector<std::string> tokens;
438 std::stringstream stream(string);
439 std::string temp;
440 uint32_t line_index = 0;
441
442 while (stream >> temp) tokens.push_back(temp);
443 auto size = tokens.size();
444 if (size > 1) {
445 if (tokens[0] == "#" && tokens[1] == "line") {
446 line_index = 2;
447 } else if (tokens[0] == "#line") {
448 line_index = 1;
449 }
450 }
451 if (0 == line_index) return false;
Mark Young0ec6b062020-11-19 15:32:17 -0700452 *linenumber = static_cast<uint32_t>(std::stoul(tokens[line_index]));
Tony-LunarG1dce2392019-10-23 16:49:29 -0600453 uint32_t filename_index = line_index + 1;
454 // Remove enclosing double quotes around filename
455 if (size > filename_index) filename = tokens[filename_index].substr(1, tokens[filename_index].size() - 2);
456 return true;
457}
458#else
459bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
460 static const std::regex line_regex( // matches #line directives
461 "^" // beginning of line
462 "\\s*" // optional whitespace
463 "#" // required text
464 "\\s*" // optional whitespace
465 "line" // required text
466 "\\s+" // required whitespace
467 "([0-9]+)" // required first capture - line number
468 "(\\s+)?" // optional second capture - whitespace
469 "(\".+\")?" // optional third capture - quoted filename with at least one char inside
470 ".*"); // rest of line (needed when using std::regex_match since the entire line is tested)
471
472 std::smatch captures;
473
474 bool found_line = std::regex_match(string, captures, line_regex);
475 if (!found_line) return false;
476
477 // filename is optional and considered found only if the whitespace and the filename are captured
478 if (captures[2].matched && captures[3].matched) {
479 // Remove enclosing double quotes. The regex guarantees the quotes and at least one char.
480 filename = captures[3].str().substr(1, captures[3].str().size() - 2);
481 }
482 *linenumber = std::stoul(captures[1]);
483 return true;
484}
485#endif // GCC_VERSION
486
487// Extract the filename, line number, and column number from the correct OpLine and build a message string from it.
488// 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 -0700489void UtilGenerateSourceMessages(const std::vector<unsigned int> &pgm, const uint32_t *debug_record, bool from_printf,
490 std::string &filename_msg, std::string &source_msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600491 using namespace spvtools;
492 std::ostringstream filename_stream;
493 std::ostringstream source_stream;
494 SHADER_MODULE_STATE shader;
495 shader.words = pgm;
496 // Find the OpLine just before the failing instruction indicated by the debug info.
497 // SPIR-V can only be iterated in the forward direction due to its opcode/length encoding.
498 uint32_t instruction_index = 0;
499 uint32_t reported_file_id = 0;
500 uint32_t reported_line_number = 0;
501 uint32_t reported_column_number = 0;
502 if (shader.words.size() > 0) {
503 for (auto insn : shader) {
504 if (insn.opcode() == spv::OpLine) {
505 reported_file_id = insn.word(1);
506 reported_line_number = insn.word(2);
507 reported_column_number = insn.word(3);
508 }
509 if (instruction_index == debug_record[kInstCommonOutInstructionIdx]) {
510 break;
511 }
512 instruction_index++;
513 }
514 }
515 // Create message with file information obtained from the OpString pointed to by the discovered OpLine.
516 std::string reported_filename;
517 if (reported_file_id == 0) {
518 filename_stream
519 << "Unable to find SPIR-V OpLine for source information. Build shader with debug info to get source information.";
520 } else {
521 bool found_opstring = false;
522 std::string prefix;
523 if (from_printf)
524 prefix = "Debug shader printf message generated ";
525 else
526 prefix = "Shader validation error occurred ";
527 for (auto insn : shader) {
528 if ((insn.opcode() == spv::OpString) && (insn.len() >= 3) && (insn.word(1) == reported_file_id)) {
529 found_opstring = true;
530 reported_filename = (char *)&insn.word(2);
531 if (reported_filename.empty()) {
532 filename_stream << prefix << "at line " << reported_line_number;
533 } else {
534 filename_stream << prefix << "in file " << reported_filename << " at line " << reported_line_number;
535 }
536 if (reported_column_number > 0) {
537 filename_stream << ", column " << reported_column_number;
538 }
539 filename_stream << ".";
540 break;
541 }
542 }
543 if (!found_opstring) {
Tony-LunarG6d195e12020-10-27 16:54:14 -0600544 filename_stream << "Unable to find SPIR-V OpString for file id " << reported_file_id << " from OpLine instruction."
545 << std::endl;
546 filename_stream << "File ID = " << reported_file_id << ", Line Number = " << reported_line_number
547 << ", Column = " << reported_column_number << std::endl;
Tony-LunarG1dce2392019-10-23 16:49:29 -0600548 }
549 }
550 filename_msg = filename_stream.str();
551
552 // Create message to display source code line containing error.
553 if ((reported_file_id != 0)) {
554 // Read the source code and split it up into separate lines.
555 std::vector<std::string> opsource_lines;
556 ReadOpSource(shader, reported_file_id, opsource_lines);
557 // Find the line in the OpSource content that corresponds to the reported error file and line.
558 if (!opsource_lines.empty()) {
559 uint32_t saved_line_number = 0;
560 std::string current_filename = reported_filename; // current "preprocessor" filename state.
561 std::vector<std::string>::size_type saved_opsource_offset = 0;
562 bool found_best_line = false;
563 for (auto it = opsource_lines.begin(); it != opsource_lines.end(); ++it) {
564 uint32_t parsed_line_number;
565 std::string parsed_filename;
566 bool found_line = GetLineAndFilename(*it, &parsed_line_number, parsed_filename);
567 if (!found_line) continue;
568
569 bool found_filename = parsed_filename.size() > 0;
570 if (found_filename) {
571 current_filename = parsed_filename;
572 }
573 if ((!found_filename) || (current_filename == reported_filename)) {
574 // Update the candidate best line directive, if the current one is prior and closer to the reported line
575 if (reported_line_number >= parsed_line_number) {
576 if (!found_best_line ||
577 (reported_line_number - parsed_line_number <= reported_line_number - saved_line_number)) {
578 saved_line_number = parsed_line_number;
579 saved_opsource_offset = std::distance(opsource_lines.begin(), it);
580 found_best_line = true;
581 }
582 }
583 }
584 }
585 if (found_best_line) {
586 assert(reported_line_number >= saved_line_number);
587 std::vector<std::string>::size_type opsource_index =
588 (reported_line_number - saved_line_number) + 1 + saved_opsource_offset;
589 if (opsource_index < opsource_lines.size()) {
590 source_stream << "\n" << reported_line_number << ": " << opsource_lines[opsource_index].c_str();
591 } else {
592 source_stream << "Internal error: calculated source line of " << opsource_index << " for source size of "
593 << opsource_lines.size() << " lines.";
594 }
595 } else {
596 source_stream << "Unable to find suitable #line directive in SPIR-V OpSource.";
597 }
598 } else {
599 source_stream << "Unable to find SPIR-V OpSource.";
600 }
601 }
602 source_msg = source_stream.str();
603}