From f7d4fbab9a3b597aae9817cd472313649ce5225f Mon Sep 17 00:00:00 2001 From: Celegans12 <53881228+Celegans12@users.noreply.github.com> Date: Wed, 7 Oct 2026 02:22:23 +0200 Subject: [PATCH] perf(shader): share the BDA byte read fallback between read sites A BDA dword read whose span the probe rejects falls back to four byte lookups with a branch each, and every fault was recorded inline with a compare-exchange and seven stores. Both were copied into every read site and both wave64 lane halves, so one large compute program grows to about a million SPIR-V words and spends about 95 s in vkCreateComputePipelines. Faults are now recorded by one DontInline function, record_bda_fault, and the byte fallback of a dword is read_bda_dword_bytes, in a stop and a coherent variant, returning the value and whether the invocation stops. Read order, fault reasons, pcs, Volatile and the stop behaviour are unchanged, and so is the probe path. --- .../libSceAgcDriver/tests/BdaExecution.cpp | 33 +++++++++ .../prx/libSceAgcDriver/tests/BdaShader.cpp | 46 ++++++++++-- .../prx/libSceAgcDriver/tests/BdaShader.hpp | 1 + .../libSceAgcDriver/tests/ShaderMemory.cpp | 74 +++++++++++++++++++ .../include/SpirvBackend/SpirvBda.hpp | 2 + .../SpirvBackend/SpirvEmitterState.hpp | 3 + .../SpirvBackend/src/SpirvBdaFault.cpp | 32 +++++++- .../SpirvBackend/src/SpirvBdaLookup.cpp | 2 + .../SpirvBackend/src/SpirvBdaRead.cpp | 59 ++++++++++++++- 9 files changed, 240 insertions(+), 12 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaExecution.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaExecution.cpp index 4cea9514c..faf2f911c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaExecution.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaExecution.cpp @@ -130,6 +130,39 @@ void RunBdaExecutionTests(const Context& context) { run(guest, 8, 0, Abi::FaultReason::InvalidTable, 3); run(std::numeric_limits::max() - 2, 8, 0, Abi::FaultReason::Overflow, 2, 1, 4); run(1, 8, 0, Abi::FaultReason::Overflow, 2, 1, -4); + Buffer words(context, 16, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); + const auto read = [&](std::uint64_t address, std::uint32_t dwords, bool coherent, bool stops, std::uint32_t value, bool faults) { + const Abi::Header header{Abi::Version, 2, sizeof(Abi::Range), 0}; + std::memcpy(table.Bytes().data(), &header, sizeof(header)); + std::memcpy(table.Bytes().data() + sizeof(header), ranges.data(), sizeof(ranges)); + std::memset(fault.Bytes().data(), 0, fault.Bytes().size()); + const std::array sentinel{0xdeadbeef, 0xdeadbeef, 0xdeadbeef, 0xdeadbeef}; + std::memcpy(words.Bytes().data(), sentinel.data(), sizeof(sentinel)); + Pipeline pipeline(context, MakeBdaDwordReadTestShader(address, dwords, coherent, stops), {&table, &fault, &words}); + pipeline.Run(1); + Abi::Fault report{}; + std::array result{}; + std::memcpy(&report, fault.Bytes().data(), sizeof(report)); + std::memcpy(result.data(), words.Bytes().data(), sizeof(result)); + auto expected = sentinel; + if (!faults || !stops) { + expected[0] = value; + for (std::uint32_t dword = 1; dword < dwords; ++dword) expected[dword] = 0; + } + if (faults) { + Require(report.state == Abi::FaultState::Ready && report.reason == Abi::FaultReason::Unmapped && report.address == guest + 5 && report.bytes == 1 && report.instruction == 0x1234, "BDA dword read did not publish its first fault"); + } else { + Require(report.state == Abi::FaultState::Empty, "mapped BDA dword read published a fault"); + } + Require(result == expected, faults && stops ? "faulting BDA dword read continued to output a substitute value" : "BDA dword read produced incorrect data"); + }; + for (const bool stops : {true, false}) { + for (const bool coherent : {false, true}) { + read(guest + 1, 1, coherent, stops, 0x55443322, false); + read(guest + 3, 1, coherent, stops, 0x5544, true); + read(guest + 1, 4, coherent, stops, 0x55443322, true); + } + } ranges[0].permissions = 0; run(guest, 8, 0, Abi::FaultReason::Permission); } diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaShader.cpp b/core/libs/prx/libSceAgcDriver/tests/BdaShader.cpp index b05dabe90..9c4dd099d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaShader.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaShader.cpp @@ -3,11 +3,19 @@ #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" -std::vector MakeBdaTestShader(std::uint64_t address, std::uint32_t bits, std::int64_t offset) { +namespace { + +template +std::vector MakeShader(std::uint64_t address, bool coherent, bool stops, const TEmit& emit) { using namespace ShaderRecompiler; IrProgram program; program.Resources().stage = IrShaderStage::Compute; program.Info().usesDma = true; + if (coherent) { + MemoryInfo memory; + memory.coherent = true; + program.Resources().memoryInfo = {memory}; + } SpirvEmitterState state(program, {}); EmitBaseHeader(state.module, program); const auto define = [&](std::uint32_t binding) { @@ -19,6 +27,12 @@ std::vector MakeBdaTestShader(std::uint64_t address, std::uint32_ state.bdaPagetableVariable = define(0); state.faultBufferVariable = define(1); const auto output = define(2); + std::vector interfaceVariables; + if (!stops) { + interfaceVariables.push_back(state.module.DefineGlobalVariable(TypePointer(state, spv::StorageClassInput, TypeU32(state)), spv::StorageClassInput)); + state.module.AddAnnotation(spv::OpDecorate, interfaceVariables[0], spv::DecorationBuiltIn, spv::BuiltInLocalInvocationIndex); + } + state.bdaStopsInvocations = stops; DefineGetBdaPointer(state); const auto main = state.module.AllocateId(); state.module.AddFunction(spv::OpFunction, TypeVoid(state), main, spv::FunctionControlMaskNone, TypeFunction(state)); @@ -29,12 +43,34 @@ std::vector MakeBdaTestShader(std::uint64_t address, std::uint32_ flags.pc = 0x1234; instruction.SetFlags(flags); auto base = BdaConstant(state, address); - if (offset != 0) base = AddBdaAddress(ctx, instruction, base, BdaConstant(state, offset < 0 ? std::uint64_t{0} - static_cast(offset) : static_cast(offset)), offset < 0); - const auto value = EmitBdaRead(ctx, instruction, base, bits); - state.module.AddFunction(spv::OpStore, BdaWord(state, output, ConstantU32(state, 0u)), value); + if (!stops) { + const auto index = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), index, interfaceVariables[0]); + base = Binary(state, spv::OpIAdd, TypeScalarU64(state), base, Unary(state, spv::OpUConvert, TypeScalarU64(state), index)); + } + const auto values = emit(ctx, instruction, base); + for (std::uint32_t index = 0; index < values.size(); ++index) state.module.AddFunction(spv::OpStore, BdaWord(state, output, ConstantU32(state, index)), values[index]); state.module.AddFunction(spv::OpReturn); state.module.AddFunction(spv::OpFunctionEnd); state.module.AddExecutionMode(main, spv::ExecutionModeLocalSize, 1u, 1u, 1u); - state.module.EmitEntryPoint(spv::ExecutionModelGLCompute, main, "main", {}); + state.module.EmitEntryPoint(spv::ExecutionModelGLCompute, main, "main", interfaceVariables); return state.module.Finalize(); } + +} + +std::vector MakeBdaTestShader(std::uint64_t address, std::uint32_t bits, std::int64_t offset) { + using namespace ShaderRecompiler; + return MakeShader(address, false, true, [&](SpirvValueEmitContext& ctx, const IrValue& instruction, std::uint32_t base) { + if (offset != 0) base = AddBdaAddress(ctx, instruction, base, BdaConstant(ctx.state, offset < 0 ? std::uint64_t{0} - static_cast(offset) : static_cast(offset)), offset < 0); + return std::vector{EmitBdaRead(ctx, instruction, base, bits)}; + }); +} + +std::vector MakeBdaDwordReadTestShader(std::uint64_t address, std::uint32_t dwords, bool coherent, bool stops) { + using namespace ShaderRecompiler; + return MakeShader(address, coherent, stops, [&](SpirvValueEmitContext& ctx, const IrValue& instruction, std::uint32_t base) { + const auto values = EmitBdaDwordReads(ctx, instruction, base, 0u, dwords, true); + return std::vector(values.begin(), values.begin() + dwords); + }); +} diff --git a/core/libs/prx/libSceAgcDriver/tests/BdaShader.hpp b/core/libs/prx/libSceAgcDriver/tests/BdaShader.hpp index 312a64ba1..2baa4468a 100644 --- a/core/libs/prx/libSceAgcDriver/tests/BdaShader.hpp +++ b/core/libs/prx/libSceAgcDriver/tests/BdaShader.hpp @@ -6,6 +6,7 @@ #include std::vector MakeBdaTestShader(std::uint64_t address, std::uint32_t bits, std::int64_t offset = 0); +std::vector MakeBdaDwordReadTestShader(std::uint64_t address, std::uint32_t dwords, bool coherent, bool stops); void RunBdaExecutionTests(const AgcDriver::Graphics::Context& context); void RunBdaContractTests(); diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index a65c7d9e5..723598c00 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -11,6 +11,7 @@ #include "SpirvBackend/SpirvOptimizer.hpp" #endif #include "CacheKey.hpp" +#include "BdaAbi.hpp" #include #include #include @@ -893,6 +894,78 @@ void verifyTwoLaneUniformValues() { require(multiplies(32u) == oneLane, "two-lane uniform values: a two-lane invocation computes a scalar value once per lane"); } +void verifyBdaReadFallbackFunctions() { + using namespace ShaderRecompiler; + const std::array capabilities{spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess}; + const std::array extensions{"SPV_KHR_physical_storage_buffer", "SPV_KHR_8bit_storage"}; + alignas(256) static std::array output{}; + const auto outputAddress = static_cast(reinterpret_cast(output.data())); + const std::array userData{0x10000000u, 0u, 0u, 0u, static_cast(outputAddress), static_cast((outputAddress >> 32u) & 0xffffu), 128u, 0x01016facu}; + const auto compile = [&](std::uint32_t loads, bool barrier, bool coherent) { + std::vector code{0x7e020200u, 0x7e040201u}; + for (std::uint32_t load = 0; load < loads; ++load) { + code.push_back(0xdc308000u | (coherent ? 0x10000u : 0u) | (4u * load + 4u)); + code.push_back(((3u + load) << 24u) | 0x007d0001u); + } + code.push_back(0xbf8c3f70u); + for (std::uint32_t load = 1; load < loads; ++load) code.push_back(0x4a060103u | ((3u + load) << 9u)); + if (barrier) code.push_back(0xbf8a0000u); + code.insert(code.end(), {0xe0700000u, 0x80010300u, 0xbf810000u}); + RecompileRequest request{}; + request.shader = {ShaderStage::Compute, 0x50000u, code, 0, {}}; + request.context.waveSize = 32; + request.context.userDataBaseRegister = 0; + request.context.userData = userData; + request.context.compute = ShaderComputeStageInfo{{32u, 1u, 1u}, 0u, {false, false, false}, false, 1u}; + request.target.vulkanVersion = 0x00401000u; + request.target.spirvVersion = 0x00010300u; + request.target.subgroupSize = 32; + request.target.bdaAbiVersion = BdaAbi::Version; + request.target.supportedCapabilities = capabilities; + request.target.supportedExtensions = extensions; + request.target.fragmentShaderBarycentricEnabled = false; + request.layout.pushConstantSizeBytes = 128; + request.useCache = false; + return Recompile(request).spirv; + }; + for (const bool barrier : {false, true}) { + for (const bool coherent : {false, true}) { + const auto one = compile(1u, barrier, coherent); + const auto five = compile(5u, barrier, coherent); + std::map names; + std::map definitions; + const auto reader = std::string("read_bda_dword_bytes") + (barrier ? "" : "_stop") + (coherent ? "_coherent" : ""); + std::string function; + std::size_t compareExchanges = 0; + std::size_t mainLookups = 0; + std::array readerLoads{}; + for (std::size_t cursor = 5; cursor < five.size();) { + const auto length = five[cursor] >> 16u; + require(length != 0 && length <= five.size() - cursor, "BDA read functions: truncated SPIR-V instruction"); + const auto op = five[cursor] & 0xffffu; + if (op == spv::OpName) names[five[cursor + 1]] = reinterpret_cast(&five[cursor + 2]); + if (op == spv::OpFunction) { + function = names[five[cursor + 2]]; + if (function == "record_bda_fault" || function.starts_with("read_bda_dword_bytes")) { + require((five[cursor + 3] & spv::FunctionControlDontInlineMask) != 0u, "BDA read functions: a fault or byte read function may be inlined"); + ++definitions[function]; + } + } + if (op == spv::OpAtomicCompareExchange) ++compareExchanges; + if (op == spv::OpFunctionCall && function == "main" && names[five[cursor + 3]] == "get_bda_pointer") ++mainLookups; + if (op == spv::OpLoad && function == reader) ++readerLoads[length > 4u && (five[cursor + 4] & spv::MemoryAccessVolatileMask) != 0u]; + cursor += length; + } + require(definitions["record_bda_fault"] == 1u && definitions[reader] == 1u, "BDA read functions: the fault and byte read functions are not defined"); + for (const auto& [name, count] : definitions) require(count == 1u, "BDA read functions: a function is defined twice"); + require(compareExchanges == 1u, "BDA read functions: a fault is recorded outside record_bda_fault"); + require(mainLookups == 0u, "BDA read functions: a read site looks up its bytes inline"); + require(readerLoads[coherent] == 4u && readerLoads[!coherent] == 0u, "BDA read functions: the byte loads do not keep the access's coherence"); + require(five.size() - one.size() < 4u * 300u, "BDA read functions: a read site takes 300 SPIR-V words or more"); + } + } +} + void verifyFunctionLdsBound() { using namespace ShaderRecompiler; const auto build = [](const auto& body) { @@ -1048,6 +1121,7 @@ int main() { verifyComputedTexelOffsets(); verifyWaveUniformValues(); verifyTwoLaneUniformValues(); + verifyBdaReadFallbackFunctions(); verifyFunctionLdsBound(); #if ANYPS5_ENABLE_SPIRV_TOOLS const std::vector minimalSpirv{ diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvBda.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvBda.hpp index b06ea3e98..a1323899b 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvBda.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvBda.hpp @@ -13,6 +13,8 @@ std::uint32_t BdaConstant(SpirvEmitterState& state, std::uint64_t value); std::uint32_t BdaWord(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index); std::uint32_t BdaLoadWord(SpirvEmitterState& state, std::uint32_t index); std::uint32_t BdaLoadAddress(SpirvEmitterState& state, std::uint32_t index); +void DefineBdaFaultFunction(SpirvEmitterState& state); +void DefineBdaDwordReadFunctions(SpirvEmitterState& state); void RecordBdaFault(SpirvEmitterState& state, std::uint32_t address, std::uint32_t bytes, std::uint32_t instruction, BdaAbi::FaultReason reason); void ReturnBdaFailureIf(SpirvEmitterState& state, std::uint32_t condition, std::uint32_t address, std::uint32_t bytes, std::uint32_t instruction, BdaAbi::FaultReason reason); void ValidateBdaTarget(const IrProgram& program, const SpirvTargetOptions& target); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index 1e761cf73..9b6794e0d 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -105,6 +105,9 @@ struct SpirvEmitterState { std::uint32_t bdaProbeFunction = 0; std::uint32_t bdaWritePointerFunction = 0; std::uint32_t bdaNoteWriteFunction = 0; + std::uint32_t bdaFaultFunction = 0; + std::array, 2> bdaDwordReadFunctions {}; + std::uint32_t bdaStopValue = 0; // False for programs with workgroup barriers: faulting BDA accesses then continue (see BdaInvocationsMayStop). bool bdaStopsInvocations = true; // Execution scope of the barriers that keep one guest wave's LDS accesses in program order across diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp index 711619793..ad34e63e2 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaFault.cpp @@ -1,6 +1,7 @@ #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvMemory/SpirvTypes.hpp" #include "SpirvBackend/SpirvMemory/SpirvConstants.hpp" +#include namespace ShaderRecompiler { @@ -26,7 +27,21 @@ std::uint32_t BdaLoadAddress(SpirvEmitterState& state, std::uint32_t index) { return Binary(state, spv::OpBitwiseOr, TypeScalarU64(state), low, Binary(state, spv::OpShiftLeftLogical, TypeScalarU64(state), high, BdaConstant(state, 32u))); } -void RecordBdaFault(SpirvEmitterState& state, std::uint32_t address, std::uint32_t bytes, std::uint32_t instruction, BdaAbi::FaultReason reason) { +void DefineBdaFaultFunction(SpirvEmitterState& state) { + const auto u32 = TypeU32(state); + const auto u64 = TypeScalarU64(state); + state.bdaFaultFunction = state.module.AllocateId(); + state.module.AddName(state.bdaFaultFunction, "record_bda_fault"); + state.module.AddFunction(spv::OpFunction, TypeVoid(state), state.bdaFaultFunction, spv::FunctionControlDontInlineMask, state.module.Type(spv::OpTypeFunction, TypeVoid(state), u32, u64, u32, u32)); + const auto reason = state.module.AllocateId(); + const auto address = state.module.AllocateId(); + const auto bytes = state.module.AllocateId(); + const auto instruction = state.module.AllocateId(); + state.module.AddFunction(spv::OpFunctionParameter, u32, reason); + state.module.AddFunction(spv::OpFunctionParameter, u64, address); + state.module.AddFunction(spv::OpFunctionParameter, u32, bytes); + state.module.AddFunction(spv::OpFunctionParameter, u32, instruction); + EmitLabel(state, state.module.AllocateId()); const auto pointer = BdaWord(state, state.faultBufferVariable, ConstantU32(state, 0u)); const auto previous = state.module.AllocateId(); const auto scope = ConstantU32(state, spv::ScopeDevice); @@ -37,7 +52,7 @@ void RecordBdaFault(SpirvEmitterState& state, std::uint32_t address, std::uint32 const auto store = [&](std::uint32_t index, std::uint32_t value) { state.module.AddFunction(spv::OpStore, BdaWord(state, state.faultBufferVariable, ConstantU32(state, index)), value); }; - store(1, ConstantU32(state, static_cast(reason))); + store(1, reason); store(2, Unary(state, spv::OpUConvert, TypeU32(state), address)); store(3, Unary(state, spv::OpUConvert, TypeU32(state), Binary(state, spv::OpShiftRightLogical, TypeScalarU64(state), address, BdaConstant(state, 32u)))); store(4, bytes); @@ -47,6 +62,13 @@ void RecordBdaFault(SpirvEmitterState& state, std::uint32_t address, std::uint32 const auto release = ConstantU32(state, spv::MemorySemanticsReleaseMask | spv::MemorySemanticsUniformMemoryMask); state.module.AddFunction(spv::OpAtomicStore, pointer, scope, release, ConstantU32(state, static_cast(BdaAbi::FaultState::Ready))); }); + state.module.AddFunction(spv::OpReturn); + state.module.AddFunction(spv::OpFunctionEnd); +} + +void RecordBdaFault(SpirvEmitterState& state, std::uint32_t address, std::uint32_t bytes, std::uint32_t instruction, BdaAbi::FaultReason reason) { + if (state.bdaFaultFunction == 0) throw std::runtime_error("BDA fault function is missing"); + state.module.AddFunction(spv::OpFunctionCall, TypeVoid(state), state.module.AllocateId(), state.bdaFaultFunction, ConstantU32(state, static_cast(reason)), address, bytes, instruction); } void ReturnBdaFailureIf(SpirvEmitterState& state, std::uint32_t condition, std::uint32_t address, std::uint32_t bytes, std::uint32_t instruction, BdaAbi::FaultReason reason) { @@ -67,7 +89,11 @@ void StopBdaInvocationIf(SpirvEmitterState& state, std::uint32_t condition) { state.module.AddFunction(spv::OpSelectionMerge, next, spv::SelectionControlMaskNone); state.module.AddFunction(spv::OpBranchConditional, condition, failed, next); EmitLabel(state, failed); - state.module.AddFunction(state.program.Resources().stage == IrShaderStage::Pixel ? spv::OpKill : spv::OpReturn); + if (state.bdaStopValue != 0) { + state.module.AddFunction(spv::OpReturnValue, state.bdaStopValue); + } else { + state.module.AddFunction(state.program.Resources().stage == IrShaderStage::Pixel ? spv::OpKill : spv::OpReturn); + } EmitLabel(state, next); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp index f3ef2e128..98c1b24d2 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaLookup.cpp @@ -158,8 +158,10 @@ static std::uint32_t DefineBdaNoteWrite(SpirvEmitterState& state) { void DefineGetBdaPointer(SpirvEmitterState& state) { if (!state.program.Info().usesDma) return; + DefineBdaFaultFunction(state); state.bdaPointerFunction = DefineBdaLookup(state, "get_bda_pointer", true); if (!BdaByteReadsForced()) state.bdaProbeFunction = DefineBdaLookup(state, "probe_bda_pointer", false); + DefineBdaDwordReadFunctions(state); if (state.program.Info().bdaWrites) { state.bdaWritePointerFunction = DefineBdaLookup(state, "get_bda_write_pointer", true, BdaAbi::Write); state.bdaNoteWriteFunction = DefineBdaNoteWrite(state); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp index df12bfd78..db3fb5db8 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvBdaRead.cpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace ShaderRecompiler { @@ -16,10 +17,18 @@ void EmitBdaOverflowCheck(SpirvEmitterState& state, std::uint32_t address, std:: StopBdaInvocationIf(state, overflow); } -std::uint32_t BdaAccessMask(const SpirvEmitterState& state, const IrValue& inst) { +bool BdaCoherent(const SpirvEmitterState& state, const IrValue& inst) { const auto index = inst.Flags().index; const auto& memory = state.program.Resources().memoryInfo; - return spv::MemoryAccessAlignedMask | (index < memory.size() && memory[index].coherent ? spv::MemoryAccessVolatileMask : 0u); + return index < memory.size() && memory[index].coherent; +} + +std::uint32_t BdaAccessMask(bool coherent) { + return spv::MemoryAccessAlignedMask | (coherent ? spv::MemoryAccessVolatileMask : 0u); +} + +std::uint32_t BdaAccessMask(const SpirvEmitterState& state, const IrValue& inst) { + return BdaAccessMask(BdaCoherent(state, inst)); } std::uint32_t EmitBdaByte(SpirvEmitterState& state, std::uint32_t guest, std::uint32_t instruction, std::uint32_t accessMask) { @@ -100,6 +109,40 @@ std::uint32_t BdaAddressUnaligned(SpirvEmitterState& state, std::uint32_t addres } +void DefineBdaDwordReadFunctions(SpirvEmitterState& state) { + const auto u32 = TypeU32(state); + const auto u64 = TypeScalarU64(state); + const auto pair = TypeU32Vector(state, 2); + const auto type = state.module.Type(spv::OpTypeFunction, pair, u64, u32); + const auto& memory = state.program.Resources().memoryInfo; + const bool coherentAccesses = std::any_of(memory.begin(), memory.end(), [](const MemoryInfo& info) { return info.coherent; }); + const bool stops = state.bdaStopsInvocations; + if (stops) state.bdaStopValue = state.module.Constant(spv::OpConstantComposite, pair, ConstantU32(state, 0u), ConstantU32(state, 1u)); + for (const bool stop : {false, true}) { + for (const bool coherent : {false, true}) { + if ((stop && !stops) || (coherent && !coherentAccesses)) continue; + const auto function = state.module.AllocateId(); + state.module.AddName(function, std::string("read_bda_dword_bytes") + (stop ? "_stop" : "") + (coherent ? "_coherent" : "")); + state.module.AddFunction(spv::OpFunction, pair, function, spv::FunctionControlDontInlineMask, type); + const auto address = state.module.AllocateId(); + const auto instruction = state.module.AllocateId(); + state.module.AddFunction(spv::OpFunctionParameter, u64, address); + state.module.AddFunction(spv::OpFunctionParameter, u32, instruction); + EmitLabel(state, state.module.AllocateId()); + state.bdaStopsInvocations = stop; + EmitBdaOverflowCheck(state, address, 4u, instruction); + const auto value = EmitBdaBytes(state, address, 4u, instruction, BdaAccessMask(coherent)); + const auto result = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeConstruct, pair, result, value, ConstantU32(state, 0u)); + state.module.AddFunction(spv::OpReturnValue, result); + state.module.AddFunction(spv::OpFunctionEnd); + state.bdaDwordReadFunctions[stop][coherent] = function; + } + } + state.bdaStopsInvocations = stops; + state.bdaStopValue = 0; +} + // APS5_BDA_BYTE_READS=1 restores one lookup and one byte load per byte for every read. bool BdaByteReadsForced() { static const bool forced = std::getenv("APS5_BDA_BYTE_READS") != nullptr; @@ -243,11 +286,19 @@ std::array EmitBdaDwordReads(SpirvValueEmitContext& ctx, const std::array addresses{}; const auto dwordAddress = [&](std::uint32_t dword) { return AddBdaImmediate(ctx, inst, address, static_cast(offset + dword * 4u)); }; const auto readBytes = [&](std::array& into) { + const auto function = state.bdaDwordReadFunctions[state.bdaStopsInvocations][BdaCoherent(state, inst)]; + if (function == 0) ctx.Fail(inst, "BDA dword read function is missing"); for (std::uint32_t dword = first; dword <= last; ++dword) { if (!isUsed(dword)) continue; if (dword != first) addresses[dword] = dwordAddress(dword); - EmitBdaOverflowCheck(state, addresses[dword], 4u, instruction); - into[dword] = EmitBdaBytes(state, addresses[dword], 4u, instruction, BdaAccessMask(state, inst)); + const auto read = state.module.AllocateId(); + state.module.AddFunction(spv::OpFunctionCall, TypeU32Vector(state, 2), read, function, addresses[dword], instruction); + into[dword] = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), into[dword], read, 0u); + if (!state.bdaStopsInvocations) continue; + const auto stopped = state.module.AllocateId(); + state.module.AddFunction(spv::OpCompositeExtract, TypeU32(state), stopped, read, 1u); + StopBdaInvocationIf(state, Binary(state, spv::OpINotEqual, TypeBool(state), stopped, ConstantU32(state, 0u))); } }; addresses[first] = dwordAddress(first);