blob: 29387982c28d782bc6625e9cfcea3f303ef74a5a [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);
258 VkBool32 *featurePtr = reinterpret_cast<VkBool32 *>(&features);
259 VkBool32 *supported = reinterpret_cast<VkBool32 *>(&supported_features);
260 for (size_t i = 0; i < sizeof(VkPhysicalDeviceFeatures); i += (sizeof(VkBool32))) {
261 *featurePtr++ |= (*supported++ & *desired++);
262 }
263 } else {
264 VkPhysicalDeviceFeatures new_features = {};
265 new_features = desired_features;
266 delete modified_create_info->pEnabledFeatures;
267 modified_create_info->pEnabledFeatures = new VkPhysicalDeviceFeatures(new_features);
268 }
269}
270
271// Generate the stage-specific part of the message.
Tony-LunarGb5fae462020-03-05 12:43:25 -0700272void UtilGenerateStageMessage(const uint32_t *debug_record, std::string &msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600273 using namespace spvtools;
274 std::ostringstream strm;
275 switch (debug_record[kInstCommonOutStageIdx]) {
276 case spv::ExecutionModelVertex: {
277 strm << "Stage = Vertex. Vertex Index = " << debug_record[kInstVertOutVertexIndex]
278 << " Instance Index = " << debug_record[kInstVertOutInstanceIndex] << ". ";
279 } break;
280 case spv::ExecutionModelTessellationControl: {
281 strm << "Stage = Tessellation Control. Invocation ID = " << debug_record[kInstTessCtlOutInvocationId]
282 << ", Primitive ID = " << debug_record[kInstTessCtlOutPrimitiveId];
283 } break;
284 case spv::ExecutionModelTessellationEvaluation: {
285 strm << "Stage = Tessellation Eval. Primitive ID = " << debug_record[kInstTessEvalOutPrimitiveId]
286 << ", TessCoord (u, v) = (" << debug_record[kInstTessEvalOutTessCoordU] << ", "
287 << debug_record[kInstTessEvalOutTessCoordV] << "). ";
288 } break;
289 case spv::ExecutionModelGeometry: {
290 strm << "Stage = Geometry. Primitive ID = " << debug_record[kInstGeomOutPrimitiveId]
291 << " Invocation ID = " << debug_record[kInstGeomOutInvocationId] << ". ";
292 } break;
293 case spv::ExecutionModelFragment: {
294 strm << "Stage = Fragment. Fragment coord (x,y) = ("
295 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordX]) << ", "
296 << *reinterpret_cast<const float *>(&debug_record[kInstFragOutFragCoordY]) << "). ";
297 } break;
298 case spv::ExecutionModelGLCompute: {
299 strm << "Stage = Compute. Global invocation ID (x, y, z) = (" << debug_record[kInstCompOutGlobalInvocationIdX] << ", "
300 << debug_record[kInstCompOutGlobalInvocationIdY] << ", " << debug_record[kInstCompOutGlobalInvocationIdZ] << " )";
301 } break;
302 case spv::ExecutionModelRayGenerationNV: {
303 strm << "Stage = Ray Generation. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
304 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
305 } break;
306 case spv::ExecutionModelIntersectionNV: {
307 strm << "Stage = Intersection. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
308 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
309 } break;
310 case spv::ExecutionModelAnyHitNV: {
311 strm << "Stage = Any Hit. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
312 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
313 } break;
314 case spv::ExecutionModelClosestHitNV: {
315 strm << "Stage = Closest Hit. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
316 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
317 } break;
318 case spv::ExecutionModelMissNV: {
319 strm << "Stage = Miss. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
320 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
321 } break;
322 case spv::ExecutionModelCallableNV: {
323 strm << "Stage = Callable. Global Launch ID (x,y,z) = (" << debug_record[kInstRayTracingOutLaunchIdX] << ", "
324 << debug_record[kInstRayTracingOutLaunchIdY] << ", " << debug_record[kInstRayTracingOutLaunchIdZ] << "). ";
325 } break;
326 default: {
327 strm << "Internal Error (unexpected stage = " << debug_record[kInstCommonOutStageIdx] << "). ";
328 assert(false);
329 } break;
330 }
331 msg = strm.str();
332}
333
334std::string LookupDebugUtilsName(const debug_report_data *report_data, const uint64_t object) {
335 auto object_label = report_data->DebugReportGetUtilsObjectName(object);
336 if (object_label != "") {
337 object_label = "(" + object_label + ")";
338 }
339 return object_label;
340}
341
342// Generate message from the common portion of the debug report record.
Tony-LunarGb5fae462020-03-05 12:43:25 -0700343void UtilGenerateCommonMessage(const debug_report_data *report_data, const VkCommandBuffer commandBuffer,
344 const uint32_t *debug_record, const VkShaderModule shader_module_handle,
345 const VkPipeline pipeline_handle, const VkPipelineBindPoint pipeline_bind_point,
346 const uint32_t operation_index, std::string &msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600347 using namespace spvtools;
348 std::ostringstream strm;
349 if (shader_module_handle == VK_NULL_HANDLE) {
350 strm << std::hex << std::showbase << "Internal Error: Unable to locate information for shader used in command buffer "
351 << LookupDebugUtilsName(report_data, HandleToUint64(commandBuffer)) << "(" << HandleToUint64(commandBuffer) << "). ";
352 assert(true);
353 } else {
354 strm << std::hex << std::showbase << "Command buffer " << LookupDebugUtilsName(report_data, HandleToUint64(commandBuffer))
355 << "(" << HandleToUint64(commandBuffer) << "). ";
356 if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS) {
357 strm << "Draw ";
358 } else if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_COMPUTE) {
359 strm << "Compute ";
360 } else if (pipeline_bind_point == VK_PIPELINE_BIND_POINT_RAY_TRACING_NV) {
361 strm << "Ray Trace ";
362 } else {
363 assert(false);
364 strm << "Unknown Pipeline Operation ";
365 }
366 strm << "Index " << operation_index << ". "
367 << "Pipeline " << LookupDebugUtilsName(report_data, HandleToUint64(pipeline_handle)) << "("
368 << HandleToUint64(pipeline_handle) << "). "
369 << "Shader Module " << LookupDebugUtilsName(report_data, HandleToUint64(shader_module_handle)) << "("
370 << HandleToUint64(shader_module_handle) << "). ";
371 }
372 strm << std::dec << std::noshowbase;
373 strm << "Shader Instruction Index = " << debug_record[kInstCommonOutInstructionIdx] << ". ";
374 msg = strm.str();
375}
376
377// Read the contents of the SPIR-V OpSource instruction and any following continuation instructions.
378// Split the single string into a vector of strings, one for each line, for easier processing.
379void ReadOpSource(const SHADER_MODULE_STATE &shader, const uint32_t reported_file_id, std::vector<std::string> &opsource_lines) {
380 for (auto insn : shader) {
381 if ((insn.opcode() == spv::OpSource) && (insn.len() >= 5) && (insn.word(3) == reported_file_id)) {
382 std::istringstream in_stream;
383 std::string cur_line;
384 in_stream.str((char *)&insn.word(4));
385 while (std::getline(in_stream, cur_line)) {
386 opsource_lines.push_back(cur_line);
387 }
388 while ((++insn).opcode() == spv::OpSourceContinued) {
389 in_stream.str((char *)&insn.word(1));
390 while (std::getline(in_stream, cur_line)) {
391 opsource_lines.push_back(cur_line);
392 }
393 }
394 break;
395 }
396 }
397}
398
399// The task here is to search the OpSource content to find the #line directive with the
400// line number that is closest to, but still prior to the reported error line number and
401// still within the reported filename.
402// From this known position in the OpSource content we can add the difference between
403// the #line line number and the reported error line number to determine the location
404// in the OpSource content of the reported error line.
405//
406// Considerations:
407// - Look only at #line directives that specify the reported_filename since
408// the reported error line number refers to its location in the reported filename.
409// - If a #line directive does not have a filename, the file is the reported filename, or
410// the filename found in a prior #line directive. (This is C-preprocessor behavior)
411// - It is possible (e.g., inlining) for blocks of code to get shuffled out of their
412// original order and the #line directives are used to keep the numbering correct. This
413// is why we need to examine the entire contents of the source, instead of leaving early
414// when finding a #line line number larger than the reported error line number.
415//
416
417// GCC 4.8 has a problem with std::regex that is fixed in GCC 4.9. Provide fallback code for 4.8
418#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
419
420#if defined(__GNUC__) && GCC_VERSION < 40900
421bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
422 // # line <linenumber> "<filename>" or
423 // #line <linenumber> "<filename>"
424 std::vector<std::string> tokens;
425 std::stringstream stream(string);
426 std::string temp;
427 uint32_t line_index = 0;
428
429 while (stream >> temp) tokens.push_back(temp);
430 auto size = tokens.size();
431 if (size > 1) {
432 if (tokens[0] == "#" && tokens[1] == "line") {
433 line_index = 2;
434 } else if (tokens[0] == "#line") {
435 line_index = 1;
436 }
437 }
438 if (0 == line_index) return false;
439 *linenumber = std::stoul(tokens[line_index]);
440 uint32_t filename_index = line_index + 1;
441 // Remove enclosing double quotes around filename
442 if (size > filename_index) filename = tokens[filename_index].substr(1, tokens[filename_index].size() - 2);
443 return true;
444}
445#else
446bool GetLineAndFilename(const std::string string, uint32_t *linenumber, std::string &filename) {
447 static const std::regex line_regex( // matches #line directives
448 "^" // beginning of line
449 "\\s*" // optional whitespace
450 "#" // required text
451 "\\s*" // optional whitespace
452 "line" // required text
453 "\\s+" // required whitespace
454 "([0-9]+)" // required first capture - line number
455 "(\\s+)?" // optional second capture - whitespace
456 "(\".+\")?" // optional third capture - quoted filename with at least one char inside
457 ".*"); // rest of line (needed when using std::regex_match since the entire line is tested)
458
459 std::smatch captures;
460
461 bool found_line = std::regex_match(string, captures, line_regex);
462 if (!found_line) return false;
463
464 // filename is optional and considered found only if the whitespace and the filename are captured
465 if (captures[2].matched && captures[3].matched) {
466 // Remove enclosing double quotes. The regex guarantees the quotes and at least one char.
467 filename = captures[3].str().substr(1, captures[3].str().size() - 2);
468 }
469 *linenumber = std::stoul(captures[1]);
470 return true;
471}
472#endif // GCC_VERSION
473
474// Extract the filename, line number, and column number from the correct OpLine and build a message string from it.
475// 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 -0700476void UtilGenerateSourceMessages(const std::vector<unsigned int> &pgm, const uint32_t *debug_record, bool from_printf,
477 std::string &filename_msg, std::string &source_msg) {
Tony-LunarG1dce2392019-10-23 16:49:29 -0600478 using namespace spvtools;
479 std::ostringstream filename_stream;
480 std::ostringstream source_stream;
481 SHADER_MODULE_STATE shader;
482 shader.words = pgm;
483 // Find the OpLine just before the failing instruction indicated by the debug info.
484 // SPIR-V can only be iterated in the forward direction due to its opcode/length encoding.
485 uint32_t instruction_index = 0;
486 uint32_t reported_file_id = 0;
487 uint32_t reported_line_number = 0;
488 uint32_t reported_column_number = 0;
489 if (shader.words.size() > 0) {
490 for (auto insn : shader) {
491 if (insn.opcode() == spv::OpLine) {
492 reported_file_id = insn.word(1);
493 reported_line_number = insn.word(2);
494 reported_column_number = insn.word(3);
495 }
496 if (instruction_index == debug_record[kInstCommonOutInstructionIdx]) {
497 break;
498 }
499 instruction_index++;
500 }
501 }
502 // Create message with file information obtained from the OpString pointed to by the discovered OpLine.
503 std::string reported_filename;
504 if (reported_file_id == 0) {
505 filename_stream
506 << "Unable to find SPIR-V OpLine for source information. Build shader with debug info to get source information.";
507 } else {
508 bool found_opstring = false;
509 std::string prefix;
510 if (from_printf)
511 prefix = "Debug shader printf message generated ";
512 else
513 prefix = "Shader validation error occurred ";
514 for (auto insn : shader) {
515 if ((insn.opcode() == spv::OpString) && (insn.len() >= 3) && (insn.word(1) == reported_file_id)) {
516 found_opstring = true;
517 reported_filename = (char *)&insn.word(2);
518 if (reported_filename.empty()) {
519 filename_stream << prefix << "at line " << reported_line_number;
520 } else {
521 filename_stream << prefix << "in file " << reported_filename << " at line " << reported_line_number;
522 }
523 if (reported_column_number > 0) {
524 filename_stream << ", column " << reported_column_number;
525 }
526 filename_stream << ".";
527 break;
528 }
529 }
530 if (!found_opstring) {
531 filename_stream << "Unable to find SPIR-V OpString for file id " << reported_file_id << " from OpLine instruction.";
532 }
533 }
534 filename_msg = filename_stream.str();
535
536 // Create message to display source code line containing error.
537 if ((reported_file_id != 0)) {
538 // Read the source code and split it up into separate lines.
539 std::vector<std::string> opsource_lines;
540 ReadOpSource(shader, reported_file_id, opsource_lines);
541 // Find the line in the OpSource content that corresponds to the reported error file and line.
542 if (!opsource_lines.empty()) {
543 uint32_t saved_line_number = 0;
544 std::string current_filename = reported_filename; // current "preprocessor" filename state.
545 std::vector<std::string>::size_type saved_opsource_offset = 0;
546 bool found_best_line = false;
547 for (auto it = opsource_lines.begin(); it != opsource_lines.end(); ++it) {
548 uint32_t parsed_line_number;
549 std::string parsed_filename;
550 bool found_line = GetLineAndFilename(*it, &parsed_line_number, parsed_filename);
551 if (!found_line) continue;
552
553 bool found_filename = parsed_filename.size() > 0;
554 if (found_filename) {
555 current_filename = parsed_filename;
556 }
557 if ((!found_filename) || (current_filename == reported_filename)) {
558 // Update the candidate best line directive, if the current one is prior and closer to the reported line
559 if (reported_line_number >= parsed_line_number) {
560 if (!found_best_line ||
561 (reported_line_number - parsed_line_number <= reported_line_number - saved_line_number)) {
562 saved_line_number = parsed_line_number;
563 saved_opsource_offset = std::distance(opsource_lines.begin(), it);
564 found_best_line = true;
565 }
566 }
567 }
568 }
569 if (found_best_line) {
570 assert(reported_line_number >= saved_line_number);
571 std::vector<std::string>::size_type opsource_index =
572 (reported_line_number - saved_line_number) + 1 + saved_opsource_offset;
573 if (opsource_index < opsource_lines.size()) {
574 source_stream << "\n" << reported_line_number << ": " << opsource_lines[opsource_index].c_str();
575 } else {
576 source_stream << "Internal error: calculated source line of " << opsource_index << " for source size of "
577 << opsource_lines.size() << " lines.";
578 }
579 } else {
580 source_stream << "Unable to find suitable #line directive in SPIR-V OpSource.";
581 }
582 } else {
583 source_stream << "Unable to find SPIR-V OpSource.";
584 }
585 }
586 source_msg = source_stream.str();
587}