Vulkan: Disable SPIR-V preprocessing when debugging

Optimization passes are likely to damage debug information, and reorder instructions. We will likely never want to optimize shaders inside the driver when debugging.

SPIR-V tools currently has a number of issues consuming shaders that use the OpenCL.Debug.100 extension instructions which need to be fixed before these instructions can be passed to it. For now, just disable shader pre-processing when we are debugging.

Bug: b/145351270
Change-Id: I71827c2bb7cf34ecfd7e55b0ca8b3189e460b150
Reviewed-on: https://swiftshader-review.googlesource.com/c/SwiftShader/+/40130
Kokoro-Presubmit: kokoro <noreply+kokoro@google.com>
Tested-by: Ben Clayton <bclayton@google.com>
Reviewed-by: Nicolas Capens <nicolascapens@google.com>
diff --git a/src/Vulkan/VkPipeline.cpp b/src/Vulkan/VkPipeline.cpp
index a89a2bc..6134ae4 100644
--- a/src/Vulkan/VkPipeline.cpp
+++ b/src/Vulkan/VkPipeline.cpp
@@ -160,7 +160,8 @@
 // preprocessSpirv applies and freezes specializations into constants, and inlines all functions.
 std::vector<uint32_t> preprocessSpirv(
     std::vector<uint32_t> const &code,
-    VkSpecializationInfo const *specializationInfo)
+    VkSpecializationInfo const *specializationInfo,
+    bool optimize)
 {
 	spvtools::Optimizer opt{ SPV_ENV_VULKAN_1_1 };
 
@@ -192,8 +193,11 @@
 		opt.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass(specializations));
 	}
 
-	// Full optimization list taken from spirv-opt.
-	opt.RegisterPerformancePasses();
+	if(optimize)
+	{
+		// Full optimization list taken from spirv-opt.
+		opt.RegisterPerformancePasses();
+	}
 
 	std::vector<uint32_t> optimized;
 	opt.Run(code.data(), code.size(), &optimized);
@@ -218,7 +222,20 @@
     bool robustBufferAccess,
     const std::shared_ptr<vk::dbg::Context> &dbgctx)
 {
-	auto code = preprocessSpirv(key.getInsns(), key.getSpecializationInfo());
+	// Do not optimize the shader if we have a debugger context.
+	// Optimization passes are likely to damage debug information, and reorder
+	// instructions.
+	const bool optimize = !dbgctx;
+
+	// TODO(b/147726513): Do not preprocess the shader if we have a debugger
+	// context.
+	// This is a work-around for the SPIR-V tools incorrectly reporting errors
+	// when debug information is provided. This can be removed once the
+	// following SPIR-V tools bugs are fixed:
+	// https://github.com/KhronosGroup/SPIRV-Tools/issues/3102
+	// https://github.com/KhronosGroup/SPIRV-Tools/issues/3103
+	// https://github.com/KhronosGroup/SPIRV-Tools/issues/3118
+	auto code = dbgctx ? key.getInsns() : preprocessSpirv(key.getInsns(), key.getSpecializationInfo(), optimize);
 	ASSERT(code.size() > 0);
 
 	// If the pipeline has specialization constants, assume they're unique and