diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index 782603557..223e69030 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -2965,6 +2965,7 @@ struct RecordedDispatch { DispatchTimer* timer; // Whether the data refresh recorded anything. bool refreshed = false; + bool resourceKeyMatched = false; }; VkDevice VulkanDevice::Device() const { @@ -3284,7 +3285,7 @@ void VulkanDevice::recordDispatch(RecordedDispatch& record) { // after an earlier dispatch's reads of the buffers by that dispatch's trailing barrier. A // recipe compares the two 64-bit hashes first: equal hashes mean the buffers hold the words. const bool differs = record.dataRefresh == RecordedDispatch::DataRefresh::Words || resources.DataWordsHash() != record.dataWordsHash; - if (differs && resources.RefreshData(commands, *record.shader, &recorder)) { + if (differs && (record.resourceKeyMatched ? resources.refreshData(commands, *record.shader, &recorder) : resources.RefreshData(commands, *record.shader, &recorder))) { covered = 0; ++d.templateRefreshed; d.templateRevalidateMs += record.revalidateMs; @@ -3577,6 +3578,7 @@ VulkanDevice::IndirectOutcome VulkanDevice::dispatch(const ShaderRecompiler::Rec auto& recorder = *state->recorder; IndirectOutcome outcome{0, 0}; RecordedDispatch record{&context, &shaders[0], resources, objects, pushStages, &pushBytes, x, y, z, arguments, nullptr, programAddress, fromCache && TemplateDataRefresh() ? RecordedDispatch::DataRefresh::Words : RecordedDispatch::DataRefresh::None, 0, revalidateMs, &timer}; + record.resourceKeyMatched = fromCache; if (arguments != 0) decideIndirect(record, outcome, groupsText); // The indirect hold total below still covers the whole call of a CPU-resolved one. const bool indirect = record.arguments != 0 || outcome.cpuReason != 0; @@ -3747,6 +3749,7 @@ RecipeOutcome VulkanDevice::DispatchRecipe(const ShaderRecompiler::RecompileResu const auto dataRefresh = !TemplateDataRefresh() ? RecordedDispatch::DataRefresh::None : refreshByWords ? RecordedDispatch::DataRefresh::Words : RecordedDispatch::DataRefresh::Hash; if (dataRefresh == RecordedDispatch::DataRefresh::Words) counters.refreshByWords.fetch_add(1, std::memory_order_relaxed); RecordedDispatch record{&context, &shaders[0], hit->resources, hit->objects, recipe.pushes ? VkShaderStageFlags{VK_SHADER_STAGE_COMPUTE_BIT} : VkShaderStageFlags{0}, &recipe.pushBytes, x, y, z, arguments, nullptr, programAddress, dataRefresh, recipe.dataWordsHash, 0, &timer}; + record.resourceKeyMatched = verify != nullptr; if (arguments != 0) decideIndirect(record, outcome, groupsText); const bool indirect = record.arguments != 0 || outcome.cpuReason != 0; const auto recordStart = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp index f645cca16..f782f7094 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp @@ -18,6 +18,8 @@ #include #include +namespace AgcDriver { class VulkanDevice; } + namespace AgcDriver::Graphics { class Recorder; @@ -227,6 +229,8 @@ public: std::vector> PresyncSurfaces() const; private: + friend class AgcDriver::VulkanDevice; + bool refreshData(VkCommandBuffer commands, const CompiledShader& shader, Recorder* recorder); struct DescribedRange { const char* kind; std::uint64_t address; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 524bb3dac..d49f26a64 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -888,7 +888,27 @@ double ShaderResources::phase(BuildPhase which) { namespace { -void ValidateRuntimeResources(const CompiledShader& shader) { +void ValidateDescriptorLayout(const Context& context, std::span bindings) { + std::map heapTotals; + std::map, std::uint64_t> stageTotals; + std::map stageResources; + for (const auto& layout : bindings) { + heapTotals[layout.descriptorType] += layout.descriptorCount; + for (std::uint32_t bit = 0u; bit < 32u; ++bit) { + const auto stage = VkShaderStageFlags{1u} << bit; + if ((layout.stageFlags & stage) == 0u) continue; + const auto count = stageTotals[{stage, layout.descriptorType}] += layout.descriptorCount; + const auto all = stageResources[stage] += layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER ? 0u : layout.descriptorCount; + Require(all <= context.limits.maxPerStageResources, "typed heaps exceed per-stage resource capacity"); + if (layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) Require(count <= context.limits.maxPerStageDescriptorSampledImages, "typed heaps exceed per-stage sampled image capacity"); + if (layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) Require(count <= context.limits.maxPerStageDescriptorStorageImages, "typed heaps exceed per-stage storage image capacity"); + if (layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) Require(count <= context.limits.maxPerStageDescriptorSamplers, "typed heaps exceed per-stage sampler capacity"); + } + } + Require(heapTotals[VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE] <= context.limits.maxDescriptorSetSampledImages && heapTotals[VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] <= context.limits.maxDescriptorSetStorageImages && heapTotals[VK_DESCRIPTOR_TYPE_SAMPLER] <= context.limits.maxDescriptorSetSamplers, "typed heaps exceed descriptor set capacity"); +} + +void ValidateRuntimeResources(const CompiledShader& shader, std::span words) { Require(shader.program != nullptr, "missing compiled shader"); const auto& program = *shader.program; const auto& descriptors = program.bindings; @@ -902,22 +922,18 @@ void ValidateRuntimeResources(const CompiledShader& shader) { heap = &binding; } } - for (const auto& binding : descriptors) { - if (binding.role != ShaderRecompiler::DescriptorRole::ShaderData) continue; - Require(binding.guestDescriptor.size() == program.shaderDataDwords, "invalid compact shader data size"); - const auto words = std::span(binding.guestDescriptor); - constexpr auto metadataWords = sizeof(ShaderRecompiler::RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t); - Require(program.imageMetadataDword <= words.size() && program.runtimeImageCount <= (words.size() - program.imageMetadataDword) / metadataWords, "runtime image metadata exceeds shader data"); - for (const auto index : program.runtimeImageResources) { - Require(index < program.runtimeImageCount, "runtime image resource exceeds its compact layout"); - const auto offset = program.imageMetadataDword + index * metadataWords; - const auto kind = words[offset]; - const auto first = words[offset + 1u]; - const auto count = words[offset + 2u]; - Require(count != 0u, "runtime image metadata has no descriptor elements"); - Require(kind < heaps.size() && heaps[kind] != nullptr, "runtime metadata references an unbound image heap"); - Require(first < heaps[kind]->count && count <= heaps[kind]->count - first, "runtime metadata exceeds its bound heap"); - } + Require(words.size() == program.shaderDataDwords, "invalid compact shader data size"); + constexpr auto metadataWords = sizeof(ShaderRecompiler::RuntimeAbi::ResourceMetadata) / sizeof(std::uint32_t); + Require(program.imageMetadataDword <= words.size() && program.runtimeImageCount <= (words.size() - program.imageMetadataDword) / metadataWords, "runtime image metadata exceeds shader data"); + for (const auto index : program.runtimeImageResources) { + Require(index < program.runtimeImageCount, "runtime image resource exceeds its compact layout"); + const auto offset = program.imageMetadataDword + index * metadataWords; + const auto kind = words[offset]; + const auto first = words[offset + 1u]; + const auto count = words[offset + 2u]; + Require(count != 0u, "runtime image metadata has no descriptor elements"); + Require(kind < heaps.size() && heaps[kind] != nullptr, "runtime metadata references an unbound image heap"); + Require(first < heaps[kind]->count && count <= heaps[kind]->count - first, "runtime metadata exceeds its bound heap"); } } @@ -997,14 +1013,13 @@ void ShaderResources::buildPrepare(std::span shaders, cons Require(binding.count == 1, "shader data and flattened SRT descriptors must not be arrays"); Require(!binding.guestDescriptor.empty(), "empty shader data descriptor"); if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) { - Require(binding.guestDescriptor.size() == shader.program->shaderDataDwords, "shader data does not match the compact runtime layout"); + ValidateRuntimeResources(shader, binding.guestDescriptor); } item.allocations.push_back(addDataBuffer(binding.guestDescriptor)); if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) shaderData = static_cast(item.allocations.back()); } bindings.push_back(std::move(item)); } - ValidateRuntimeResources(shader); for (const auto index : offsetsInData) allocations[index].dataAllocation = shaderData; for (auto index = firstDeferred; index < deferredImages.size(); ++index) { deferredImages[index].firstSampler = firstSampler; @@ -1012,24 +1027,6 @@ void ShaderResources::buildPrepare(std::span shaders, cons } } Require(storageBuffers <= context.limits.maxDescriptorSetStorageBuffers, "pipeline descriptors exceed device limits"); - std::map heapTotals; - std::map, std::uint64_t> stageTotals; - std::map stageResources; - for (const auto& binding : bindings) { - const auto& layout = binding.layout; - heapTotals[layout.descriptorType] += layout.descriptorCount; - for (std::uint32_t bit = 0u; bit < 32u; ++bit) { - const auto stage = VkShaderStageFlags{1u} << bit; - if ((layout.stageFlags & stage) == 0u) continue; - const auto count = stageTotals[{stage, layout.descriptorType}] += layout.descriptorCount; - const auto all = stageResources[stage] += layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER ? 0u : layout.descriptorCount; - Require(all <= context.limits.maxPerStageResources, "typed heaps exceed per-stage resource capacity"); - if (layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) Require(count <= context.limits.maxPerStageDescriptorSampledImages, "typed heaps exceed per-stage sampled image capacity"); - if (layout.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) Require(count <= context.limits.maxPerStageDescriptorStorageImages, "typed heaps exceed per-stage storage image capacity"); - if (layout.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) Require(count <= context.limits.maxPerStageDescriptorSamplers, "typed heaps exceed per-stage sampler capacity"); - } - } - Require(heapTotals[VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE] <= context.limits.maxDescriptorSetSampledImages && heapTotals[VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] <= context.limits.maxDescriptorSetStorageImages && heapTotals[VK_DESCRIPTOR_TYPE_SAMPLER] <= context.limits.maxDescriptorSetSamplers, "typed heaps exceed descriptor set capacity"); timing.bindingsMs = phase(BuildPhase::Bindings); // For every build, locked ones included: their stage B then takes the fast path too, and the // collects cost the same wherever they run. @@ -1046,6 +1043,7 @@ void ShaderResources::buildPrepare(std::span shaders, cons if (context.descriptorCache != nullptr && !noLayoutCache) { _layout = context.descriptorCache->Layout(layoutKey, description); } else { + ValidateDescriptorLayout(context, description); VkDescriptorSetLayoutCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; info.bindingCount = static_cast(description.size()); info.pBindings = description.data(); @@ -2209,6 +2207,7 @@ VkDescriptorSetLayout DescriptorCache::Layout(std::span key ++stats.layoutHits; return found->second; } + ValidateDescriptorLayout(context, bindings); ++stats.layoutMisses; VkDescriptorSetLayoutCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; info.bindingCount = static_cast(bindings.size()); @@ -2452,6 +2451,11 @@ bool ShaderResources::DataWordsDiffer(const CompiledShader& shader) const { bool ShaderResources::RefreshData(VkCommandBuffer commands, const CompiledShader& shader, Recorder* recorder) { Require(shader.program != nullptr, "missing compiled shader"); Require(!refreshResourceKey.empty() && MatchesContentKey(shader, refreshResourceKey), "runtime data refresh cannot replace bound resources"); + return refreshData(commands, shader, recorder); +} + +bool ShaderResources::refreshData(VkCommandBuffer commands, const CompiledShader& shader, Recorder* recorder) { + Require(shader.program != nullptr, "missing compiled shader"); const auto& program = *shader.program; Require(program.bindings.size() == bindings.size(), "template bindings disagree with the shader"); bool recorded = false; @@ -2467,7 +2471,7 @@ bool ShaderResources::RefreshData(VkCommandBuffer commands, const CompiledShader const auto size = binding.guestDescriptor.size() * sizeof(std::uint32_t); Require(allocation.buffer != nullptr && !allocation.guest && allocation.size == size && size <= MaxRefreshBytes, "template data buffer cannot take the dispatch's words"); if (allocation.dataWords.size() == binding.guestDescriptor.size() && std::equal(allocation.dataWords.begin(), allocation.dataWords.end(), binding.guestDescriptor.begin())) continue; - if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader); + if (binding.role == ShaderRecompiler::DescriptorRole::ShaderData) ValidateRuntimeResources(shader, binding.guestDescriptor); if (recorder != nullptr && timing == Recorder::NoTiming) timing = recorder->BeginGpuTiming(Recorder::CommandClass::TemplateDataRefresh); writeDataWords(commands, bindings[index].allocations.front(), binding.guestDescriptor); allocation.dataWords.assign(binding.guestDescriptor.begin(), binding.guestDescriptor.end()); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp index aba4a7ab4..1e0447560 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderDiskCache.cpp @@ -792,6 +792,8 @@ void verifyBuiltinSpecialization() { emit(spv::OpConstant, {3u, 8u, 2u}); emit(spv::OpConstant, {3u, 9u, 3u}); emit(spv::OpConstantComposite, {4u, 30u, 6u, 7u, 8u, 9u}); + emit(spv::OpTypePointer, {32u, spv::StorageClassPrivate, 4u}); + emit(spv::OpVariable, {32u, 31u, spv::StorageClassPrivate}); emit(spv::OpFunction, {1u, 10u, spv::FunctionControlMaskNone, 5u}); emit(spv::OpLabel, {11u}); emit(spv::OpBitFieldUExtract, {3u, 12u, 9u, 7u, 7u}); @@ -813,6 +815,7 @@ void verifyBuiltinSpecialization() { emit(spv::OpVectorExtractDynamic, {3u, 25u, 30u, 8u}); emit(spv::OpVectorExtractDynamic, {3u, 26u, 30u, 9u}); emit(spv::OpCompositeConstruct, {4u, 27u, 23u, 24u, 25u, 26u}); + emit(spv::OpStore, {31u, 27u}); emit(spv::OpBranch, {22u}); emit(spv::OpLabel, {21u}); emit(spv::OpUnreachable, {}); @@ -827,7 +830,7 @@ void verifyBuiltinSpecialization() { require(count != 0u && count <= specialized.size() - cursor, "builtin specialization produced a truncated instruction"); const auto op = static_cast(specialized[cursor] & 0xffffu); require(op != spv::OpSwitch && op != spv::OpBranchConditional && op != spv::OpPhi && op != spv::OpVectorExtractDynamic, "builtin specialization retained constant control flow or dynamic exports"); - if (op == spv::OpCopyObject && specialized[cursor + 2u] == 27u) identity = specialized[cursor + 3u] == 30u; + if (op == spv::OpStore && specialized[cursor + 1u] == 31u) identity = specialized[cursor + 2u] == 30u; if (op == spv::OpConstant && specialized[cursor + 2u] == 18u) correctPhi = specialized[cursor + 3u] == 1u; cursor += count; } @@ -835,6 +838,66 @@ void verifyBuiltinSpecialization() { require(SpecializeSpirv(specialized) == specialized, "builtin specialization is not stable"); } +void verifySpecializationLiveness() { + std::vector words{spv::MagicNumber, 0x00010300u, 0u, 64u, 0u}; + const auto emit = [&](spv::Op op, std::initializer_list operands) { + words.push_back((static_cast(operands.size() + 1u) << 16u) | op); + words.insert(words.end(), operands); + }; + emit(spv::OpCapability, {spv::CapabilityShader}); + emit(spv::OpMemoryModel, {spv::AddressingModelLogical, spv::MemoryModelGLSL450}); + emit(spv::OpEntryPoint, {spv::ExecutionModelGLCompute, 10u, 0x6e69616du, 0u}); + emit(spv::OpExecutionMode, {10u, spv::ExecutionModeLocalSize, 1u, 1u, 1u}); + emit(spv::OpDecorate, {27u, spv::DecorationRelaxedPrecision}); + emit(spv::OpTypeVoid, {1u}); + emit(spv::OpTypeInt, {3u, 32u, 0u}); + emit(spv::OpTypePointer, {4u, spv::StorageClassPrivate, 3u}); + emit(spv::OpTypeFunction, {5u, 1u}); + emit(spv::OpConstant, {3u, 6u, 0u}); + emit(spv::OpConstant, {3u, 7u, 1u}); + emit(spv::OpTypeStruct, {24u, 3u, 3u, 3u, 3u, 3u, 3u, 3u, 3u, 3u, 3u, 3u, 3u, 3u, 3u, 3u, 3u}); + emit(spv::OpConstantComposite, {24u, 25u, 7u, 7u, 7u, 7u, 7u, 7u, 7u, 7u, 7u, 7u, 7u, 7u, 7u, 7u, 7u, 7u}); + emit(spv::OpVariable, {4u, 8u, spv::StorageClassPrivate, 6u}); + emit(spv::OpFunction, {1u, 10u, spv::FunctionControlMaskNone, 5u}); + emit(spv::OpLabel, {11u}); + emit(spv::OpLoad, {3u, 12u, 8u}); + emit(spv::OpIMul, {3u, 13u, 12u, 7u}); + emit(spv::OpIAdd, {3u, 14u, 13u, 7u}); + emit(spv::OpCopyObject, {3u, 15u, 12u}); + emit(spv::OpCopyObject, {3u, 16u, 15u}); + emit(spv::OpIAdd, {3u, 17u, 16u, 7u}); + emit(spv::OpStore, {8u, 17u}); + emit(spv::OpLoad, {3u, 18u, 8u, spv::MemoryAccessVolatileMask}); + emit(spv::OpFunctionCall, {1u, 20u, 30u}); + emit(spv::OpCompositeExtract, {3u, 26u, 25u, 15u}); + emit(spv::OpStore, {8u, 26u}); + emit(spv::OpCopyObject, {3u, 27u, 12u}); + emit(spv::OpStore, {8u, 27u}); + emit(spv::OpLoad, {3u, 28u, 8u}); + emit(spv::OpReturn, {}); + emit(spv::OpFunctionEnd, {}); + emit(spv::OpFunction, {1u, 30u, spv::FunctionControlMaskNone, 5u}); + emit(spv::OpLabel, {31u}); + emit(spv::OpReturn, {}); + emit(spv::OpFunctionEnd, {}); + const auto specialized = SpecializeSpirv(words); + std::map> results; + std::size_t stores = 0; + for (std::size_t cursor = 5; cursor < specialized.size();) { + const auto count = specialized[cursor] >> 16u; + const auto op = static_cast(specialized[cursor] & 0xffffu); + require(count != 0u && count <= specialized.size() - cursor, "dead computation removal truncated an instruction"); + if (op == spv::OpLoad || op == spv::OpCopyObject || op == spv::OpIAdd || op == spv::OpIMul || op == spv::OpCompositeExtract || op == spv::OpFunctionCall) results.emplace(specialized[cursor + 2u], std::vector(specialized.begin() + cursor, specialized.begin() + cursor + count)); + if (op == spv::OpStore) ++stores; + cursor += count; + } + for (const auto id : {13u, 14u, 15u, 16u, 28u}) require(!results.contains(id), "specialization retained a dead computation or copy chain"); + require(results.at(17u).at(3) == 12u, "copy propagation lost the live source"); + require(results.at(26u).at(4) == 15u, "copy propagation rewrote a literal as an ID"); + require(results.contains(18u) && results.contains(20u) && results.contains(27u) && stores == 3u, "specialization removed an effect or decorated copy"); + require(SpecializeSpirv(specialized) == specialized, "dead computation removal is not stable"); +} + void verifyDefaultDirectory(const char* self) { setEnvironment("ANYPS5_SHADER_CACHE_DIR", ""); setEnvironment("ANYPS5_NO_SHADER_CACHE", "1"); @@ -869,6 +932,7 @@ int main(int argc, char** argv) { verifyBindingPlanSelection(); verifyVertexTypeSpecialization(); verifyBuiltinSpecialization(); + verifySpecializationLiveness(); std::error_code error; std::filesystem::remove_all(directory, error); std::cout << "shader disk cache tests passed\n"; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvSpecialization.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvSpecialization.cpp index 239b84190..8301bb05e 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvSpecialization.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvSpecialization.cpp @@ -33,6 +33,193 @@ Instruction Make(spv::Op op, std::initializer_list operands) { return result; } +bool PureInstruction(const Instruction& instruction) { + switch (Opcode(instruction)) { + case spv::OpVectorExtractDynamic: + case spv::OpVectorInsertDynamic: + case spv::OpVectorShuffle: + case spv::OpCompositeConstruct: + case spv::OpCompositeExtract: + case spv::OpCompositeInsert: + case spv::OpCopyObject: + case spv::OpTranspose: + case spv::OpConvertFToU: + case spv::OpConvertFToS: + case spv::OpConvertSToF: + case spv::OpConvertUToF: + case spv::OpUConvert: + case spv::OpSConvert: + case spv::OpFConvert: + case spv::OpQuantizeToF16: + case spv::OpConvertPtrToU: + case spv::OpSatConvertSToU: + case spv::OpSatConvertUToS: + case spv::OpConvertUToPtr: + case spv::OpPtrCastToGeneric: + case spv::OpGenericCastToPtr: + case spv::OpGenericCastToPtrExplicit: + case spv::OpBitcast: + case spv::OpSNegate: + case spv::OpFNegate: + case spv::OpIAdd: + case spv::OpFAdd: + case spv::OpISub: + case spv::OpFSub: + case spv::OpIMul: + case spv::OpFMul: + case spv::OpUDiv: + case spv::OpSDiv: + case spv::OpFDiv: + case spv::OpUMod: + case spv::OpSRem: + case spv::OpSMod: + case spv::OpFRem: + case spv::OpFMod: + case spv::OpVectorTimesScalar: + case spv::OpMatrixTimesScalar: + case spv::OpVectorTimesMatrix: + case spv::OpMatrixTimesVector: + case spv::OpMatrixTimesMatrix: + case spv::OpOuterProduct: + case spv::OpDot: + case spv::OpIAddCarry: + case spv::OpISubBorrow: + case spv::OpUMulExtended: + case spv::OpSMulExtended: + case spv::OpAny: + case spv::OpAll: + case spv::OpIsNan: + case spv::OpIsInf: + case spv::OpIsFinite: + case spv::OpIsNormal: + case spv::OpSignBitSet: + case spv::OpLessOrGreater: + case spv::OpOrdered: + case spv::OpUnordered: + case spv::OpLogicalEqual: + case spv::OpLogicalNotEqual: + case spv::OpLogicalOr: + case spv::OpLogicalAnd: + case spv::OpLogicalNot: + case spv::OpSelect: + case spv::OpIEqual: + case spv::OpINotEqual: + case spv::OpUGreaterThan: + case spv::OpSGreaterThan: + case spv::OpUGreaterThanEqual: + case spv::OpSGreaterThanEqual: + case spv::OpULessThan: + case spv::OpSLessThan: + case spv::OpULessThanEqual: + case spv::OpSLessThanEqual: + case spv::OpFOrdEqual: + case spv::OpFUnordEqual: + case spv::OpFOrdNotEqual: + case spv::OpFUnordNotEqual: + case spv::OpFOrdLessThan: + case spv::OpFUnordLessThan: + case spv::OpFOrdGreaterThan: + case spv::OpFUnordGreaterThan: + case spv::OpFOrdLessThanEqual: + case spv::OpFUnordLessThanEqual: + case spv::OpFOrdGreaterThanEqual: + case spv::OpFUnordGreaterThanEqual: + case spv::OpShiftRightLogical: + case spv::OpShiftRightArithmetic: + case spv::OpShiftLeftLogical: + case spv::OpBitwiseOr: + case spv::OpBitwiseXor: + case spv::OpBitwiseAnd: + case spv::OpNot: + case spv::OpBitFieldInsert: + case spv::OpBitFieldSExtract: + case spv::OpBitFieldUExtract: + case spv::OpBitReverse: + case spv::OpBitCount: + case spv::OpDPdx: + case spv::OpDPdy: + case spv::OpFwidth: + case spv::OpDPdxFine: + case spv::OpDPdyFine: + case spv::OpFwidthFine: + case spv::OpDPdxCoarse: + case spv::OpDPdyCoarse: + case spv::OpFwidthCoarse: + case spv::OpAccessChain: + case spv::OpInBoundsAccessChain: + case spv::OpPtrAccessChain: + case spv::OpInBoundsPtrAccessChain: + case spv::OpArrayLength: + case spv::OpPhi: + return true; + case spv::OpLoad: + return instruction.size() == 4u || (instruction.size() == 5u && instruction[4] == spv::MemoryAccessMaskNone); + default: + return false; + } +} + +template +bool VisitInputs(const Instruction& instruction, const TVisitor& visit) { + std::size_t first = 3u; + std::size_t end = instruction.size(); + switch (Opcode(instruction)) { + case spv::OpVectorShuffle: + case spv::OpCompositeInsert: + end = 5u; + break; + case spv::OpCompositeExtract: + case spv::OpGenericCastToPtrExplicit: + case spv::OpArrayLength: + end = 4u; + break; + case spv::OpLoad: + if (instruction.size() > 5u) return false; + end = 4u; + break; + case spv::OpStore: + if (instruction.size() > 4u) return false; + first = 1u; + end = 3u; + break; + case spv::OpBranch: + case spv::OpReturnValue: + first = 1u; + end = 2u; + break; + case spv::OpBranchConditional: + first = 1u; + end = 4u; + break; + case spv::OpSelectionMerge: + first = 1u; + end = 2u; + break; + case spv::OpLoopMerge: + first = 1u; + end = 3u; + break; + case spv::OpFunctionCall: + break; + case spv::OpReturn: + case spv::OpUnreachable: + case spv::OpKill: + case spv::OpLabel: + case spv::OpFunction: + case spv::OpFunctionEnd: + case spv::OpFunctionParameter: + case spv::OpLine: + case spv::OpNoLine: + return true; + default: + if (!PureInstruction(instruction)) return false; + break; + } + if (end > instruction.size()) throw std::runtime_error("truncated prepared instruction operands"); + for (auto index = first; index < end; ++index) visit(index); + return true; +} + struct ScalarType { std::uint32_t width; bool boolean; @@ -66,8 +253,9 @@ public: while (changed) { changed = fold(); changed |= prune(); + changed |= propagateCopies(); } - removeUnusedExtracts(); + removeDeadComputations(); orderPhis(); std::vector words = header; bool inserted = false; @@ -305,22 +493,91 @@ private: instructions = std::move(ordered); } - void removeUnusedExtracts() { - std::set referenced; + bool propagateCopies() { + std::map copies; + for (const auto& instruction : instructions) { + if (Opcode(instruction) != spv::OpCopyObject) continue; + if (instruction.size() != 4u) throw std::runtime_error("invalid prepared copy instruction"); + copies.emplace(instruction[2], instruction[3]); + } + if (copies.empty()) return false; for (const auto& instruction : instructions) { if (instruction.empty()) continue; const auto op = Opcode(instruction); - if (op == spv::OpName || op == spv::OpDecorate) continue; + if (op == spv::OpName || op == spv::OpMemberName) continue; + if (VisitInputs(instruction, [](std::size_t) {})) continue; bool hasResult = false; bool hasType = false; spv::HasResultAndType(op, &hasResult, &hasType); const auto resultIndex = hasResult ? (hasType ? 2u : 1u) : 0u; - for (std::size_t index = 1; index < instruction.size(); ++index) if (index != resultIndex) referenced.insert(instruction[index]); + for (std::size_t index = 1; index < instruction.size(); ++index) if (index != resultIndex) copies.erase(instruction[index]); } + if (copies.empty()) return false; + const auto resolve = [&](std::uint32_t id) { + std::size_t count = 0; + while (copies.contains(id)) { + if (++count > copies.size()) throw std::runtime_error("cyclic prepared copy chain"); + id = copies.at(id); + } + return id; + }; + bool function = false; for (auto& instruction : instructions) { - if (Opcode(instruction) != spv::OpCompositeExtract || referenced.contains(Result(instruction))) continue; - removed.insert(Result(instruction)); - instruction.clear(); + if (instruction.empty()) continue; + const auto op = Opcode(instruction); + if (op == spv::OpFunction) function = true; + if (op == spv::OpFunctionEnd) function = false; + if (!function) continue; + if (op == spv::OpCopyObject && copies.contains(instruction[2])) { + removed.insert(instruction[2]); + instruction.clear(); + continue; + } + VisitInputs(instruction, [&](std::size_t index) { instruction[index] = resolve(instruction[index]); }); + } + return true; + } + + void removeDeadComputations() { + std::map definitions; + std::vector pending; + bool function = false; + for (std::size_t index = 0; index < instructions.size(); ++index) { + const auto& instruction = instructions[index]; + if (instruction.empty()) continue; + const auto op = Opcode(instruction); + if (op == spv::OpFunction) function = true; + if (op == spv::OpFunctionEnd) function = false; + if (!function) { + if (op == spv::OpDecorateId || op == spv::OpGroupDecorate || op == spv::OpGroupMemberDecorate) { + for (std::size_t operand = 1; operand < instruction.size(); ++operand) pending.push_back(instruction[operand]); + } + continue; + } + if (PureInstruction(instruction)) { + definitions.emplace(Result(instruction), index); + continue; + } + if (VisitInputs(instruction, [&](std::size_t operand) { pending.push_back(instruction[operand]); })) continue; + bool hasResult = false; + bool hasType = false; + spv::HasResultAndType(op, &hasResult, &hasType); + const auto resultIndex = hasResult ? (hasType ? 2u : 1u) : 0u; + for (std::size_t operand = 1; operand < instruction.size(); ++operand) if (operand != resultIndex) pending.push_back(instruction[operand]); + } + std::set live; + while (!pending.empty()) { + const auto id = pending.back(); + pending.pop_back(); + const auto found = definitions.find(id); + if (found == definitions.end() || !live.insert(id).second) continue; + const auto& instruction = instructions[found->second]; + if (!VisitInputs(instruction, [&](std::size_t operand) { pending.push_back(instruction[operand]); })) throw std::runtime_error("missing prepared pure instruction operands"); + } + for (const auto& [id, index] : definitions) { + if (live.contains(id)) continue; + removed.insert(id); + instructions[index].clear(); } }