From cd61b53a63c0bc01ecea31c6895cc32c88e94222 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:34:13 -0500 Subject: [PATCH 01/34] feat(agc): draw PS4 LS-HS-VS tessellation through the off-chip ring lowering A GCN title routes tessellation as VGT_SHADER_STAGES_EN 0x45 (LS_EN 1, HS_EN 1, VS_EN 1 = VS_STAGE_DS, no ES or GS), which DecodeShaderStages refused. Decode it for GCN guests, read the local, hull and domain programs from the LS, HS and VS registers with their own user data, and give each stage the GCN wave inputs: LS v0 VertexID, v1 RelAutoIndex, v2 and v3 InstanceID; HS v0 PatchID, v1 the packed relative patch and control point, then the off-chip SGPR when OC_LDS_EN is set and the factor SGPR; domain v0 and v1 the tessellation coordinate, v2 the relative patch, v3 PatchID and the off-chip SGPR when OC_LDS_EN is set. The GCN local shader is a whole program ending in s_endpgm and links its fetch shader like a GCN vertex shader. The new TessellationConfiguration.onChip records OC_LDS_EN clear. Hull outputs kept in LDS (on chip) are refused by name and recorded as debt. Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/Driver/Draw/DrawDecode.cpp | 10 +- .../Execution/src/Driver/Draw/DrawLookup.cpp | 1 + .../src/Driver/Draw/DrawRegisterKey.cpp | 2 +- .../src/Driver/Draw/DrawRelocate.cpp | 2 +- .../src/Driver/Shaders/ShaderRegistry.cpp | 4 +- .../Graphics/include/State.hpp | 3 +- .../Graphics/src/PipelineJournal.cpp | 2 + .../libSceAgcDriver/Graphics/src/State.cpp | 21 +- .../prx/libSceAgcDriver/tests/Graphics.cpp | 50 +++ .../tests/execution/GcnTessellation.cpp | 296 ++++++++++++++++++ core/shader/recompiler/CacheKey.hpp | 1 + .../ControlFlow/src/RequestSerializer.cpp | 6 +- .../Optimization/ShaderStageInputInfo.hpp | 1 + .../Optimization/src/TessellationLowering.cpp | 4 + core/shader/recompiler/Recompiler.cpp | 2 +- core/shader/recompiler/Recompiler.hpp | 1 + .../Translation/src/InstructionTranslator.cpp | 17 + .../src/ShaderInputInfoBuilder.cpp | 1 + .../tests/RequestSerializerTests.cpp | 37 ++- .../claude-gcn-ls-hs-vs-tessellation.md | 11 + 20 files changed, 452 insertions(+), 20 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp create mode 100644 docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp index be0cdb093192..79d81459a4c5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp @@ -3,6 +3,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" #include #include #include @@ -121,7 +122,7 @@ void DecodeGraphicsPrograms(DrawDecode& decoded, const QueueState& queue, const DrawProgram result{ {stage, address, std::span(snapshot.code).subspan(codeOffset), snapshot.headerAddress, snapshot.header}, userDataBase, - stage == Stage::Fragment || userDataBase == 0x04cu ? 0u : 8u, + stage == Stage::Fragment || userDataBase == 0x04cu || ShaderRecompiler::GcnGuestShaders() ? 0u : 8u, {}, memory, program, @@ -148,7 +149,12 @@ void DecodeGraphicsPrograms(DrawDecode& decoded, const QueueState& queue, const roles.push_back(role); }; auto& graphics = product->state; - if (graphics.stages.path == Graphics::ShaderPath::Tessellation || graphics.stages.path == Graphics::ShaderPath::TessellationGeometry) { + if (graphics.stages.legacyTessellation) { + require(graphics.stages.tessellation.has_value(), "tessellation draw has no tessellation configuration"); + append(0x148, 5, Stage::Local, 0x14b, 0x14c, Role::Local); + append(0x108, 7, Stage::TessellationControl, 0x10b, 0x10c, Role::Hull); + append(0x048, 2, Stage::TessellationEvaluation, 0x04b, 0x04c, Role::Domain); + } else if (graphics.stages.path == Graphics::ShaderPath::Tessellation || graphics.stages.path == Graphics::ShaderPath::TessellationGeometry) { const auto localAddress = programAddress(0x148); const auto local = !staticAbi || localAddress != 0 ? ProgramSnapshot(registry, localAddress, {3, 5}) : nullptr; const bool mergedHull = local != nullptr && !local->header.empty() && local->type == 3; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp index 57b3eceb4f0b..ae4110836aca 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp @@ -33,6 +33,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptr(tess.breakAtInstance)}) mix(value); mix(tess.mergedHull); + mix(tess.onChip); } mix(graphics.rectList); mix(graphics.rasterizerDiscard); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp index 406e025ce6e2..6605c037f2ea 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp @@ -242,7 +242,7 @@ bool Driver::sameDecode(const DrawDecode& a, const DrawDecode& b) { const auto sameTess = [](const std::optional& x, const std::optional& y) { if (x.has_value() != y.has_value()) return false; if (!x) return true; - return x->inputControlPoints == y->inputControlPoints && x->outputControlPoints == y->outputControlPoints && x->domain == y->domain && x->partitioning == y->partitioning && x->outputTopology == y->outputTopology && x->patchesPerGroup == y->patchesPerGroup && x->primitiveGroupSize == y->primitiveGroupSize && x->breakAtInstance == y->breakAtInstance && x->mergedHull == y->mergedHull; + return x->inputControlPoints == y->inputControlPoints && x->outputControlPoints == y->outputControlPoints && x->domain == y->domain && x->partitioning == y->partitioning && x->outputTopology == y->outputTopology && x->patchesPerGroup == y->patchesPerGroup && x->primitiveGroupSize == y->primitiveGroupSize && x->breakAtInstance == y->breakAtInstance && x->mergedHull == y->mergedHull && x->onChip == y->onChip; }; if (s.stages.path != t.stages.path || s.stages.registerValue != t.stages.registerValue || s.stages.vertexWaveSize != t.stages.vertexWaveSize || s.stages.fragmentWaveSize != t.stages.fragmentWaveSize || s.stages.hullWaveSize != t.stages.hullWaveSize || !sameMesh(s.stages.mesh, t.stages.mesh) || !sameMesh(s.stages.tessellationGeometry, t.stages.tessellationGeometry) || !sameTess(s.stages.tessellation, t.stages.tessellation)) return false; if (!sameColor(s.color, t.color) || s.colors.size() != t.colors.size() || s.blends.size() != t.blends.size()) return false; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp index 0cb69b035e4b..009d8626e97b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRelocate.cpp @@ -87,7 +87,7 @@ void Driver::tagUserValueWords(DispatchVariant& variant, const DrawProgram& prog return std::any_of(variant.runs.begin(), variant.runs.end(), [&](const auto& run) { return run.first < base + bytes && run.second > base; }); }; const auto taken = [&](std::uint32_t index) { return ((variant.relocatableWords | variant.valueWords | variant.calleeWords) >> index & 1u) != 0; }; - if (ShaderRecompiler::GcnGuestShaders() && program.binary.stage == ShaderRecompiler::ShaderStage::Vertex) { + if (ShaderRecompiler::GcnGuestShaders() && (program.binary.stage == ShaderRecompiler::ShaderStage::Vertex || program.binary.stage == ShaderRecompiler::ShaderStage::Local)) { for (const auto instruction : program.binary.code) { if ((instruction & 0xff80ff00u) != 0xbe802100u) continue; const auto target = instruction & 0xffu; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp index 91d3c56328e1..917edac89000 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp @@ -1100,8 +1100,8 @@ std::vector ReadTableCallees(const ShaderRecompil } std::shared_ptr LinkUserDataCallees(const ShaderRecompiler::RecompileRequest& request, const ShaderSnapshot& snapshot, std::size_t codeOffset) { - const bool gcnVertex = ShaderRecompiler::GcnGuestShaders() && request.shader.stage == ShaderRecompiler::ShaderStage::Vertex; - if (request.shader.stage != ShaderRecompiler::ShaderStage::Compute && !gcnVertex) return nullptr; + const bool gcnFetch = ShaderRecompiler::GcnGuestShaders() && (request.shader.stage == ShaderRecompiler::ShaderStage::Vertex || request.shader.stage == ShaderRecompiler::ShaderStage::Local); + if (request.shader.stage != ShaderRecompiler::ShaderStage::Compute && !gcnFetch) return nullptr; const auto code = request.shader.code; if (std::none_of(code.begin(), code.end(), [](std::uint32_t word) { return (word & 0xff80ff00u) == 0xbe802100u; })) return nullptr; const ShaderRecompiler::SwappcInfo swappc{false, request.context.userDataBaseRegister, static_cast(request.context.userData.size()), request.context.waveSize}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp index 9123d6ae5ed6..deadfd7bd4df 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp @@ -44,6 +44,7 @@ struct ShaderStages { std::uint32_t hullWaveSize = 64; std::optional tessellationGeometry; bool legacyVertex = false; + bool legacyTessellation = false; }; inline constexpr std::uint16_t UnclampedBlendMask = 0xffffu; @@ -393,7 +394,7 @@ inline constexpr std::array DrawKeyRegisters{{ // The pixel program address, RSRC2 and user words; the geometry-back user pointer and program // address; the vertex/geometry-front RSRC1/RSRC2 and user words; the vertex program address; // the hull user pointer, program address, RSRC2 and user words; the local program address. - {RegisterBank::Shader, 0x008, 0x24}, {RegisterBank::Shader, 0x048, 0x14}, {RegisterBank::Shader, 0x082, 2}, {RegisterBank::Shader, 0x088, 2}, {RegisterBank::Shader, 0x08a, 0x22}, {RegisterBank::Shader, 0x0c8, 2}, {RegisterBank::Shader, 0x102, 2}, {RegisterBank::Shader, 0x108, 2}, {RegisterBank::Shader, 0x10b, 0x21}, {RegisterBank::Shader, 0x148, 2}, + {RegisterBank::Shader, 0x008, 0x24}, {RegisterBank::Shader, 0x048, 0x14}, {RegisterBank::Shader, 0x082, 2}, {RegisterBank::Shader, 0x088, 2}, {RegisterBank::Shader, 0x08a, 0x22}, {RegisterBank::Shader, 0x0c8, 2}, {RegisterBank::Shader, 0x102, 2}, {RegisterBank::Shader, 0x108, 2}, {RegisterBank::Shader, 0x10b, 0x21}, {RegisterBank::Shader, 0x148, 0x14}, // GE_PRIM_TYPE, GE_MULTI_PRIM_IB_RESET_EN, the geometry subgroup sizes. {RegisterBank::UserConfig, 0x242, 1}, {RegisterBank::UserConfig, 0x24b, 1}, {RegisterBank::UserConfig, 0x25b, 1}, }}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp index 40151aece0c2..75adc03cebaa 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp @@ -172,6 +172,7 @@ void encodeTessellation(Writer& writer, const ShaderRecompiler::TessellationConf writer.U32(tessellation.instancePatches); writer.Bool(tessellation.drawParameters); writer.Bool(tessellation.mergedHull); + writer.Bool(tessellation.onChip); } void decodeTessellation(Reader& reader, ShaderRecompiler::TessellationConfiguration& tessellation) { @@ -180,6 +181,7 @@ void decodeTessellation(Reader& reader, ShaderRecompiler::TessellationConfigurat tessellation.instancePatches = reader.U32(); tessellation.drawParameters = reader.Bool(); tessellation.mergedHull = reader.Bool(); + tessellation.onChip = reader.Bool(); } void encodeState(Writer& writer, const State& state) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp index cbcabc964770..ac00d39b4191 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp @@ -1376,7 +1376,9 @@ ShaderStages DecodeShaderStages(const QueueState& queue, bool vertexWorkgroup) { validate((value & 0x2000u) != 0, "legacy vertex routing without PRIMGEN_EN is unsupported"); validate((value & ~0x0247a010u) == 0 || value == 0x02002008u, "unsupported vertex routing, scheduling or wave-ID state"); } else if (path == ShaderPath::Tessellation || path == ShaderPath::TessellationGeometry) { - if (path == ShaderPath::Tessellation) validate((value & ~0x0267ed0du) == 0 && (value & 0x02002000u) == 0x02002000u && (value & 3u) == 1u && ((value >> 3u) & 3u) == 1u, "unsupported tessellation routing"); + const bool legacy = ShaderRecompiler::GcnGuestShaders() && (value & 0x2000u) == 0; + if (legacy) validate(path == ShaderPath::Tessellation && (value & ~0x100u) == 0x45u, "GCN tessellation routing other than LS, HS and a domain shader on the VS stage is unsupported"); + else if (path == ShaderPath::Tessellation) validate((value & ~0x0267ed0du) == 0 && (value & 0x02002000u) == 0x02002000u && (value & 3u) == 1u && ((value >> 3u) & 3u) == 1u, "unsupported tessellation routing"); else validate((value & ~0x0067ed2du) == 0 && (value & 0x02002000u) == 0x2000u && (value & 3u) == 1u && ((value >> 3u) & 3u) == 1u, "unsupported tessellation and geometry routing"); const auto config = read(queue.context, 0x2d6); const auto parameters = read(queue.context, 0x2db); @@ -1384,11 +1386,26 @@ ShaderStages DecodeShaderStages(const QueueState& queue, bool vertexWorkgroup) { ShaderRecompiler::TessellationConfiguration tess{(config >> 8u) & 0x3fu, (config >> 14u) & 0x3fu, parameters & 3u, (parameters >> 2u) & 7u, (parameters >> 5u) & 7u, config & 0xffu, primitiveGroup == queue.userConfig.end() ? 0u : primitiveGroup->second & 0x1ffu, primitiveGroup != queue.userConfig.end() && (primitiveGroup->second & 0x40000u) != 0u}; validate(tess.inputControlPoints != 0 && tess.inputControlPoints <= 32 && tess.outputControlPoints != 0 && tess.outputControlPoints <= 32, "invalid tessellation control-point counts"); validate(tess.patchesPerGroup != 0, "VGT_LS_HS_CONFIG.NUM_PATCHES is zero"); - if ((parameters & ~0x000600ffu) != 0) Require(false, zeroMessage(0x2db, parameters, "VGT_TF_PARAM donut, factor detection, memory type or reserved state")); + if ((parameters & ~(legacy ? 0x0001bcffu : 0x000600ffu)) != 0) Require(false, zeroMessage(0x2db, parameters, "VGT_TF_PARAM donut, factor detection, memory type or reserved state")); if (!((tess.domain == 1 || tess.domain == 2) && (tess.partitioning == 0 || tess.partitioning == 2 || tess.partitioning == 3) && (tess.outputTopology == 2 || tess.outputTopology == 3))) validate(false, tessellationMessage(config, parameters, tess).c_str()); result.minTessellationLevel = readFloat(queue.context, 0x287); result.maxTessellationLevel = readFloat(queue.context, 0x286); Require(result.minTessellationLevel >= 0.0f && result.minTessellationLevel <= 63.0f && result.minTessellationLevel <= result.maxTessellationLevel && result.maxTessellationLevel >= 1.0f, "tessellation level clamps need 0 <= VGT_HOS_MIN_TESS_LEVEL <= 63, VGT_HOS_MAX_TESS_LEVEL >= 1 and the minimum at most the maximum"); + if (legacy) { + const auto hull = read(queue.shader, 0x10b, RegisterBank::Shader); + const auto domain = read(queue.shader, 0x4b, RegisterBank::Shader); + validate((hull & 0x100u) == 0, "SPI_SHADER_PGM_RSRC2_HS.TG_SIZE_EN on a GCN hull shader is not implemented"); + validate((domain & 0x1f00u) == 0, "stream-out from a GCN domain shader (SPI_SHADER_PGM_RSRC2_VS.SO_EN or SO_BASE*_EN) is not implemented"); + validate(((hull ^ domain) & 0x80u) == 0, "the GCN hull and domain shaders disagree on SPI_SHADER_PGM_RSRC2.OC_LDS_EN"); + const auto unitStepRate = [&](std::uint32_t offset) { + const auto rate = find(queue.context, offset); + return rate == queue.context.end() || rate->second == 1u; + }; + const auto components = (read(queue.shader, 0x14a, RegisterBank::Shader) >> 24u) & 3u; + validate(components < 2u || unitStepRate(0x2a8), "GCN local shader instance step rates other than 1 are not implemented"); + tess.onChip = (hull & 0x80u) == 0; + result.legacyTessellation = true; + } result.tessellation = tess; if (path == ShaderPath::TessellationGeometry) result.tessellationGeometry = meshConfiguration(4u, false); } else { diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index a3469b6aa2e4..4c47441719db 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -1358,6 +1358,56 @@ void ShaderStageTests() { queue.context[0x2db] = 0x40049; queue.context[0x286] = 0x42800000; queue.context[0x287] = 0x3f800000; + { + ShaderRecompiler::SetGcnGuestShaders(true); + struct Restore { + ~Restore() { ShaderRecompiler::SetGcnGuestShaders(false); } + } restore; + auto gcn = queue; + gcn.context[0x2d5] = 0x45; + gcn.context[0x2db] = 0x1bc49; + gcn.shader[0x14a] = 0x030c0048; + gcn.shader[0x10b] = 0x10; + gcn.shader[0x4b] = 0x18; + AgcDriver::Graphics::ShaderStages gcnStages; + { + std::vector gcnLog; + { + const AgcDriver::Graphics::RegisterReadLogScope logScope(&gcnLog); + gcnStages = AgcDriver::Graphics::DecodeShaderStages(gcn); + } + for (const auto read : gcnLog) Require(AgcDriver::Graphics::DrawKeyCovers(read), "DrawKeyRegisters lacks a GCN tessellation register the decoder reads: " + std::to_string(read.offset)); + } + Require(gcnStages.path == AgcDriver::Graphics::ShaderPath::Tessellation && gcnStages.legacyTessellation && !gcnStages.legacyVertex && gcnStages.tessellation && gcnStages.tessellation->onChip && !gcnStages.tessellation->mergedHull && gcnStages.vertexWaveSize == 64u && gcnStages.hullWaveSize == 64u, "the GCN LS, HS and VS-stage domain routing 0x45 with OC_LDS_EN clear did not decode as on-chip GCN tessellation"); + Require(gcnStages.tessellation->inputControlPoints == 3 && gcnStages.tessellation->outputControlPoints == 3 && gcnStages.tessellation->domain == 1 && gcnStages.tessellation->partitioning == 2 && gcnStages.tessellation->outputTopology == 2 && gcnStages.tessellation->patchesPerGroup == 85, "the GCN triangle-patch configuration decoded differently"); + gcn.context[0x2d5] = 0x145; + gcn.shader[0x10b] = 0x90; + gcn.shader[0x4b] = 0x98; + const auto offChip = AgcDriver::Graphics::DecodeShaderStages(gcn); + Require(offChip.legacyTessellation && !offChip.tessellation->onChip, "GCN routing 0x145 with OC_LDS_EN set did not decode as off-chip GCN tessellation"); + for (const auto routing : {0x4du, 0x05u, 0x44u, 0x245u, 0x65u}) { + gcn.context[0x2d5] = routing; + expectFailure([&] { AgcDriver::Graphics::DecodeShaderStages(gcn); }, "GCN tessellation routing other than LS, HS and a domain shader on the VS stage"); + } + gcn.context[0x2d5] = 0x45; + for (const auto parameters : {0x4049u, 0x40049u, 0x149u}) { + gcn.context[0x2db] = parameters; + expectFailure([&] { AgcDriver::Graphics::DecodeShaderStages(gcn); }, "VGT_TF_PARAM"); + } + gcn.context[0x2db] = 0x49; + gcn.shader[0x4b] = 0x18; + expectFailure([&] { AgcDriver::Graphics::DecodeShaderStages(gcn); }, "disagree on SPI_SHADER_PGM_RSRC2.OC_LDS_EN"); + gcn.shader[0x4b] = 0x1098; + expectFailure([&] { AgcDriver::Graphics::DecodeShaderStages(gcn); }, "stream-out from a GCN domain shader"); + gcn.shader[0x4b] = 0x98; + gcn.shader[0x10b] = 0x190; + expectFailure([&] { AgcDriver::Graphics::DecodeShaderStages(gcn); }, "TG_SIZE_EN"); + gcn.shader[0x10b] = 0x90; + gcn.context[0x2a8] = 2; + expectFailure([&] { AgcDriver::Graphics::DecodeShaderStages(gcn); }, "GCN local shader instance step rates other than 1"); + gcn.shader[0x14a] = 0x010c0048; + Require(AgcDriver::Graphics::DecodeShaderStages(gcn).legacyTessellation, "a GCN local shader that loads no step-rate instance VGPR was refused for its step rate"); + } queue.context[0x2d5] = 0x0260210d; { const auto wave32 = AgcDriver::Graphics::DecodeState(queue).stages; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp new file mode 100644 index 000000000000..4d55750f8f30 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp @@ -0,0 +1,296 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "Recompiler.hpp" +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; +using ShaderRecompiler::TessellationConfiguration; + +constexpr std::uint32_t Width = 256; +constexpr std::uint32_t Height = 80; +constexpr std::array Background{16, 24, 40, 255}; +constexpr std::array White{255, 255, 255, 255}; +alignas(256) std::array Pixels{}; + +alignas(256) constexpr std::array GcnLocal{ + 0xbefc03c1, 0xd2900002, 0x02110900, 0xd2900003, 0x02090500, 0xd2900004, 0x02090100, 0x7e040d02, + 0x7e060d03, 0x7e080d04, 0x100a04ff, 0x3f19999a, 0x060a0aff, 0xbf666666, 0x3e0a06ff, 0x3e800000, + 0x100c08ff, 0x3f4ccccd, 0x060c0cff, 0xbf4ccccd, 0x340e0284, 0xd8340000, 0x00000507, 0xd8340004, + 0x00000607, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnHullOffChip{ + 0xbefc03c1, 0xd2900002, 0x02151101, 0xd2900003, 0x02210101, 0x34080484, 0xd2860005, 0x04116103, + 0xd8d80000, 0x06000005, 0xd8d80004, 0x07000005, 0xbf8c007f, 0xe0701000, 0x04000605, 0xe0701004, + 0x04000705, 0x7d840480, 0xbe86246a, 0x36100081, 0x7e100d08, 0x081010f2, 0x34120684, 0xe0701000, + 0x05000809, 0xe0701004, 0x05000809, 0xe0701008, 0x05000809, 0xe070100c, 0x05000809, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnHullOnChip{ + 0xd2900002, 0x02151101, 0xd2900003, 0x02210101, 0x7d840480, 0xbe86246a, 0x36100081, 0x7e100d08, + 0x081010f2, 0x34120684, 0xe0701000, 0x04000809, 0xe0701004, 0x04000809, 0xe0701008, 0x04000809, + 0xe070100c, 0x04000809, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnHullOnChipLds{ + 0xbefc03c1, 0xd2900002, 0x02151101, 0xd2900003, 0x02210101, 0x34080484, 0xd2860005, 0x04116103, + 0xd8d80000, 0x06000005, 0xbf8c007f, 0x4a140aff, 0x00000900, 0xd8340000, 0x0000060a, 0x7d840480, + 0xbe86246a, 0x36100081, 0x7e100d08, 0x081010f2, 0x34120684, 0xe0701000, 0x04000809, 0xe0701004, + 0x04000809, 0xe0701008, 0x04000809, 0xe070100c, 0x04000809, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnDomainOffChip{ + 0x160804b0, 0xe0301000, 0x04000504, 0xe0301004, 0x04000604, 0xe0301010, 0x04000704, 0xe0301014, + 0x04000804, 0xe0301020, 0x04000904, 0xe0301024, 0x04000a04, 0xbf8c0070, 0x081600f2, 0x0816030b, + 0x10180b00, 0x3e180f01, 0x3e18130b, 0x101a0d00, 0x3e1a1101, 0x3e1a150b, 0x7e1c0280, 0x7e1e02f2, + 0xf80008cf, 0x0f0e0d0c, 0xf800020f, 0x0f0f0f0f, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnDomainOnChip{ + 0x081600f2, 0x0816030b, 0x7e080d03, 0x100808ff, 0x3f19999a, 0x060808ff, 0xbf666666, 0x3e0802f0, + 0x3e0816ff, 0x3e800000, 0x100a16ff, 0x3fcccccd, 0x060a0aff, 0xbf4ccccd, 0x7e1c0280, 0x7e1e02f2, + 0xf80008cf, 0x0f0e0504, 0xf800020f, 0x0f0f0f0f, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnDomainOnChipLds{ + 0xbefc03c1, 0x160804b0, 0xd8d80000, 0x05000004, 0xbf8c007f, 0x7e1e02f2, 0xf80008cf, 0x0f0f0505, + 0xbf810000, +}; + +alignas(256) constexpr std::array PixelCode{ + 0xc8020002, 0xc8060102, 0xc80a0202, 0xc80e0302, 0xf800180f, 0x03020100, 0xbf810000, +}; + +constexpr std::uint16_t Corner(std::uint32_t patch, std::uint32_t x, std::uint32_t y) { + return static_cast((patch << 4u) | (x << 2u) | y); +} + +alignas(256) constexpr std::array Indices{ + Corner(0, 0, 0), Corner(0, 2, 0), Corner(0, 1, 2), + Corner(1, 0, 0), Corner(1, 2, 0), Corner(1, 1, 2), + Corner(2, 0, 0), Corner(2, 2, 0), Corner(2, 1, 2), +}; + +constexpr std::array RingUserData{0x1000u, 0u, 0u, 0u}; + +TessellationConfiguration Patches(bool onChip) { + TessellationConfiguration configuration{3u, 3u, 1u, 0u, 2u, 4u}; + configuration.onChip = onChip; + return configuration; +} + +struct Stages { + ShaderRecompiler::RecompileResult local; + ShaderRecompiler::RecompileResult hull; + ShaderRecompiler::RecompileResult domain; + ShaderRecompiler::RecompileResult fragment; +}; + +ShaderRecompiler::RecompileResult Compile(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, std::uint32_t& pushCursor, const TessellationConfiguration& configuration) { + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const auto userData = stage == ShaderStage::TessellationControl || stage == ShaderStage::TessellationEvaluation ? std::span(RingUserData) : std::span(); + std::optional pixel; + std::optional vertex; + std::optional graphics; + if (stage == ShaderStage::Fragment) { + ShaderRecompiler::ShaderPixelStageInfo info{}; + info.interpolatorCount = 1; + info.interpolatorSettings[0] = 0x400u; + info.targetOutputMode[0] = 9; + info.targetExportMapping.fill(0xe4u); + pixel = info; + } else { + vertex = ShaderRecompiler::ShaderVertexStageInfo{}; + graphics = ShaderRecompiler::GraphicsCompileContext{0u, {}, std::nullopt, configuration, {reinterpret_cast(Indices.data()), static_cast(Indices.size()), 2, 1}}; + } + auto layout = stage == ShaderStage::Fragment ? PixelPushLayout(pushCursor, target) : ShaderRecompiler::BindingLayout{0, 0, pushCursor, AgcDriver::Graphics::PipelinePushSlotBytes - pushCursor}; + if (layout.pushConstantOffsetBytes < AgcDriver::Graphics::PipelinePushSlotBytes) layout.pushConstantSizeBytes = ShaderRecompiler::TessellationLevelPushOffsetBytes - layout.pushConstantOffsetBytes; + ShaderRecompiler::RecompileRequest request{ + {stage, reinterpret_cast(code.data()), code, 0, {}}, + {64, 0u, userData, std::nullopt, pixel, vertex, memory}, + target, + layout, + graphics + }; + request.useCache = false; + auto result = ShaderRecompiler::Recompile(request); + pushCursor += static_cast(result.pushConstants.size()); + return result; +} + +void ExpectRefusal(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, const std::string& reason) { + std::uint32_t cursor = 0; + try { + static_cast(Compile(target, stage, code, cursor, Patches(true))); + } catch (const std::exception& error) { + Require(std::string(error.what()).find(reason) != std::string::npos, "the refusal named another reason: " + std::string(error.what())); + return; + } + Require(false, "a GCN tessellation program was accepted although " + reason); +} + +std::array PixelAt(std::uint32_t x, std::uint32_t y) { + const auto offset = (static_cast(y) * Width + x) * 4u; + return {std::to_integer(Pixels[offset]), std::to_integer(Pixels[offset + 1]), std::to_integer(Pixels[offset + 2]), std::to_integer(Pixels[offset + 3])}; +} + +std::string PixelText(const std::array& pixel) { + char text[64]; + std::snprintf(text, sizeof(text), "(%u, %u, %u, %u)", pixel[0], pixel[1], pixel[2], pixel[3]); + return text; +} + +std::uint32_t Column(std::uint32_t patch, float offset) { + return static_cast((-0.9f + 0.6f * static_cast(patch) + offset + 1.0f) * 0.5f * Width); +} + +std::uint32_t Row(float y) { + return static_cast((1.0f - y) * 0.5f * Height); +} + +void Draw(AgcDriver::VulkanDevice& device, const Stages& stages, const TessellationConfiguration& configuration) { + for (std::size_t i = 0; i < Pixels.size(); i += 4) { + for (std::size_t c = 0; c < 4; ++c) Pixels[i + c] = std::byte{Background[c]}; + } + std::uint32_t cursor = 0; + const auto offset = [&](const ShaderRecompiler::RecompileResult& result) { + const auto at = result.pushConstants.empty() ? 0u : cursor; + cursor += static_cast(result.pushConstants.size()); + return at; + }; + const std::array shaders{{ + {ShaderStage::Local, &stages.local, offset(stages.local)}, + {ShaderStage::TessellationControl, &stages.hull, offset(stages.hull)}, + {ShaderStage::TessellationEvaluation, &stages.domain, offset(stages.domain)}, + {ShaderStage::Fragment, &stages.fragment, PixelPushOffset(cursor, device.Target())}, + }}; + AgcDriver::Graphics::State state{}; + state.stages = {AgcDriver::Graphics::ShaderPath::Tessellation, 0x45u, 64, 64, std::nullopt, configuration, 1.0f, 64.0f}; + state.stages.legacyTessellation = true; + state.color = {reinterpret_cast(Pixels.data()), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, Pixels.size(), 0xe4u}; + state.colors = {state.color}; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_PATCH_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{0, 0}, {Width, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + state.blend.colorWriteMask = 15; + state.blends = {state.blend}; + state.blendConstants = {}; + device.Draw(state, {reinterpret_cast(Indices.data()), static_cast(Indices.size()), 2, 1, 0, true, 0, 0}, shaders); + device.WaitIdle(); +} + +void RequirePatches(AgcDriver::VulkanDevice& device, std::span hull, std::span domain, bool onChip, const std::string& program) { + const auto target = device.Target(); + const auto configuration = Patches(onChip); + std::uint32_t cursor = 0; + Stages stages{ + Compile(target, ShaderStage::Local, GcnLocal, cursor, configuration), + Compile(target, ShaderStage::TessellationControl, hull, cursor, configuration), + Compile(target, ShaderStage::TessellationEvaluation, domain, cursor, configuration), + Compile(target, ShaderStage::Fragment, PixelCode, cursor, configuration), + }; + Draw(device, stages, configuration); + constexpr std::array, 4> inside{{{0.25f, -0.267f}, {0.06f, -0.72f}, {0.44f, -0.72f}, {0.25f, 0.4f}}}; + for (std::uint32_t patch = 0; patch < 3u; ++patch) { + const auto expected = patch == 1u ? Background : White; + for (const auto [x, y] : inside) { + const auto pixel = PixelAt(Column(patch, x), Row(y)); + Require(pixel == expected, program + ": patch " + std::to_string(patch) + " at (" + std::to_string(x) + ", " + std::to_string(y) + ") is " + PixelText(pixel) + ", expected " + PixelText(expected) + (patch == 1u ? " for a patch whose tessellation factors are 0" : " inside its tessellated triangle")); + } + const auto outside = PixelAt(Column(patch, 0.45f), Row(0.5f)); + Require(outside == Background, program + ": patch " + std::to_string(patch) + " covers a pixel outside its triangle: " + PixelText(outside)); + } +} + +void Bind(AgcDriver::QueueState& queue, const void* code, std::uint32_t program, std::uint32_t resources, std::span users) { + const auto address = reinterpret_cast(code); + queue.shader[program] = static_cast(address >> 8u); + queue.shader[program + 1u] = static_cast(address >> 40u); + queue.shader[resources] = static_cast(users.size()) << 1u; + for (std::size_t i = 0; i < users.size(); ++i) queue.shader[resources + 1u + static_cast(i)] = users[i]; +} + +void RequireProgramDecode() { + using namespace AgcDriver::DriverDetail; + using ShaderRecompiler::ProgramRole; + constexpr std::array localUsers{0x11110001u, 0x11110002u}; + constexpr std::array hullUsers{0x22220001u, 0x22220002u, 0x22220003u, 0x22220004u}; + constexpr std::array domainUsers{0x33330001u, 0x33330002u, 0x33330003u}; + AgcDriver::QueueState queue{}; + queue.context[0x8e] = 0xfu; + queue.context[0x8f] = 0xfu; + Bind(queue, GcnLocal.data(), 0x148u, 0x14bu, localUsers); + Bind(queue, GcnHullOffChip.data(), 0x108u, 0x10bu, hullUsers); + Bind(queue, GcnDomainOffChip.data(), 0x048u, 0x04bu, domainUsers); + Bind(queue, PixelCode.data(), 0x008u, 0x00bu, {}); + DrawDecode draw{}; + draw.state.stages = {AgcDriver::Graphics::ShaderPath::Tessellation, 0x45u, 64u, 64u, std::nullopt, Patches(false), 1.0f, 64.0f}; + draw.state.stages.legacyTessellation = true; + draw.pixel.interpolatorCount = 1; + draw.pixel.interpolatorSettings[0] = 0x400u; + draw.pixel.targetOutputMode[0] = 9; + draw.pixel.targetExportMapping.fill(0xe4u); + const ShaderRegistry registry; + DecodeGraphicsPrograms(draw, queue, registry, false, true); + const std::vector roles{ProgramRole::Local, ProgramRole::Hull, ProgramRole::Domain, ProgramRole::Fragment}; + Require(draw.roles == roles, "the GCN LS, HS and VS-stage domain programs did not decode as the local, hull and domain roles"); + const std::array stages{ShaderStage::Local, ShaderStage::TessellationControl, ShaderStage::TessellationEvaluation, ShaderStage::Fragment}; + const std::array codes{GcnLocal.data(), GcnHullOffChip.data(), GcnDomainOffChip.data(), PixelCode.data()}; + const std::array, 4> users{localUsers, hullUsers, domainUsers, {}}; + for (std::size_t index = 0; index < draw.programs.size(); ++index) { + const auto& program = draw.programs[index]; + const auto name = "GCN program " + std::to_string(index); + Require(program.binary.stage == stages[index] && program.binary.codeAddress == reinterpret_cast(codes[index]), name + " was read from another program register"); + Require(program.firstUserSgpr == 0u && program.hiddenUserWords == 0u, name + " places its user data after hidden words"); + Require(std::ranges::equal(program.userData, users[index]), name + " did not read its own stage's user data"); + } + Require(!draw.state.stages.tessellation->mergedHull, "a GCN hull program decoded as a merged hull"); +} + +} + +int main() { + try { + ShaderRecompiler::SetGcnGuestShaders(true); + RequireProgramDecode(); + ShaderRecompiler::SetGcnGuestShaders(false); + auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + const auto target = device->Target(); + if (!target.tessellation.has_value()) { + std::puts("GCN tessellation: skipped, the device has no tessellation shaders"); + return VulkanTestSkipped; + } + ShaderRecompiler::SetGcnGuestShaders(true); + RequirePatches(*device, GcnHullOffChip, GcnDomainOffChip, false, "GCN off-chip LS-HS-VS draw"); + RequirePatches(*device, GcnHullOnChip, GcnDomainOnChip, true, "GCN on-chip LS-HS-VS draw"); + ExpectRefusal(target, ShaderStage::TessellationControl, GcnHullOnChipLds, "keeps its outputs on chip"); + ExpectRefusal(target, ShaderStage::TessellationEvaluation, GcnDomainOnChipLds, "reads them from LDS"); + ShaderRecompiler::SetGcnGuestShaders(false); + device.reset(); + std::puts("GCN tessellation tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index 0c3228419dc1..78aba8d27fd5 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -148,6 +148,7 @@ class RecompileCacheKey { if (tessellation == nullptr) return; for (const auto value : {tessellation->inputControlPoints, tessellation->outputControlPoints, tessellation->domain, tessellation->partitioning, tessellation->outputTopology}) append(key, value); if (request.shader.stage != ShaderStage::TessellationEvaluation) append(key, tessellation->mergedHull); + append(key, tessellation->onChip); if (request.shader.stage == ShaderStage::Local) return; append(key, tessellation->patchesPerGroup); append(key, tessellation->primitiveGroupSize); diff --git a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp index 63ac303e6691..15115f418c49 100644 --- a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp +++ b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp @@ -916,7 +916,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const std::string buffer; Writer writer(buffer); writer.WriteU32(0x41505335u); - writer.WriteU32(62u); + writer.WriteU32(63u); writeShaderBinary(writer, request.shader); writeGuestContext(writer, request.context); writeSpirvTarget(writer, request.target); @@ -970,6 +970,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const writer.WriteU32(request.target.maxImageArrayLayers); writer.WriteBool(request.target.fixedPushSlots); writer.WriteBool(request.target.spannedAnySubgroup); + if (request.graphics && request.graphics->tessellation) writer.WriteBool(request.graphics->tessellation->onChip); return base64Encode(buffer); } @@ -978,7 +979,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const Reader reader(decoded); if (reader.ReadU32() != 0x41505335u) throw std::runtime_error("invalid recompile request signature"); const auto version = reader.ReadU32(); - if (version < 1u || version > 62u || version == 50u || (version >= 58u && version <= 61u)) throw std::runtime_error("unsupported recompile request serialization version"); + if (version < 1u || version > 63u || version == 50u || (version >= 58u && version <= 61u)) throw std::runtime_error("unsupported recompile request serialization version"); DeserializedRequest result{}; result.request.shader = readShaderBinary(reader, result.shaderCode, result.shaderHeader); result.request.context = readGuestContext(reader, result, version); @@ -1054,6 +1055,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const result.request.target.fixedPushSlots = reader.ReadBool(); } if (version >= 62u) result.request.target.spannedAnySubgroup = reader.ReadBool(); + if (version >= 63u && result.request.graphics && result.request.graphics->tessellation) result.request.graphics->tessellation->onChip = reader.ReadBool(); if (version >= 21u && reader.Remaining() != 0u) throw std::runtime_error("RequestSerializer: unexpected trailing data"); return result; } diff --git a/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp b/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp index 103a4c37279e..c0a283b4d2bd 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp @@ -116,6 +116,7 @@ struct ShaderTessellationInputInfo { std::uint32_t instancePatches = 0; bool drawParameters = false; bool mergedHull = false; + bool onChip = false; std::uint32_t geometryItemDwords = 0; }; diff --git a/core/shader/recompiler/Optimization/src/TessellationLowering.cpp b/core/shader/recompiler/Optimization/src/TessellationLowering.cpp index a425c5a4f32a..6323df2dfddc 100644 --- a/core/shader/recompiler/Optimization/src/TessellationLowering.cpp +++ b/core/shader/recompiler/Optimization/src/TessellationLowering.cpp @@ -1015,6 +1015,10 @@ class Lowering { access.kind = TessellationAttribute::GeometryOutput; } else if (stage == IrShaderStage::TessellationControl && !access.write) { access.kind = TessellationAttribute::ControlInput; + } else if (tessellation.onChip && stage == IrShaderStage::TessellationControl) { + Fail("a hull shader that keeps its outputs on chip (SPI_SHADER_PGM_RSRC2_HS.OC_LDS_EN=0) writes them to LDS, which is not implemented", flags.pc); + } else if (tessellation.onChip && stage == IrShaderStage::TessellationEvaluation) { + Fail("a domain shader that reads hull outputs on chip (SPI_SHADER_PGM_RSRC2_VS.OC_LDS_EN=0) reads them from LDS, which is not implemented", flags.pc); } else { Fail("unsupported LDS access in a tessellation stage", flags.pc); } diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 5e70c4b95608..210237cc8750 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -137,7 +137,7 @@ RdnaProgram DecodeStageProgram(ShaderStageKind stage, std::span(6), u32(0u)); setVector(static_cast(7), u32(0u)); setVector(static_cast(8), entryIr.IAdd(draw(2u), builtin(StageInputKind::WorkgroupId, 1u))); + } else if (options.stage == ShaderStageKind::Local && options.gcnLegacyVertexInputs) { + setVector(static_cast(0), drawIndex(StageInputKind::VertexIndex)); + setVector(static_cast(1), tessellationBase(TessellationBaseKind::RelativeIndex)); + setVector(static_cast(2), drawIndex(StageInputKind::InstanceIndex)); + setVector(static_cast(3), drawIndex(StageInputKind::InstanceIndex)); + } else if (options.stage == ShaderStageKind::TessellationControl && options.gcnLegacyVertexInputs) { + auto reg = options.userDataBaseRegister + options.userDataCount; + if (!options.inputInfo.vertex->tess.onChip) entryIr.SetScalarReg(static_cast(reg++), tessellationBase(TessellationBaseKind::OffChip)); + entryIr.SetScalarReg(static_cast(reg), tessellationBase(TessellationBaseKind::Factor)); + setVector(static_cast(0), builtin(StageInputKind::PrimitiveId)); + setVector(static_cast(1), entryIr.BitwiseOr(entryIr.ShiftLeftLogical(builtin(StageInputKind::InvocationId), entryIr.Constant(8u)), tessellationBase(TessellationBaseKind::RelativeIndex))); + } else if (options.stage == ShaderStageKind::TessellationEvaluation && options.gcnLegacyVertexInputs) { + if (!options.inputInfo.vertex->tess.onChip) entryIr.SetScalarReg(static_cast(options.userDataBaseRegister + options.userDataCount), tessellationBase(TessellationBaseKind::OffChip)); + setVector(static_cast(0), builtin(StageInputKind::TessCoord, 0u)); + setVector(static_cast(1), builtin(StageInputKind::TessCoord, 1u)); + setVector(static_cast(2), tessellationBase(TessellationBaseKind::RelativeIndex)); + setVector(static_cast(3), builtin(StageInputKind::PrimitiveId)); } else if (options.stage == ShaderStageKind::Local) { entryIr.SetScalarReg(static_cast(3), entryIr.Constant(64u)); setVector(static_cast(2), drawIndex(StageInputKind::VertexIndex)); diff --git a/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp b/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp index 19414421c6d9..448012a5c646 100644 --- a/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp +++ b/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp @@ -237,6 +237,7 @@ ShaderStageInputInfo BuildShaderStageInputInfo(ShaderStageKind stage, const Gues target.instancePatches = tessellation->instancePatches; target.drawParameters = tessellation->drawParameters; target.mergedHull = tessellation->mergedHull; + target.onChip = tessellation->onChip; target.geometryItemDwords = stage == ShaderStageKind::TessellationEvaluation && mesh != nullptr ? mesh->esgsItemSize : 0u; } if (stage == ShaderStageKind::Mesh) { diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index a4460e375b3a..3f72177e7547 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -198,12 +198,32 @@ void VerifyTessellationInstancePatches() { Require(ShaderRecompiler::TessellationInstancePatches(request) == 4u); } +void VerifyTessellationOnChip() { + const ShaderRecompiler::RequestSerializer serializer; + for (const bool onChip : {false, true}) { + ShaderRecompiler::RecompileRequest request{}; + request.graphics.emplace(); + request.graphics->tessellation = ShaderRecompiler::TessellationConfiguration{3u, 3u, 1u, 0u, 2u}; + request.graphics->tessellation->onChip = onChip; + const auto encoded = serializer.Serialize(request); + const auto replay = serializer.Deserialize(encoded); + Require(replay.request.graphics && replay.request.graphics->tessellation && replay.request.graphics->tessellation->onChip == onChip); + Require(serializer.Serialize(replay.request) == encoded); + auto version62 = DecodeBase64(encoded); + Require(version62[4] == 63u && version62.back() == (onChip ? 1u : 0u)); + version62.pop_back(); + version62[4] = 62u; + const auto replay62 = serializer.Deserialize(EncodeBase64(version62)); + Require(replay62.request.graphics && replay62.request.graphics->tessellation && !replay62.request.graphics->tessellation->onChip); + } +} + } std::string SerializeVersion56(const ShaderRecompiler::RecompileRequest& request) { auto bytes = DecodeBase64(ShaderRecompiler::RequestSerializer{}.Serialize(request)); - Require(bytes.size() > 14u && bytes[4] == 62u); - bytes.resize(bytes.size() - 6u); + Require(bytes.size() > 14u && bytes[4] == 63u); + bytes.resize(bytes.size() - (request.graphics && request.graphics->tessellation ? 7u : 6u)); bytes[4] = 56u; return EncodeBase64(bytes); } @@ -226,7 +246,7 @@ void VerifyTargetOptions() { Require(replay.request.target.float16WidenNans == widen && replay.request.target.float16NarrowNans == narrow); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 62u && bytes.back() == 0u); + Require(bytes[4] == 63u && bytes.back() == 0u); for (std::size_t missing = 1u; missing <= 6u; ++missing) { auto truncated = bytes; truncated.resize(truncated.size() - missing); @@ -776,7 +796,7 @@ int VerifyVersion56Compatibility() { version40[4] = 40u; const auto replay40 = serializer.Deserialize(EncodeBase64(version40)); Require(!replay40.request.target.float32DenormPreserve && replay40.request.target.float32FlushToZero == !preserve); - for (const std::uint8_t unwritten : {58u, 59u, 60u, 61u, 63u}) { + for (const std::uint8_t unwritten : {58u, 59u, 60u, 61u, 64u}) { auto future = bytes; future[4] = unwritten; bool futureRejected = false; @@ -891,10 +911,10 @@ int VerifyVersion56Compatibility() { const auto replay35 = serializer.Deserialize(EncodeBase64(version35)); Require(replay35.request.target.spannedWaves == spanned && !replay35.request.target.float32FlushToZero); request.target.spannedAnySubgroup = spanned; - const auto version62 = DecodeBase64(serializer.Serialize(request)); - Require(version62[4] == 62u && version62.back() == (spanned ? 1u : 0u)); - Require(serializer.Deserialize(EncodeBase64(version62)).request.target.spannedAnySubgroup == spanned); - auto version57 = version62; + const auto current = DecodeBase64(serializer.Serialize(request)); + Require(current[4] == 63u && current.back() == (spanned ? 1u : 0u)); + Require(serializer.Deserialize(EncodeBase64(current)).request.target.spannedAnySubgroup == spanned); + auto version57 = current; version57[4] = 57u; version57.pop_back(); const auto replay57 = serializer.Deserialize(EncodeBase64(version57)); @@ -1170,6 +1190,7 @@ int VerifyVersion56Compatibility() { } int main() { + VerifyTessellationOnChip(); VerifyTargetOptions(); return VerifyVersion56Compatibility(); } diff --git a/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md b/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md new file mode 100644 index 000000000000..8b87fff07ed9 --- /dev/null +++ b/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md @@ -0,0 +1,11 @@ +# shader + +## add Functional + +- [PS4 (GCN) on-chip tessellation](../../../core/shader/recompiler/Optimization/src/TessellationLowering.cpp) (shader recompiler, PS4) - not measured on a console. LS, HS and VS-stage domain routing (`VGT_SHADER_STAGES_EN` 0x45 or 0x145) is drawn through the off-chip ring lowering. With `SPI_SHADER_PGM_RSRC2_HS.OC_LDS_EN` clear the hull shader keeps its control points and patch constants in LDS and the domain shader reads them there, at offsets a tessellation constant buffer bound by the title computes at run time; a hull LDS write or a domain LDS read then throws. An on-chip hull that writes only tessellation factors and a domain shader that reads no hull output are drawn. + +# libSceAgcDriver + +## add Functional + +- [PS4 (GCN) tessellation routing](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver, PS4) - not measured on a console. LS, HS, ES and GS routing, `SPI_SHADER_PGM_RSRC2_HS.TG_SIZE_EN`, domain stream-out (`SPI_SHADER_PGM_RSRC2_VS.SO_EN` or `SO_BASE*_EN`) and a local shader that loads InstanceID / `VGT_INSTANCE_STEP_RATE_0` other than 1 throw. `DYNAMIC_HS` and the `VGT_TF_PARAM` fields `NUM_DS_WAVES_PER_SIMD` and `RDREQ_POLICY` are taken as scheduling and cache hints with no effect on the result. From 74ddfc40e9004b737ce4de8fe4f8299ec42a3966 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:46:33 -0500 Subject: [PATCH 02/34] fix(agc): bump the pipeline journal format for the tessellation on-chip byte Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp index 75adc03cebaa..7926a3dce72c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp @@ -56,7 +56,7 @@ static_assert(sizeof(ShaderRecompiler::TessellationConfiguration) == 40, "Tessel constexpr std::uint32_t FileMagic = 0x4c4a5041u; // Bumped when the recipe codec, CanonicalPipelineState or the store key change in a way the // layout guards above do not catch (a field renumbered or reinterpreted at the same size). -constexpr std::uint32_t FileFormat = 19u; +constexpr std::uint32_t FileFormat = 20u; constexpr std::uint32_t ModuleRecord = 1u; constexpr std::uint32_t GraphicsRecord = 2u; constexpr std::uint32_t ComputeRecord = 3u; From 74f63257aa6f9d202b94618ea3ab9e6ef88f2ed0 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 06:19:38 -0500 Subject: [PATCH 03/34] feat(shader): lower PS4 on-chip tessellation LDS through the off-chip ring With SPI_SHADER_PGM_RSRC2_HS.OC_LDS_EN clear a GCN hull shader keeps its output control points and patch constants in LDS, and the domain shader reads them there. The offsets come from the tessellation constant buffer, a V# in four user data words laid out as shadPS4's TessellationDataConstantBuffer, so the lowering refused them. The lowering now finds the constant buffer that on-chip LDS addresses read and throws TessellationConstantsRequired naming its user data words when the request carries no values. The driver then reads its nine dwords from guest memory, remembers the words for that program, and prepares the stage again with GraphicsCompileContext.tessellationConstants, which is part of the shader key and the serialized request (version 64). The lowering replaces the buffer's reads with those values, so the addresses become affine. Hull writes and domain reads at or above hs_output_base become off-chip ring accesses rebased by it, and the existing ring lowering places control points and patch constants. A hull with hs_output_base 0 is pass-through: each invocation copies its input control point to its output control point. Co-Authored-By: Claude Opus 5.5 --- .../include/Driver/Shaders/ShaderRegistry.hpp | 1 + .../Execution/src/Driver/Draw/Draw.cpp | 5 +- .../Execution/src/Driver/Draw/DrawCapture.cpp | 57 ++++++- .../src/Driver/Shaders/ShaderDiagnostics.cpp | 3 + .../tests/execution/GcnTessellation.cpp | 84 ++++++++++- core/shader/recompiler/CacheKey.hpp | 1 + .../ControlFlow/src/RequestSerializer.cpp | 15 +- .../Optimization/ShaderStageInputInfo.hpp | 2 + .../Optimization/TessellationLowering.hpp | 12 ++ .../Optimization/src/TessellationLowering.cpp | 140 +++++++++++++++++- core/shader/recompiler/Recompiler.cpp | 9 +- core/shader/recompiler/Recompiler.hpp | 3 + .../tests/RequestSerializerTests.cpp | 36 ++++- .../claude-gcn-ls-hs-vs-tessellation.md | 2 +- 14 files changed, 345 insertions(+), 25 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp index f1419567989f..91c1427cd272 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Shaders/ShaderRegistry.hpp @@ -193,6 +193,7 @@ struct PreparedShaders : PreparedShaderState { bool pending = false; std::vector convertedSamples; std::vector layerRowSamples; + std::vector> tessellationConstants; }; class SharedCode { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 03de50683e76..fc6d1afa69a5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -681,7 +681,8 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe stageData.resize(programs.size()); auto& drawHit = tail.drawHit; auto& verifyHit = tail.verifyHit; - tail.stageEntries = useDrawEntries && !(graphics.stages.tessellation && !drawParameters.indirect && drawParameters.instanceCount > 1u); + const bool onChipTessellation = graphics.stages.tessellation && graphics.stages.tessellation->onChip; + tail.stageEntries = useDrawEntries && !onChipTessellation && !(graphics.stages.tessellation && !drawParameters.indirect && drawParameters.instanceCount > 1u); const bool stageEntries = tail.stageEntries; try { lookupDraw(submission, localDevice, graphics, pixel, programs, roles, vertexInfos, stageEntries, registerKey, profile, drawKey, entry, matched, matchedRegions, drawHit, verifyHit, phaseTiming, phaseMs, dataEntry, dataCandidates, stageData); @@ -1364,7 +1365,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { } std::vector> recipeStages; - if (registerKey && !drawParameters.indirect && !patchedStages && !graphics.stages.tessellationGeometry && Graphics::DrawRecipes()) { + if (registerKey && !drawParameters.indirect && !patchedStages && !graphics.stages.tessellationGeometry && !(graphics.stages.tessellation && graphics.stages.tessellation->onChip) && Graphics::DrawRecipes()) { recipeStages.reserve(programs.size()); for (std::size_t i = 0; i < programs.size(); ++i) recipeStages.push_back(drawHit ? (matched[i] != nullptr && matched[i]->donor != nullptr ? matched[i]->donor : matched[i]) : fresh[i]); if (std::all_of(recipeStages.begin(), recipeStages.end(), [](const std::shared_ptr& variant) { return variant == nullptr; })) recipeStages.clear(); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 3658ba6a71ca..9ca97ce18fa1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -6,12 +6,15 @@ #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Execution/include/Pm4.hpp" #include "Optimization/ResourceProgram.hpp" +#include "Optimization/TessellationLowering.hpp" #include +#include #include #include #include #include #include +#include #include #include #include @@ -22,6 +25,35 @@ namespace AgcDriver::DriverDetail { namespace { +std::array ReadTessellationConstants(std::span userData, std::uint32_t word) { + require(word + 4u <= userData.size(), "the tessellation constant buffer's V# lies past the stage's user data"); + const auto base = static_cast(userData[word]) | (static_cast(userData[word + 1u] & 0xffffu) << 32u); + const auto stride = (userData[word + 1u] >> 16u) & 0x3fffu; + const auto size = stride == 0u ? static_cast(userData[word + 2u]) : static_cast(stride) * userData[word + 2u]; + std::array constants{}; + for (std::uint32_t index = 0; index < constants.size(); ++index) { + if (4u * index + 4u > size) break; + GuestMemory::Read(base + 4u * index, std::as_writable_bytes(std::span(&constants[index], 1u)), 4u); + } + return constants; +} + +std::optional TessellationConstantWord(const ShaderSnapshot& snapshot, std::size_t codeOffset) { + std::lock_guard lock(snapshot.prepared->mutex); + for (const auto& [offset, word] : snapshot.prepared->tessellationConstants) { + if (offset == codeOffset) return word; + } + return std::nullopt; +} + +void RecordTessellationConstantWord(const ShaderSnapshot& snapshot, std::size_t codeOffset, std::uint32_t word) { + std::lock_guard lock(snapshot.prepared->mutex); + for (const auto& [offset, known] : snapshot.prepared->tessellationConstants) { + if (offset == codeOffset) return; + } + snapshot.prepared->tessellationConstants.emplace_back(codeOffset, word); +} + void TraceMaterializationFailure(std::uint64_t token, const Submission& submission, std::size_t packetOffset, std::size_t stage, const char* phase, const std::exception_ptr& failure) { if (token == 0) return; const char* type = "unknown"; @@ -179,10 +211,23 @@ std::shared_ptr Driver::materializeDraw {0, 0, pushOffset, pushBytes}, ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, Graphics::StageMeshConfiguration(graphics.stages, program.binary.stage), graphics.stages.tessellation, {drawParameters.indexAddress, drawParameters.indexCount, drawParameters.indexSize, drawParameters.instanceCount}, program.binary.stage == Stage::Mesh ? meshBarycentrics : std::nullopt} }; + if (request.graphics->tessellation && request.graphics->tessellation->onChip && (program.binary.stage == Stage::TessellationControl || program.binary.stage == Stage::TessellationEvaluation)) { + if (const auto word = TessellationConstantWord(*program.snapshot, program.codeOffset)) request.graphics->tessellationConstants = ReadTessellationConstants(program.userData, *word); + } + const auto pinTessellationConstants = [&](const ShaderRecompiler::TessellationConstantsRequired& required) { + if (request.graphics->tessellationConstants) throw required; + RecordTessellationConstantWord(*program.snapshot, program.codeOffset, required.UserDataWord()); + request.graphics->tessellationConstants = ReadTessellationConstants(program.userData, required.UserDataWord()); + }; const auto waitedBefore = traceCapSync() || profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; auto invocation = [&] { try { - return InvocationFor(*program.snapshot, program.codeOffset, request, AsyncDrawCompile()); + try { + return InvocationFor(*program.snapshot, program.codeOffset, request, AsyncDrawCompile()); + } catch (const ShaderRecompiler::TessellationConstantsRequired& required) { + pinTessellationConstants(required); + return InvocationFor(*program.snapshot, program.codeOffset, request, AsyncDrawCompile()); + } } catch (const DrawCompilePending&) { throw; } catch (...) { @@ -213,7 +258,15 @@ std::shared_ptr Driver::materializeDraw const auto capture = [&] { const SampledReadScope sampling(evidenceReads); try { - return CaptureInvocation(shaderMemory, *program.snapshot, program.codeOffset, request, invocation); + try { + return CaptureInvocation(shaderMemory, *program.snapshot, program.codeOffset, request, invocation); + } catch (const ShaderRecompiler::TessellationConstantsRequired& required) { + pinTessellationConstants(required); + invocation = InvocationFor(*program.snapshot, program.codeOffset, request, AsyncDrawCompile()); + return CaptureInvocation(shaderMemory, *program.snapshot, program.codeOffset, request, invocation); + } + } catch (const DrawCompilePending&) { + throw; } catch (const std::exception& error) { throw named(error, shaderMemory.Regions()); } diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderDiagnostics.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderDiagnostics.cpp index 6dbe187d297d..693f6407d59a 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderDiagnostics.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderDiagnostics.cpp @@ -2,6 +2,7 @@ #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" #include "ControlFlow/RequestSerializer.hpp" #include "Optimization/ResourceProgram.hpp" +#include "Optimization/TessellationLowering.hpp" #include #include #include @@ -81,6 +82,8 @@ std::shared_ptr PrepareShaderWithDiagnosti } try { std::rethrow_exception(failure); + } catch (const ShaderRecompiler::TessellationConstantsRequired&) { + throw; } catch (const std::exception& error) { std::ostringstream where; where << "shader 0x" << std::hex << request.shader.codeAddress << " stage " << static_cast(request.shader.stage); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp index 4d55750f8f30..7f40b679caf6 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp @@ -2,6 +2,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" #include "Recompiler.hpp" +#include "Optimization/TessellationLowering.hpp" #include "RdnaDecoder/RdnaInstructionDecoder.hpp" #include "VulkanTestDevice.hpp" #include @@ -71,6 +72,44 @@ alignas(256) constexpr std::array GcnDomainOnChipLds{ 0xbf810000, }; +alignas(256) constexpr std::array GcnHullOnChipPassthrough{ + 0xbefc03c1, 0xc2c60500, 0xd2900002, 0x02151101, 0xd2900003, 0x02210101, 0xbf8c007f, 0x7d840480, + 0xbe86246a, 0x36100081, 0x7e100d08, 0x081010f2, 0x34120684, 0xe0701000, 0x08000809, 0xe0701004, + 0x08000809, 0xe0701008, 0x08000809, 0xe070100c, 0x08000809, 0x7e140211, 0xd286000a, 0x04282103, + 0x7e1602f2, 0xd8340000, 0x00000b0a, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnHullOnChipOutputs{ + 0xbefc03c1, 0xc2c60500, 0xd2900002, 0x02151101, 0xd2900003, 0x02210101, 0xbf8c007f, 0x34080484, + 0xd2860005, 0x04116103, 0xd8d80000, 0x06000005, 0xd8d80004, 0x07000005, 0x7e28020f, 0xd2860014, + 0x04502503, 0xd2860014, 0x04501b02, 0xbf8c007f, 0xd8340000, 0x00000614, 0xd8340004, 0x00000714, + 0x7d840480, 0xbe86246a, 0x36100081, 0x7e100d08, 0x081010f2, 0x34120684, 0xe0701000, 0x08000809, + 0xe0701004, 0x08000809, 0xe0701008, 0x08000809, 0xe070100c, 0x08000809, 0x7e140211, 0xd286000a, + 0x04282103, 0x7e1602f2, 0xd8340000, 0x00000b0a, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnDomainOnChipInputs{ + 0xbefc03c1, 0xc2c20100, 0xbf8c007f, 0x7e080207, 0xd2860004, 0x04101502, 0xd8d80000, 0x05000004, + 0xd8d80004, 0x06000004, 0xd8d80010, 0x07000004, 0xd8d80014, 0x08000004, 0xd8d80020, 0x09000004, + 0xd8d80024, 0x0a000004, 0x7e180209, 0xd286000c, 0x04301102, 0xd8d80000, 0x0d00000c, 0xbf8c007f, + 0x081600f2, 0x0816030b, 0x101c0b00, 0x3e1c0f01, 0x3e1c130b, 0x101c1b0e, 0x101e0d00, 0x3e1e1101, + 0x3e1e150b, 0x101e1b0f, 0x7e200280, 0x7e2202f2, 0xf80008cf, 0x11100f0e, 0xf800020f, 0x11111111, + 0xbf810000, +}; + +alignas(256) constexpr std::array GcnDomainOnChipOffsetInputs{ + 0xbefc03c1, 0xc2c20100, 0xbf8c007f, 0xd2860004, 0x02001502, 0xd8d800c0, 0x05000004, 0xd8d800c4, + 0x06000004, 0xd8d800d0, 0x07000004, 0xd8d800d4, 0x08000004, 0xd8d800e0, 0x09000004, 0xd8d800e4, + 0x0a000004, 0x7e180209, 0xd286000c, 0x04301102, 0xd8d80000, 0x0d00000c, 0xbf8c007f, 0x081600f2, + 0x0816030b, 0x101c0b00, 0x3e1c0f01, 0x3e1c130b, 0x101c1b0e, 0x101e0d00, 0x3e1e1101, 0x3e1e150b, + 0x101e1b0f, 0x7e200280, 0x7e2202f2, 0xf80008cf, 0x11100f0e, 0xf800020f, 0x11111111, 0xbf810000, +}; + +using Constants = std::array; + +alignas(16) constexpr Constants PassthroughConstants{16u, 16u, 4u, 0u, 16u, 192u, 48u, 0u, 0u}; +alignas(16) constexpr Constants OutputConstants{16u, 16u, 4u, 192u, 16u, 384u, 48u, 0u, 0u}; + alignas(256) constexpr std::array PixelCode{ 0xc8020002, 0xc8060102, 0xc80a0202, 0xc80e0302, 0xf800180f, 0x03020100, 0xbf810000, }; @@ -87,6 +126,16 @@ alignas(256) constexpr std::array Indices{ constexpr std::array RingUserData{0x1000u, 0u, 0u, 0u}; +std::array ConstantBuffer(const Constants& constants) { + const auto address = reinterpret_cast(constants.data()); + return {static_cast(address), static_cast(address >> 32u) & 0xffffu, static_cast(sizeof(Constants)), 0x00027facu}; +} + +std::array HullUserData(const Constants& constants) { + const auto buffer = ConstantBuffer(constants); + return {RingUserData[0], RingUserData[1], RingUserData[2], RingUserData[3], buffer[0], buffer[1], buffer[2], buffer[3]}; +} + TessellationConfiguration Patches(bool onChip) { TessellationConfiguration configuration{3u, 3u, 1u, 0u, 2u, 4u}; configuration.onChip = onChip; @@ -100,9 +149,9 @@ struct Stages { ShaderRecompiler::RecompileResult fragment; }; -ShaderRecompiler::RecompileResult Compile(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, std::uint32_t& pushCursor, const TessellationConfiguration& configuration) { +ShaderRecompiler::RecompileResult Compile(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, std::uint32_t& pushCursor, const TessellationConfiguration& configuration, std::span stageUserData = {}, const std::optional& constants = std::nullopt) { const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; - const auto userData = stage == ShaderStage::TessellationControl || stage == ShaderStage::TessellationEvaluation ? std::span(RingUserData) : std::span(); + const auto userData = !stageUserData.empty() ? stageUserData : stage == ShaderStage::TessellationControl || stage == ShaderStage::TessellationEvaluation ? std::span(RingUserData) : std::span(); std::optional pixel; std::optional vertex; std::optional graphics; @@ -127,11 +176,23 @@ ShaderRecompiler::RecompileResult Compile(const ShaderRecompiler::SpirvTarget& t graphics }; request.useCache = false; + if (request.graphics) request.graphics->tessellationConstants = constants; auto result = ShaderRecompiler::Recompile(request); pushCursor += static_cast(result.pushConstants.size()); return result; } +void ExpectConstantsRequired(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, std::span userData, std::uint32_t word) { + std::uint32_t cursor = 0; + try { + static_cast(Compile(target, stage, code, cursor, Patches(true), userData)); + } catch (const ShaderRecompiler::TessellationConstantsRequired& required) { + Require(required.UserDataWord() == word, "the tessellation constant buffer was asked for at user data word " + std::to_string(required.UserDataWord()) + ", expected " + std::to_string(word)); + return; + } + Require(false, "an on-chip GCN tessellation program that addresses LDS through the tessellation constant buffer compiled without its constants"); +} + void ExpectRefusal(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, const std::string& reason) { std::uint32_t cursor = 0; try { @@ -198,14 +259,18 @@ void Draw(AgcDriver::VulkanDevice& device, const Stages& stages, const Tessellat device.WaitIdle(); } -void RequirePatches(AgcDriver::VulkanDevice& device, std::span hull, std::span domain, bool onChip, const std::string& program) { +void RequirePatches(AgcDriver::VulkanDevice& device, std::span hull, std::span domain, bool onChip, const std::string& program, const std::optional& constants = std::nullopt) { const auto target = device.Target(); const auto configuration = Patches(onChip); + const auto hullUsers = constants ? HullUserData(*constants) : std::array{}; + const auto domainUsers = constants ? ConstantBuffer(*constants) : std::array{}; + const auto hullData = constants ? std::span(hullUsers) : std::span(); + const auto domainData = constants ? std::span(domainUsers) : std::span(); std::uint32_t cursor = 0; Stages stages{ Compile(target, ShaderStage::Local, GcnLocal, cursor, configuration), - Compile(target, ShaderStage::TessellationControl, hull, cursor, configuration), - Compile(target, ShaderStage::TessellationEvaluation, domain, cursor, configuration), + Compile(target, ShaderStage::TessellationControl, hull, cursor, configuration, hullData, constants), + Compile(target, ShaderStage::TessellationEvaluation, domain, cursor, configuration, domainData, constants), Compile(target, ShaderStage::Fragment, PixelCode, cursor, configuration), }; Draw(device, stages, configuration); @@ -284,7 +349,14 @@ int main() { RequirePatches(*device, GcnHullOffChip, GcnDomainOffChip, false, "GCN off-chip LS-HS-VS draw"); RequirePatches(*device, GcnHullOnChip, GcnDomainOnChip, true, "GCN on-chip LS-HS-VS draw"); ExpectRefusal(target, ShaderStage::TessellationControl, GcnHullOnChipLds, "keeps its outputs on chip"); - ExpectRefusal(target, ShaderStage::TessellationEvaluation, GcnDomainOnChipLds, "reads them from LDS"); + ExpectRefusal(target, ShaderStage::TessellationEvaluation, GcnDomainOnChipLds, "reads LDS at an address that does not come from the tessellation constant buffer"); + RequirePatches(*device, GcnHullOnChipPassthrough, GcnDomainOnChipInputs, true, "GCN on-chip pass-through LS-HS-VS draw through LDS", PassthroughConstants); + RequirePatches(*device, GcnHullOnChipOutputs, GcnDomainOnChipInputs, true, "GCN on-chip LS-HS-VS draw with hull output control points in LDS", OutputConstants); + RequirePatches(*device, GcnHullOnChipOutputs, GcnDomainOnChipOffsetInputs, true, "GCN on-chip LS-HS-VS draw whose domain shader reaches the hull output control points through its LDS instruction offset", OutputConstants); + const auto hullUsers = HullUserData(PassthroughConstants); + const auto domainUsers = ConstantBuffer(PassthroughConstants); + ExpectConstantsRequired(target, ShaderStage::TessellationControl, GcnHullOnChipPassthrough, hullUsers, 4u); + ExpectConstantsRequired(target, ShaderStage::TessellationEvaluation, GcnDomainOnChipInputs, domainUsers, 0u); ShaderRecompiler::SetGcnGuestShaders(false); device.reset(); std::puts("GCN tessellation tests passed"); diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index 78aba8d27fd5..0b08d211cad8 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -150,6 +150,7 @@ class RecompileCacheKey { if (request.shader.stage != ShaderStage::TessellationEvaluation) append(key, tessellation->mergedHull); append(key, tessellation->onChip); if (request.shader.stage == ShaderStage::Local) return; + append(key, request.graphics->tessellationConstants); append(key, tessellation->patchesPerGroup); append(key, tessellation->primitiveGroupSize); append(key, TessellationInstancePatches(request)); diff --git a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp index 15115f418c49..cafee4c71efd 100644 --- a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp +++ b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp @@ -916,7 +916,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const std::string buffer; Writer writer(buffer); writer.WriteU32(0x41505335u); - writer.WriteU32(63u); + writer.WriteU32(64u); writeShaderBinary(writer, request.shader); writeGuestContext(writer, request.context); writeSpirvTarget(writer, request.target); @@ -971,6 +971,13 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const writer.WriteBool(request.target.fixedPushSlots); writer.WriteBool(request.target.spannedAnySubgroup); if (request.graphics && request.graphics->tessellation) writer.WriteBool(request.graphics->tessellation->onChip); + if (request.graphics && request.graphics->tessellation) { + const auto& constants = request.graphics->tessellationConstants; + writer.WriteBool(constants.has_value()); + if (constants) { + for (const auto word : *constants) writer.WriteU32(word); + } + } return base64Encode(buffer); } @@ -979,7 +986,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const Reader reader(decoded); if (reader.ReadU32() != 0x41505335u) throw std::runtime_error("invalid recompile request signature"); const auto version = reader.ReadU32(); - if (version < 1u || version > 63u || version == 50u || (version >= 58u && version <= 61u)) throw std::runtime_error("unsupported recompile request serialization version"); + if (version < 1u || version > 64u || version == 50u || (version >= 58u && version <= 61u)) throw std::runtime_error("unsupported recompile request serialization version"); DeserializedRequest result{}; result.request.shader = readShaderBinary(reader, result.shaderCode, result.shaderHeader); result.request.context = readGuestContext(reader, result, version); @@ -1056,6 +1063,10 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const } if (version >= 62u) result.request.target.spannedAnySubgroup = reader.ReadBool(); if (version >= 63u && result.request.graphics && result.request.graphics->tessellation) result.request.graphics->tessellation->onChip = reader.ReadBool(); + if (version >= 64u && result.request.graphics && result.request.graphics->tessellation && reader.ReadBool()) { + auto& constants = result.request.graphics->tessellationConstants.emplace(); + for (auto& word : constants) word = reader.ReadU32(); + } if (version >= 21u && reader.Remaining() != 0u) throw std::runtime_error("RequestSerializer: unexpected trailing data"); return result; } diff --git a/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp b/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp index c0a283b4d2bd..e883de440a0d 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp @@ -117,6 +117,8 @@ struct ShaderTessellationInputInfo { bool drawParameters = false; bool mergedHull = false; bool onChip = false; + std::optional> constants; + std::uint32_t userDataBase = 0; std::uint32_t geometryItemDwords = 0; }; diff --git a/core/shader/recompiler/Optimization/include/Optimization/TessellationLowering.hpp b/core/shader/recompiler/Optimization/include/Optimization/TessellationLowering.hpp index 7032578c3b91..e09ded1ea547 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/TessellationLowering.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/TessellationLowering.hpp @@ -4,9 +4,21 @@ #include "IntermediateRepresentation/IrProgram.hpp" #include "Optimization/ShaderStageInputInfo.hpp" #include "Recompiler.hpp" +#include +#include +#include namespace ShaderRecompiler { +class TessellationConstantsRequired : public std::runtime_error { +public: + TessellationConstantsRequired(std::uint32_t userDataWord, const std::string& reason) : std::runtime_error(reason), word(userDataWord) {} + [[nodiscard]] std::uint32_t UserDataWord() const noexcept { return word; } + +private: + std::uint32_t word; +}; + class TessellationLowering { public: void Lower(IrProgram& program, const ShaderTessellationInputInfo& tessellation, const TessellationTargetLimits* limits = nullptr) const; diff --git a/core/shader/recompiler/Optimization/src/TessellationLowering.cpp b/core/shader/recompiler/Optimization/src/TessellationLowering.cpp index 6323df2dfddc..6de673e0c127 100644 --- a/core/shader/recompiler/Optimization/src/TessellationLowering.cpp +++ b/core/shader/recompiler/Optimization/src/TessellationLowering.cpp @@ -803,6 +803,7 @@ class Lowering { evaluator(stage == IrShaderStage::TessellationControl ? tessellation.outputControlPoints : capture ? 1u : 0u, stage == IrShaderStage::Local ? LocalVertexIndexCount : static_cast(tessellation.patchesPerGroup), capture), localStride(program.Metadata().tessellationLocalStride) {} void Run() { + pinConstants(); if (merged) { if (tessellation.inputControlPoints > tessellation.outputControlPoints) Fail("a merged hull program with more input than output control points runs its local part on lanes the hull stage does not have", 0u); requireUniformBarriers(); @@ -815,6 +816,7 @@ class Lowering { derive(); orderControlOutputReads(); for (const auto& access : accesses) rewrite(access); + if (passthrough) copyInputControlPoints(); if (stage == IrShaderStage::TessellationEvaluation) removePrimitiveExports(); constexpr DeadCodeEliminator deadCodeEliminator; deadCodeEliminator.Eliminate(program); @@ -1013,12 +1015,16 @@ class Lowering { access.kind = TessellationAttribute::ControlShared; } else if (capture && access.write) { access.kind = TessellationAttribute::GeometryOutput; + } else if (onChip() && stage == IrShaderStage::TessellationEvaluation && access.write) { + Fail("a domain shader that reads hull outputs on chip (SPI_SHADER_PGM_RSRC2_VS.OC_LDS_EN=0) writes LDS", flags.pc); + } else if (onChip() && (access.write || stage == IrShaderStage::TessellationEvaluation) && !layout) { + Fail(stage == IrShaderStage::TessellationControl ? "a hull shader that keeps its outputs on chip (SPI_SHADER_PGM_RSRC2_HS.OC_LDS_EN=0) writes LDS at an address that does not come from the tessellation constant buffer" : "a domain shader that reads hull outputs on chip (SPI_SHADER_PGM_RSRC2_VS.OC_LDS_EN=0) reads LDS at an address that does not come from the tessellation constant buffer", flags.pc); + } else if (onChip() && stage == IrShaderStage::TessellationEvaluation) { + access.kind = TessellationAttribute::EvaluationInput; } else if (stage == IrShaderStage::TessellationControl && !access.write) { access.kind = TessellationAttribute::ControlInput; - } else if (tessellation.onChip && stage == IrShaderStage::TessellationControl) { - Fail("a hull shader that keeps its outputs on chip (SPI_SHADER_PGM_RSRC2_HS.OC_LDS_EN=0) writes them to LDS, which is not implemented", flags.pc); - } else if (tessellation.onChip && stage == IrShaderStage::TessellationEvaluation) { - Fail("a domain shader that reads hull outputs on chip (SPI_SHADER_PGM_RSRC2_VS.OC_LDS_EN=0) reads them from LDS, which is not implemented", flags.pc); + } else if (onChip()) { + access.kind = TessellationAttribute::ControlOutput; } else { Fail("unsupported LDS access in a tessellation stage", flags.pc); } @@ -1047,6 +1053,7 @@ class Lowering { } access.memoryOffset = memory.offset; access.address.constant += memory.offset; + if (onChip() && layout && shared != SharedAccess::None && address != nullptr) placeOnChip(access); if ((access.address.constant & (access.half ? 1 : 3)) != 0 || (access.half && access.kind != TessellationAttribute::LocalOutput && access.kind != TessellationAttribute::ControlInput && access.kind != TessellationAttribute::ControlShared)) Fail("unaligned tessellation ring or LDS address", flags.pc); accesses.push_back(access); } @@ -1059,6 +1066,10 @@ class Lowering { } void derive() { + if (passthrough) { + agree(localStride, layout->localStride, 0u); + agree(controlStride, layout->localStride, 0u); + } const auto inputs = static_cast(tessellation.inputControlPoints); const auto outputs = static_cast(tessellation.outputControlPoints); const auto soleControlPoint = [&](const Access& access) { @@ -1491,6 +1502,119 @@ class Lowering { return result; } + [[nodiscard]] bool onChip() const { + return tessellation.onChip && (stage == IrShaderStage::TessellationControl || stage == IrShaderStage::TessellationEvaluation); + } + + std::optional constantBufferWord(const IrValue* read) const { + const IrValue* handle = read->Argument(0)->Resolve(); + if (handle->Opcode() != IrOpcode::GetBufferResource || handle->ArgumentCount() != 4u) return std::nullopt; + std::optional first; + for (std::uint32_t word = 0; word < 4u; ++word) { + const IrValue* part = handle->Argument(word)->Resolve(); + if (part->Opcode() != IrOpcode::GetUserData) return std::nullopt; + const auto reg = RegIndex(static_cast(part->Argument(0)->Register().index)); + if (reg < tessellation.userDataBase) return std::nullopt; + if (!first) first = reg - tessellation.userDataBase; + if (reg - tessellation.userDataBase != *first + word) return std::nullopt; + } + return first; + } + + void pinConstants() { + if (!onChip()) return; + const auto& memoryInfo = program.Resources().memoryInfo; + std::vector pending; + for (IrBlock* block : program.BlockOrder()) { + for (IrValue* inst : block->Instructions()) { + if (SharedAccessOf(inst->Opcode()) == SharedAccess::None || memoryInfo.at(inst->Flags().index).kind != ResourceKind::Lds) continue; + pending.push_back(inst->Argument(0)->Resolve()); + } + } + std::unordered_set visited; + std::optional buffer; + while (!pending.empty()) { + IrValue* value = pending.back(); + pending.pop_back(); + if (value == nullptr || value->HasImmediate() || !visited.insert(value).second) continue; + if (value->Opcode() == IrOpcode::ReadConstBuffer) { + const auto word = constantBufferWord(value); + if (!word) Fail("an on-chip LDS address reads a constant buffer whose V# is not four consecutive user data words", value->Flags().pc); + if (buffer && *buffer != *word) Fail("on-chip LDS addresses read more than one constant buffer", value->Flags().pc); + buffer = word; + continue; + } + for (std::size_t index = 0; index < value->ArgumentCount(); ++index) { + if (IrValue* argument = value->Argument(index)) pending.push_back(argument->Resolve()); + } + } + if (!buffer) return; + if (!tessellation.constants) { + char text[160]; + std::snprintf(text, sizeof(text), "tessellation lowering: on-chip LDS addresses read the tessellation constant buffer in user data words %u-%u", *buffer, *buffer + 3u); + throw TessellationConstantsRequired(*buffer, text); + } + const auto& words = *tessellation.constants; + for (IrBlock* block : program.BlockOrder()) { + for (IrValue* inst : block->Instructions()) { + if (inst->Opcode() != IrOpcode::ReadConstBuffer || constantBufferWord(inst) != buffer) continue; + const IrValue* offset = inst->Argument(1)->Resolve(); + if (!offset->HasImmediate() || offset->Type() != IrType::U32) continue; + const auto bytes = static_cast(memoryInfo.at(inst->Flags().index).offset) + offset->ImmediateU32(); + if (bytes / 4u >= words.size()) continue; + inst->ReplaceAllUsesWith(&constant(words[bytes / 4u])); + } + } + layout = OnChipLayout{words[0], words[1], words[3]}; + passthrough = stage == IrShaderStage::TessellationControl && layout->outputBase == 0u && layout->localStride != 0u; + if (passthrough && layout->localStride != layout->controlStride) Fail("a pass-through hull shader on chip has an output control point stride other than its input stride", 0u); + if (passthrough && tessellation.inputControlPoints != tessellation.outputControlPoints) Fail("a pass-through hull shader on chip has other than as many output as input control points", 0u); + if ((layout->outputBase & 3u) != 0u) Fail("the hull shader's on-chip output control points start at an unaligned LDS offset", 0u); + } + + void placeOnChip(Access& access) { + const auto base = static_cast(layout->outputBase); + const auto end = evaluator.Highest(access.address) + (access.half ? 2 : 4 * static_cast(access.components)); + if (access.kind == TessellationAttribute::ControlInput) { + if (layout->outputBase == 0u || end <= base) return; + if (evaluator.Lowest(access.address) < base) Fail("a hull shader reads LDS across its input and output control points on chip", access.pc); + access.kind = TessellationAttribute::ControlOutput; + } + if (evaluator.Lowest(access.address) < base) Fail(stage == IrShaderStage::TessellationControl ? "a hull shader writes LDS below its on-chip output control points" : "a domain shader reads LDS below the hull shader's on-chip output control points", access.pc); + if (base == 0) return; + access.address.constant -= base; + if (!access.address.dynamic) return; + IrValue& rebased = program.CreateValue(IrOpcode::ISub32, IrType::U32); + rebased.AddArgument(access.addressValue); + rebased.AddArgument(&constant(layout->outputBase)); + access.block->InsertInstructionBefore(access.inst, &rebased); + access.addressValue = &rebased; + } + + void copyInputControlPoints() { + IrBlock& entry = *program.BlockOrder().front(); + IrValue* first = entry.Instructions().empty() ? nullptr : entry.Instructions().front(); + const auto emit = [&](IrOpcode opcode, IrType type, std::initializer_list arguments) -> IrValue& { + IrValue& value = program.CreateValue(opcode, type); + for (IrValue* argument : arguments) value.AddArgument(argument); + if (first != nullptr) { + entry.InsertInstructionBefore(first, &value); + } else { + entry.AppendInstruction(&value); + } + return value; + }; + IrValue& always = program.CreateValue(IrOpcode::Void, IrType::Bool); + always.SetImmediateBool(true); + IrValue& invocation = emit(IrOpcode::GetBuiltin, IrType::U32, {&constant(static_cast(StageInputKind::InvocationId)), &constant(0u)}); + IrValue& point = emit(IrOpcode::IMul32, IrType::U32, {&invocation, &constant(layout->localStride)}); + for (std::uint32_t offset = 0; offset < layout->localStride; offset += 4u) { + IrValue& address = emit(IrOpcode::IAdd32, IrType::U32, {&point, &constant(offset)}); + IrValue& value = emit(IrOpcode::GetTessellationAttribute, IrType::U32, {&constant(static_cast(TessellationAttribute::ControlInput)), &address, &always}); + static_cast(emit(IrOpcode::SetTessellationAttribute, IrType::Void, {&constant(static_cast(TessellationAttribute::ControlOutput)), &constant(offset), &value, &always})); + } + } + [[nodiscard]] bool restartsPerInstance() const { const auto patches = tessellation.instancePatches; const auto group = tessellation.primitiveGroupSize; @@ -1653,10 +1777,18 @@ class Lowering { std::vector accesses; enum class Dependence : std::uint8_t { Visiting, No, Yes }; + struct OnChipLayout { + std::uint32_t localStride; + std::uint32_t controlStride; + std::uint32_t outputBase; + }; + std::uint32_t localStride; std::uint32_t controlStride = 0; std::uint32_t patchStride = 0; std::uint32_t sharedStride = 0; + std::optional layout; + bool passthrough = false; std::map, Dependence> dependence; }; diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 210237cc8750..b4208766822d 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -380,7 +380,10 @@ IrProgram PrepareResourceProgram(const RecompileRequest& request, ShaderPreparat if (inputInfo.vertex != nullptr) { constexpr TessellationLowering tessellationLowering; - tessellationLowering.Lower(program, inputInfo.vertex->tess, request.target.tessellation ? &*request.target.tessellation : nullptr); + auto tessellation = inputInfo.vertex->tess; + tessellation.constants = request.graphics ? request.graphics->tessellationConstants : std::nullopt; + tessellation.userDataBase = request.context.userDataBaseRegister; + tessellationLowering.Lower(program, tessellation, request.target.tessellation ? &*request.target.tessellation : nullptr); } deadCodeEliminator.EliminateUnobservedPhis(program); @@ -1707,6 +1710,8 @@ auto CountedCompile(Compile&& compile) { return result; } catch (const ConvertedSampleRequired&) { throw; + } catch (const TessellationConstantsRequired&) { + throw; } catch (const std::exception&) { NoteFailureOnce(); throw; @@ -2330,6 +2335,8 @@ auto recompileReporting(const RecompileRequest& request, Impl&& impl) -> decltyp return impl(); } catch (const ConvertedSampleRequired&) { throw; + } catch (const TessellationConstantsRequired&) { + throw; } catch (const std::exception& e) { NoteFailureOnce(); constexpr auto requestSerializer = RequestSerializer{}; diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 43f284af69ed..9e1e84fbea31 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -498,6 +498,8 @@ struct MeshBarycentricLayout { bool operator==(const MeshBarycentricLayout&) const = default; }; +inline constexpr std::uint32_t TessellationConstantWords = 9; + struct GraphicsCompileContext { std::uint32_t firstUserSgpr; std::span linkedPrograms; @@ -505,6 +507,7 @@ struct GraphicsCompileContext { std::optional tessellation; GraphicsDrawParameters draw; std::optional meshBarycentrics; + std::optional> tessellationConstants; }; struct RecompileRequest { diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index 3f72177e7547..41b07102f8e4 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -207,23 +207,45 @@ void VerifyTessellationOnChip() { request.graphics->tessellation->onChip = onChip; const auto encoded = serializer.Serialize(request); const auto replay = serializer.Deserialize(encoded); - Require(replay.request.graphics && replay.request.graphics->tessellation && replay.request.graphics->tessellation->onChip == onChip); + Require(replay.request.graphics && replay.request.graphics->tessellation && replay.request.graphics->tessellation->onChip == onChip && !replay.request.graphics->tessellationConstants); Require(serializer.Serialize(replay.request) == encoded); auto version62 = DecodeBase64(encoded); - Require(version62[4] == 63u && version62.back() == (onChip ? 1u : 0u)); + Require(version62[4] == 64u && version62.back() == 0u && version62[version62.size() - 2u] == (onChip ? 1u : 0u)); + version62.pop_back(); + version62[4] = 63u; + const auto replay63 = serializer.Deserialize(EncodeBase64(version62)); + Require(replay63.request.graphics && replay63.request.graphics->tessellation && replay63.request.graphics->tessellation->onChip == onChip && !replay63.request.graphics->tessellationConstants); version62.pop_back(); version62[4] = 62u; const auto replay62 = serializer.Deserialize(EncodeBase64(version62)); Require(replay62.request.graphics && replay62.request.graphics->tessellation && !replay62.request.graphics->tessellation->onChip); } + ShaderRecompiler::RecompileRequest request{}; + request.graphics.emplace(); + request.graphics->tessellation = ShaderRecompiler::TessellationConfiguration{1u, 1u, 2u, 0u, 2u}; + request.graphics->tessellation->onChip = true; + request.graphics->tessellationConstants = std::array{128u, 128u, 15u, 0u, 96u, 1920u, 128u, 0x3f800000u, 0u}; + const auto encoded = serializer.Serialize(request); + const auto replay = serializer.Deserialize(encoded); + Require(replay.request.graphics && replay.request.graphics->tessellationConstants == request.graphics->tessellationConstants); + Require(serializer.Serialize(replay.request) == encoded); + auto truncated = DecodeBase64(encoded); + truncated.pop_back(); + bool rejected = false; + try { + static_cast(serializer.Deserialize(EncodeBase64(truncated))); + } catch (const std::runtime_error&) { + rejected = true; + } + Require(rejected); } } std::string SerializeVersion56(const ShaderRecompiler::RecompileRequest& request) { auto bytes = DecodeBase64(ShaderRecompiler::RequestSerializer{}.Serialize(request)); - Require(bytes.size() > 14u && bytes[4] == 63u); - bytes.resize(bytes.size() - (request.graphics && request.graphics->tessellation ? 7u : 6u)); + Require(bytes.size() > 14u && bytes[4] == 64u); + bytes.resize(bytes.size() - (request.graphics && request.graphics->tessellation ? 8u : 6u)); bytes[4] = 56u; return EncodeBase64(bytes); } @@ -246,7 +268,7 @@ void VerifyTargetOptions() { Require(replay.request.target.float16WidenNans == widen && replay.request.target.float16NarrowNans == narrow); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 63u && bytes.back() == 0u); + Require(bytes[4] == 64u && bytes.back() == 0u); for (std::size_t missing = 1u; missing <= 6u; ++missing) { auto truncated = bytes; truncated.resize(truncated.size() - missing); @@ -796,7 +818,7 @@ int VerifyVersion56Compatibility() { version40[4] = 40u; const auto replay40 = serializer.Deserialize(EncodeBase64(version40)); Require(!replay40.request.target.float32DenormPreserve && replay40.request.target.float32FlushToZero == !preserve); - for (const std::uint8_t unwritten : {58u, 59u, 60u, 61u, 64u}) { + for (const std::uint8_t unwritten : {58u, 59u, 60u, 61u, 65u}) { auto future = bytes; future[4] = unwritten; bool futureRejected = false; @@ -912,7 +934,7 @@ int VerifyVersion56Compatibility() { Require(replay35.request.target.spannedWaves == spanned && !replay35.request.target.float32FlushToZero); request.target.spannedAnySubgroup = spanned; const auto current = DecodeBase64(serializer.Serialize(request)); - Require(current[4] == 63u && current.back() == (spanned ? 1u : 0u)); + Require(current[4] == 64u && current.back() == (spanned ? 1u : 0u)); Require(serializer.Deserialize(EncodeBase64(current)).request.target.spannedAnySubgroup == spanned); auto version57 = current; version57[4] = 57u; diff --git a/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md b/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md index 8b87fff07ed9..2de1b17f0d02 100644 --- a/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md +++ b/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md @@ -2,7 +2,7 @@ ## add Functional -- [PS4 (GCN) on-chip tessellation](../../../core/shader/recompiler/Optimization/src/TessellationLowering.cpp) (shader recompiler, PS4) - not measured on a console. LS, HS and VS-stage domain routing (`VGT_SHADER_STAGES_EN` 0x45 or 0x145) is drawn through the off-chip ring lowering. With `SPI_SHADER_PGM_RSRC2_HS.OC_LDS_EN` clear the hull shader keeps its control points and patch constants in LDS and the domain shader reads them there, at offsets a tessellation constant buffer bound by the title computes at run time; a hull LDS write or a domain LDS read then throws. An on-chip hull that writes only tessellation factors and a domain shader that reads no hull output are drawn. +- [PS4 (GCN) on-chip tessellation](../../../core/shader/recompiler/Optimization/src/TessellationLowering.cpp) (shader recompiler, PS4) - not measured on a console. The tessellation constant buffer (shadPS4 `TessellationDataConstantBuffer`) is read from guest memory for every on-chip draw and compiled into its hull and domain stages, so those draws are kept in no draw cache or recipe. With `OC_LDS_EN` clear, hull LDS writes and domain LDS reads at or above `hs_output_base` go through the off-chip ring lowering at that offset less `hs_output_base`. A hull with `hs_output_base` 0 is taken as pass-through and copies `ls_stride` bytes of its input control point to its output; one with another output stride or control point count throws, as does an on-chip LDS address that reads another constant buffer or none. LS, HS and VS-stage domain routing (0x45, 0x145) uses the off-chip ring lowering. # libSceAgcDriver From 33f8d6a5a87988ad0ba63e376225f5cbbf6be328 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:53:56 -0500 Subject: [PATCH 04/34] test(agc): expect request serialization version 63 in shader memory tests The on-chip tessellation byte moved new requests to version 63, but agc_shader_memory still expected 62, kept 63 in its unsupported list and stripped six trailing bytes from a tessellated merged-hull request when making its version 56 fixture. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 3e84cd29ec3d..56842bd93a7d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -8915,7 +8915,7 @@ void verifyPixelRequestSerialization() { minimal.context.pixel->layerExported = true; minimal.context.pixel->ditheredAlphaToCoverage = true; const auto encoded = serializer.Serialize(minimal); - require(requestPrefix(encoded, 8u) == "NVNQQT4AAAA=", "new requests did not use serialization version 62"); + require(requestPrefix(encoded, 8u) == "NVNQQT8AAAA=", "new requests did not use serialization version 63"); auto withBarycentric = minimal; withBarycentric.target.fragmentBarycentricBuiltins = true; require(serializer.Deserialize(serializer.Serialize(withBarycentric)).request.target.fragmentBarycentricBuiltins && !serializer.Deserialize(encoded).request.target.fragmentBarycentricBuiltins, "barycentric built-ins were lost in serialization"); @@ -9036,7 +9036,7 @@ void verifyPixelRequestSerialization() { for (std::size_t bytes = 0; bytes < 45u; ++bytes) { expectFailure([&] { static_cast(serializer.Deserialize(requestPrefix(encoded, mappingOffset + bytes))); }, "truncated data", "a truncated pixel mapping, packing, dual-source, alpha-to-coverage, stencil reference export flag, primitive class, layer export, dither or front-face flag, quad pixel mask or quad sample mask was accepted"); } - for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQToAAAA=", "NVNQQT0AAAA=", "NVNQQT8AAAA="}) { + for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQToAAAA=", "NVNQQT0AAAA=", "NVNQQUAAAAA="}) { expectFailure([&] { static_cast(serializer.Deserialize(unsupported)); }, "serialization version", "an unsupported request version was accepted"); } static constexpr std::string_view version18Request{ @@ -9093,9 +9093,9 @@ std::vector decodeBase64(std::string_view text) { return bytes; } -std::vector version56Bytes(std::vector bytes) { - require(bytes.size() > 14u && bytes[4] == 62u, "a legacy fixture did not start from serialization version 62"); - bytes.resize(bytes.size() - 6u); +std::vector version56Bytes(std::vector bytes, bool tessellated = false) { + require(bytes.size() > 14u && bytes[4] == 63u, "a legacy fixture did not start from serialization version 63"); + bytes.resize(bytes.size() - (tessellated ? 7u : 6u)); bytes[4] = 56u; return bytes; } @@ -9670,7 +9670,7 @@ void verifyMergedHullConfiguration() { require(replay.request.graphics.has_value() && replay.request.graphics->tessellation.has_value() && replay.request.graphics->tessellation->mergedHull, "a merged hull configuration was lost in serialization"); require(!serializer.Deserialize(separate).request.graphics->tessellation->mergedHull, "a separate hull configuration was read as merged"); constexpr std::size_t pointTailBytes = 13u; - auto legacy = version56Bytes(decodeBase64(merged)); + auto legacy = version56Bytes(decodeBase64(merged), true); require(legacy.size() > 60u + pointTailBytes && legacy[4] == 56u, "a merged hull request did not use serialization version 56"); legacy.resize(legacy.size() - sizeof(std::uint32_t) - 7u - pointTailBytes); legacy.pop_back(); From 88d2f038970cdbdbc0ec3bfc8da7c9363813d42a Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:56:19 -0500 Subject: [PATCH 05/34] test(agc): expect request serialization version 64 in shader memory tests The tessellation constants flag moves new requests to version 64, which writes two trailing bytes for a tessellated request. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 56842bd93a7d..c60e754247aa 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -8915,7 +8915,7 @@ void verifyPixelRequestSerialization() { minimal.context.pixel->layerExported = true; minimal.context.pixel->ditheredAlphaToCoverage = true; const auto encoded = serializer.Serialize(minimal); - require(requestPrefix(encoded, 8u) == "NVNQQT8AAAA=", "new requests did not use serialization version 63"); + require(requestPrefix(encoded, 8u) == "NVNQQUAAAAA=", "new requests did not use serialization version 64"); auto withBarycentric = minimal; withBarycentric.target.fragmentBarycentricBuiltins = true; require(serializer.Deserialize(serializer.Serialize(withBarycentric)).request.target.fragmentBarycentricBuiltins && !serializer.Deserialize(encoded).request.target.fragmentBarycentricBuiltins, "barycentric built-ins were lost in serialization"); @@ -9036,7 +9036,7 @@ void verifyPixelRequestSerialization() { for (std::size_t bytes = 0; bytes < 45u; ++bytes) { expectFailure([&] { static_cast(serializer.Deserialize(requestPrefix(encoded, mappingOffset + bytes))); }, "truncated data", "a truncated pixel mapping, packing, dual-source, alpha-to-coverage, stencil reference export flag, primitive class, layer export, dither or front-face flag, quad pixel mask or quad sample mask was accepted"); } - for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQToAAAA=", "NVNQQT0AAAA=", "NVNQQUAAAAA="}) { + for (const auto unsupported : {"NVNQQQAAAAA=", "NVNQQTIAAAA=", "NVNQQToAAAA=", "NVNQQT0AAAA=", "NVNQQUEAAAA="}) { expectFailure([&] { static_cast(serializer.Deserialize(unsupported)); }, "serialization version", "an unsupported request version was accepted"); } static constexpr std::string_view version18Request{ @@ -9094,8 +9094,8 @@ std::vector decodeBase64(std::string_view text) { } std::vector version56Bytes(std::vector bytes, bool tessellated = false) { - require(bytes.size() > 14u && bytes[4] == 63u, "a legacy fixture did not start from serialization version 63"); - bytes.resize(bytes.size() - (tessellated ? 7u : 6u)); + require(bytes.size() > 14u && bytes[4] == 64u, "a legacy fixture did not start from serialization version 64"); + bytes.resize(bytes.size() - (tessellated ? 8u : 6u)); bytes[4] = 56u; return bytes; } From 3a4e170130d3bcb4791a62a22146eea44bf6bf3d Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:19:43 -0500 Subject: [PATCH 06/34] feat(agc): draw PS4 ES-GS-VS geometry shaders through a Vulkan geometry stage A GCN title routes geometry shaders as VGT_SHADER_STAGES_EN 0xb0 (ES_EN 2 = ES_STAGE_REAL, GS_EN 1, VS_EN 2 = VS_STAGE_COPY_SHADER), which DecodeShaderStages refused. Decode it for GCN guests with VGT_GS_MODE GS_SCENARIO_G off chip and read the export, geometry and copy programs from the ES, GS and VS registers. The ES is compiled as a Vulkan vertex shader whose ESGS ring stores (soffset the ES2GS offset SGPR) become its output record. The GS is compiled as a Vulkan geometry shader: its input VGPRs carry the ES vertex offsets, ESGS ring reads become reads of the input record of that vertex, GSVS ring stores (soffset the GS2VS offset SGPR) go to a per-invocation array of VGT_GS_VERT_ITEMSIZE times VGT_GS_MAX_VERT_OUT dwords, and s_sendmsg GS emit and cut become EmitVertex and EndPrimitive. The copy VS is not compiled: its exports, each component a GSVS ring dword or a constant, define the outputs every emit copies out of that array for the emitted vertex. Request serialization goes to version 63 and the pipeline journal to format 20 for the geometry configuration. Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/Driver/Draw/Draw.cpp | 18 +- .../Execution/src/Driver/Draw/DrawCapture.cpp | 2 +- .../Execution/src/Driver/Draw/DrawDecode.cpp | 11 +- .../Execution/src/Driver/Draw/DrawLookup.cpp | 4 +- .../src/Driver/Draw/DrawProgramTrace.cpp | 2 + .../src/Driver/Draw/DrawRegisterKey.cpp | 2 +- .../src/Driver/Shaders/ShaderRegistry.cpp | 9 +- .../Graphics/include/State.hpp | 2 + .../libSceAgcDriver/Graphics/src/Pipeline.cpp | 5 + .../Graphics/src/PipelineJournal.cpp | 25 +- .../Graphics/src/ShaderResources.cpp | 2 +- .../Graphics/src/ShaderValidation.cpp | 33 +- .../libSceAgcDriver/Graphics/src/State.cpp | 53 ++- .../tests/execution/GcnGeometry.cpp | 302 ++++++++++++++ core/shader/recompiler/CMakeLists.txt | 3 + core/shader/recompiler/CacheKey.hpp | 15 + .../include/ControlFlow/RequestSerializer.hpp | 1 + .../ControlFlow/src/RequestSerializer.cpp | 43 +- core/shader/recompiler/Deserialize.cpp | 4 +- .../IrMetadata/ShaderStage.hpp | 3 +- .../IrMetadata/StageIO.hpp | 10 +- .../src/IrOpcode.cpp | 2 +- .../src/IrProgram.cpp | 2 +- .../include/Optimization/GeometryLowering.hpp | 16 + .../Optimization/ShaderStageInputInfo.hpp | 12 + .../Optimization/src/GeometryLowering.cpp | 376 ++++++++++++++++++ .../Optimization/src/ShaderInfoCollector.cpp | 4 +- core/shader/recompiler/Recompiler.cpp | 16 +- core/shader/recompiler/Recompiler.hpp | 31 +- .../SpirvBackend/SpirvEmitterHelpers.hpp | 1 + .../SpirvBackend/SpirvEmitterInstructions.hpp | 1 + .../SpirvBackend/SpirvEmitterState.hpp | 3 +- .../src/SpirvAlu/SpirvAluEmitterMath.cpp | 2 +- .../SpirvBackend/src/SpirvEmitter.cpp | 2 +- .../SpirvBackend/src/SpirvFlowEmitter.cpp | 1 + .../src/SpirvMemory/SpirvEmitterHelpers.cpp | 2 +- .../src/SpirvMemory/SpirvModuleSetup.cpp | 4 + .../SpirvBackend/src/SpirvModuleEmitter.cpp | 96 ++++- .../Translation/InstructionTranslator.hpp | 3 +- .../Translation/ShaderInputInfoBuilder.hpp | 4 +- .../src/ControlFlowInstructions.cpp | 10 + .../Translation/src/InstructionTranslator.cpp | 24 ++ .../src/ShaderInputInfoBuilder.cpp | 30 +- .../tests/RequestSerializerTests.cpp | 42 +- .../debt/changes/claude-gcn-es-gs-copy-vs.md | 11 + 45 files changed, 1174 insertions(+), 70 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp create mode 100644 core/shader/recompiler/Optimization/include/Optimization/GeometryLowering.hpp create mode 100644 core/shader/recompiler/Optimization/src/GeometryLowering.cpp create mode 100644 docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 03de50683e76..bf8a6e1ac5e1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -271,7 +271,7 @@ DrawFinisher::Pending heldWrites(const DrawTail& tail) { } const auto& roles = tail.decode->roles; for (std::size_t i = 0; i < tail.matched.size(); ++i) { - if (i < roles.size() && roles[i] == ShaderRecompiler::ProgramRole::GeometryBack) continue; + if (i < roles.size() && ShaderRecompiler::LinkedOnlyRole(roles[i])) continue; const auto& variant = tail.matched[i]; if (variant == nullptr || variant->compiled == nullptr) { const bool candidates = !tail.drawHit && i < tail.dataCandidates.size() && !tail.dataCandidates[i].empty(); @@ -637,10 +637,11 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe decodeReads.resize(programs.size()); const auto decodeVertexInfo = [&](std::size_t i) { const auto& program = programs[i]; - if (program.binary.stage == Stage::Fragment || roles[i] == Role::GeometryBack) return; + if (program.binary.stage == Stage::Fragment || ShaderRecompiler::LinkedOnlyRole(roles[i])) return; vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, decodeReads[i], 8u - program.firstUserSgpr); if (vertexInfos[i]) { - vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, readRegister(queue.context, 0x207), program.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; + const auto& exporter = roles[i] == Role::Geometry && i + 1u < programs.size() && roles[i + 1u] == Role::Copy ? programs[i + 1u] : program; + vertexInfos[i]->paClVsOutCntl = PositionExportLayout(exporter.snapshot.get(), exporter.codeOffset, exporter.binary.code, readRegister(queue.context, 0x207), exporter.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode; Graphics::ApplyPointSize(graphics, *vertexInfos[i]); } @@ -890,7 +891,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const auto locate = [&](std::uint32_t location) -> std::optional> { if (location == 0x280u) return std::nullopt; for (std::size_t i = 0; i < programs.size(); ++i) { - if (roles[i] == Role::Fragment || roles[i] == Role::GeometryBack || location < programs[i].userDataBase) continue; + if (roles[i] == Role::Fragment || ShaderRecompiler::LinkedOnlyRole(roles[i]) || location < programs[i].userDataBase) continue; const auto word = location - programs[i].userDataBase + (8u - programs[i].firstUserSgpr); if (word < programs[i].userData.size()) return std::make_pair(i, static_cast(word)); } @@ -898,11 +899,12 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { }; const auto decodeVertexInfo = [&](std::size_t i) { const auto& program = programs[i]; - if (program.binary.stage == Stage::Fragment || roles[i] == Role::GeometryBack) return; + if (program.binary.stage == Stage::Fragment || ShaderRecompiler::LinkedOnlyRole(roles[i])) return; decodeReads[i].clear(); vertexInfos[i] = Graphics::DecodeVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, &decodeReads[i], false, 8u - program.firstUserSgpr); if (vertexInfos[i]) { - vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, tail.reg207, program.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; + const auto& exporter = roles[i] == Role::Geometry && i + 1u < programs.size() && roles[i + 1u] == Role::Copy ? programs[i + 1u] : program; + vertexInfos[i]->paClVsOutCntl = PositionExportLayout(exporter.snapshot.get(), exporter.codeOffset, exporter.binary.code, tail.reg207, exporter.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode; Graphics::ApplyPointSize(graphics, *vertexInfos[i]); } @@ -974,7 +976,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const bool fixedSlots = localDevice->GraphicsPipelineLibraries(); const bool hasFragment = std::ranges::any_of(programs, [](const DrawProgram& program) { return program.binary.stage == ShaderRecompiler::ShaderStage::Fragment; }); for (std::size_t i = 0; i < programs.size(); ++i) { - if (roles[i] == Role::GeometryBack) continue; + if (ShaderRecompiler::LinkedOnlyRole(roles[i])) continue; const auto& program = programs[i]; pushCursorBytes = Graphics::StagePushOffset(pushCursorBytes, program.binary.stage, fixedSlots); require(pushCursorBytes <= Graphics::PushBlockBytes(fixedSlots), "stage push constant offset exceeds the pipeline push constant block"); @@ -1506,7 +1508,7 @@ void Driver::restartFinishedDraw(DrawTail& tail) { tail.decodeReads[i].clear(); tail.vertexInfos[i].reset(); const auto& program = programs[i]; - if (program.binary.stage == Stage::Fragment || roles[i] == Role::GeometryBack) continue; + if (program.binary.stage == Stage::Fragment || ShaderRecompiler::LinkedOnlyRole(roles[i])) continue; tail.vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, tail.decodeReads[i], 8u - program.firstUserSgpr); if (!tail.vertexInfos[i]) continue; tail.vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, tail.reg207, program.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 3658ba6a71ca..af030f19da2f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -177,7 +177,7 @@ std::shared_ptr Driver::materializeDraw {waveSize, program.firstUserSgpr, program.userData, std::nullopt, program.binary.stage == Stage::Fragment ? std::optional(pixel) : std::nullopt, vertexInfos[i], memory, RegisteredFloatMode(*program.snapshot)}, localDevice->Target(), {0, 0, pushOffset, pushBytes}, - ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, Graphics::StageMeshConfiguration(graphics.stages, program.binary.stage), graphics.stages.tessellation, {drawParameters.indexAddress, drawParameters.indexCount, drawParameters.indexSize, drawParameters.instanceCount}, program.binary.stage == Stage::Mesh ? meshBarycentrics : std::nullopt} + ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, Graphics::StageMeshConfiguration(graphics.stages, program.binary.stage), graphics.stages.tessellation, {drawParameters.indexAddress, drawParameters.indexCount, drawParameters.indexSize, drawParameters.instanceCount}, program.binary.stage == Stage::Mesh ? meshBarycentrics : std::nullopt, Graphics::StageGeometryConfiguration(graphics.stages, program.binary.stage)} }; const auto waitedBefore = traceCapSync() || profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; auto invocation = [&] { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp index be0cdb093192..b9f47d24d5c6 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp @@ -3,6 +3,7 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Diagnostics.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawPipeline.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" #include #include #include @@ -90,7 +91,7 @@ std::vector> UserDataWords(const std::vector std::vector> words; if (location == 0x280u) return words; for (std::size_t i = 0; i < programs.size(); ++i) { - if (roles[i] == Role::Fragment || roles[i] == Role::GeometryBack || location < programs[i].userDataBase) continue; + if (roles[i] == Role::Fragment || ShaderRecompiler::LinkedOnlyRole(roles[i]) || location < programs[i].userDataBase) continue; const auto word = location - programs[i].userDataBase + (8u - programs[i].firstUserSgpr); if (word < programs[i].userData.size()) words.emplace_back(i, static_cast(word)); } @@ -121,7 +122,7 @@ void DecodeGraphicsPrograms(DrawDecode& decoded, const QueueState& queue, const DrawProgram result{ {stage, address, std::span(snapshot.code).subspan(codeOffset), snapshot.headerAddress, snapshot.header}, userDataBase, - stage == Stage::Fragment || userDataBase == 0x04cu ? 0u : 8u, + stage == Stage::Fragment || userDataBase == 0x04cu || ShaderRecompiler::GcnGuestShaders() ? 0u : 8u, {}, memory, program, @@ -176,6 +177,12 @@ void DecodeGraphicsPrograms(DrawDecode& decoded, const QueueState& queue, const append(0xc8, type, Stage::Mesh, 0x8b, 0x8c, Role::Main); InitializeMerged(queue, programs.back(), 0x82, type == 4, staticAbi); if (type == 4) append(0x88, 6, Stage::Mesh, 0x8b, 0x8c, Role::GeometryBack); + } else if (graphics.stages.legacyGeometry) { + append(0x0c8, 4, Stage::Vertex, 0x0cb, 0x0cc, Role::Main); + append(0x088, 6, Stage::Geometry, 0x08b, 0x08c, Role::Geometry); + append(0x048, 2, Stage::Vertex, 0x04b, 0x04c, Role::Copy); + auto& geometry = *graphics.stages.legacyGeometry; + geometry.exports = ShaderRecompiler::ParseGeometryCopyProgram(programs.back().binary.code, geometry.maxVertices, geometry.vertexDwords); } else if (graphics.stages.legacyVertex) { append(0x48, 2, Stage::Vertex, 0x4b, 0x4c, Role::Main); } else { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp index 57b3eceb4f0b..ceb7649250d8 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp @@ -142,7 +142,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptr sampling; for (std::size_t i = 0; !miss && i < programs.size(); ++i) { - if (roles[i] == Role::GeometryBack) continue; + if (ShaderRecompiler::LinkedOnlyRole(roles[i])) continue; ++stageValidations; cursor = Graphics::StagePushOffset(cursor, programs[i].binary.stage, fixedSlots); if (cursor > Graphics::PushBlockBytes(fixedSlots)) { miss = DrawMiss::Layout; break; } @@ -258,7 +258,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptr sampling; for (std::size_t i = 0; i < programs.size(); ++i) { - if (roles[i] == Role::GeometryBack || programs[i].userData.size() != dataEntry->decode->programs[i].userData.size()) continue; + if (ShaderRecompiler::LinkedOnlyRole(roles[i]) || programs[i].userData.size() != dataEntry->decode->programs[i].userData.size()) continue; const auto& now = programs[i].userData; const auto& was = dataEntry->decode->programs[i].userData; auto& candidates = dataCandidates[i]; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawProgramTrace.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawProgramTrace.cpp index 7123e8727dab..4506523fe65f 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawProgramTrace.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawProgramTrace.cpp @@ -25,6 +25,8 @@ const char* RoleName(ShaderRecompiler::ProgramRole role) { switch (role) { case ProgramRole::Main: return "main"; case ProgramRole::GeometryBack: return "geometry-back"; + case ProgramRole::Geometry: return "geometry"; + case ProgramRole::Copy: return "copy"; case ProgramRole::Local: return "local"; case ProgramRole::Hull: return "hull"; case ProgramRole::Domain: return "domain"; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp index 406e025ce6e2..c034c9b1dcc5 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawRegisterKey.cpp @@ -244,7 +244,7 @@ bool Driver::sameDecode(const DrawDecode& a, const DrawDecode& b) { if (!x) return true; return x->inputControlPoints == y->inputControlPoints && x->outputControlPoints == y->outputControlPoints && x->domain == y->domain && x->partitioning == y->partitioning && x->outputTopology == y->outputTopology && x->patchesPerGroup == y->patchesPerGroup && x->primitiveGroupSize == y->primitiveGroupSize && x->breakAtInstance == y->breakAtInstance && x->mergedHull == y->mergedHull; }; - if (s.stages.path != t.stages.path || s.stages.registerValue != t.stages.registerValue || s.stages.vertexWaveSize != t.stages.vertexWaveSize || s.stages.fragmentWaveSize != t.stages.fragmentWaveSize || s.stages.hullWaveSize != t.stages.hullWaveSize || !sameMesh(s.stages.mesh, t.stages.mesh) || !sameMesh(s.stages.tessellationGeometry, t.stages.tessellationGeometry) || !sameTess(s.stages.tessellation, t.stages.tessellation)) return false; + if (s.stages.path != t.stages.path || s.stages.registerValue != t.stages.registerValue || s.stages.vertexWaveSize != t.stages.vertexWaveSize || s.stages.fragmentWaveSize != t.stages.fragmentWaveSize || s.stages.hullWaveSize != t.stages.hullWaveSize || !sameMesh(s.stages.mesh, t.stages.mesh) || !sameMesh(s.stages.tessellationGeometry, t.stages.tessellationGeometry) || !sameTess(s.stages.tessellation, t.stages.tessellation) || s.stages.legacyGeometry != t.stages.legacyGeometry) return false; if (!sameColor(s.color, t.color) || s.colors.size() != t.colors.size() || s.blends.size() != t.blends.size()) return false; for (std::size_t i = 0; i < s.colors.size(); ++i) { if (!sameColor(s.colors[i], t.colors[i])) return false; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp index 91d3c56328e1..5d20c75288b4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp @@ -2288,6 +2288,7 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod if (decoded.state.stages.path == Graphics::ShaderPath::TessellationGeometry) expected.push_back(ShaderRecompiler::ProgramRole::Main); } else { expected.push_back(ShaderRecompiler::ProgramRole::Main); + if (decoded.state.stages.legacyGeometry) expected.insert(expected.end(), {ShaderRecompiler::ProgramRole::Geometry, ShaderRecompiler::ProgramRole::Copy}); if (decoded.state.stages.path == Graphics::ShaderPath::Geometry && !decoded.programs.empty() && decoded.programs.front().snapshot->type == 4) expected.push_back(ShaderRecompiler::ProgramRole::GeometryBack); } if (!decoded.roles.empty() && decoded.roles.back() == ShaderRecompiler::ProgramRole::Fragment) expected.push_back(ShaderRecompiler::ProgramRole::Fragment); @@ -2307,7 +2308,7 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod const bool fixedSlots = target.fixedPushSlots; const bool hasFragment = !decoded.roles.empty() && decoded.roles.back() == ShaderRecompiler::ProgramRole::Fragment; for (std::size_t index = 0; index < decoded.programs.size(); ++index) { - if (decoded.roles[index] == ShaderRecompiler::ProgramRole::GeometryBack) continue; + if (ShaderRecompiler::LinkedOnlyRole(decoded.roles[index])) continue; const auto& program = decoded.programs[index]; const bool fragment = program.binary.stage == ShaderRecompiler::ShaderStage::Fragment; const auto wave = Graphics::StageWaveSize(decoded.state.stages, program.binary.stage); @@ -2329,11 +2330,13 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod continue; } if (vertex) { - vertex->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, decoded.state.paClVsOutCntl, program.tailContinuation.get()) | decoded.state.layerExports | decoded.state.viewportExports; + const bool copied = decoded.roles[index] == ShaderRecompiler::ProgramRole::Geometry && index + 1u < decoded.programs.size() && decoded.roles[index + 1u] == ShaderRecompiler::ProgramRole::Copy; + const auto& exporter = copied ? decoded.programs[index + 1u] : program; + vertex->paClVsOutCntl = PositionExportLayout(exporter.snapshot.get(), exporter.codeOffset, exporter.binary.code, decoded.state.paClVsOutCntl, exporter.tailContinuation.get()) | decoded.state.layerExports | decoded.state.viewportExports; vertex->depthRemapMode = decoded.state.depthRemap.mode; Graphics::ApplyPointSize(decoded.state, *vertex); } - ShaderRecompiler::RecompileRequest request{program.binary, {wave, program.firstUserSgpr, program.userData, {}, fragment ? std::optional(decoded.pixel) : std::nullopt, vertex, memory, RegisteredFloatMode(*program.snapshot)}, target, {0, 0, offset, room}, ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, Graphics::StageMeshConfiguration(decoded.state.stages, program.binary.stage), decoded.state.stages.tessellation, {}}}; + ShaderRecompiler::RecompileRequest request{program.binary, {wave, program.firstUserSgpr, program.userData, {}, fragment ? std::optional(decoded.pixel) : std::nullopt, vertex, memory, RegisteredFloatMode(*program.snapshot)}, target, {0, 0, offset, room}, ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, Graphics::StageMeshConfiguration(decoded.state.stages, program.binary.stage), decoded.state.stages.tessellation, {}, std::nullopt, Graphics::StageGeometryConfiguration(decoded.state.stages, program.binary.stage)}}; std::vector key; ShaderRecompiler::BuildPreparedShaderKey(request, key); std::shared_ptr handle; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp index 9123d6ae5ed6..22e178d1701c 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp @@ -44,6 +44,7 @@ struct ShaderStages { std::uint32_t hullWaveSize = 64; std::optional tessellationGeometry; bool legacyVertex = false; + std::optional legacyGeometry; }; inline constexpr std::uint16_t UnclampedBlendMask = 0xffffu; @@ -253,6 +254,7 @@ void ApplyReadOnlyDepthBoundsComparison(State& state, const ShaderRecompiler::Sh void NormalizeUnusedViewportDepth(State& state, const ShaderRecompiler::ShaderPixelStageInfo& pixel); std::uint32_t StageWaveSize(const ShaderStages& stages, ShaderRecompiler::ShaderStage stage); std::optional StageMeshConfiguration(const ShaderStages& stages, ShaderRecompiler::ShaderStage stage); +std::optional StageGeometryConfiguration(const ShaderStages& stages, ShaderRecompiler::ShaderStage stage); std::uint32_t StagePushLimit(const ShaderStages& stages, std::uint32_t pushOffset, bool depthRemap); std::array SampleLocations(const State& state); std::array PixelSampleLocations(const State& state, const ShaderRecompiler::ShaderPixelStageInfo& pixel); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp index 5eda4cff3231..a3a149426c2e 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Pipeline.cpp @@ -545,6 +545,11 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput const bool barycentricPatches = BarycentricPatches(state, shaders); if (barycentricPatches) Require(context.tessellationShader && ((state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST && (!state.primitiveRestart || !context.primitiveListRestart)) || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP), "emulated barycentrics through tessellation require a triangle list or strip, with primitive restart in a list only on a device without VK_EXT_primitive_topology_list_restart"); if (std::any_of(shaders.begin(), shaders.end(), [](const CompiledShader& shader) { return shader.stage == ShaderRecompiler::ShaderStage::Geometry; })) Require(context.geometryShader, "device does not support geometry shaders"); + if (state.stages.legacyGeometry) { + const auto& geometry = *state.stages.legacyGeometry; + const auto outputs = static_cast(geometry.exports.size()) * 4u; + Require(geometry.maxVertices <= context.limits.maxGeometryOutputVertices && geometry.instances <= context.limits.maxGeometryShaderInvocations && ((geometry.esgsItemDwords + 3u) & ~3u) <= context.limits.maxGeometryInputComponents && outputs <= context.limits.maxGeometryOutputComponents && outputs * geometry.maxVertices <= context.limits.maxGeometryTotalOutputComponents, "a GCN geometry shader exceeds the device's geometry output vertices, invocations, input or output components"); + } if (state.stages.tessellation) { Require(context.tessellationShader, "device does not support tessellation shaders"); Require(state.stages.tessellation->inputControlPoints <= context.limits.maxTessellationPatchSize && state.stages.tessellation->outputControlPoints <= context.limits.maxTessellationPatchSize, "tessellation patch exceeds device limits"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp index 40151aece0c2..c4f93bec2d7a 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp @@ -56,7 +56,7 @@ static_assert(sizeof(ShaderRecompiler::TessellationConfiguration) == 40, "Tessel constexpr std::uint32_t FileMagic = 0x4c4a5041u; // Bumped when the recipe codec, CanonicalPipelineState or the store key change in a way the // layout guards above do not catch (a field renumbered or reinterpreted at the same size). -constexpr std::uint32_t FileFormat = 19u; +constexpr std::uint32_t FileFormat = 20u; constexpr std::uint32_t ModuleRecord = 1u; constexpr std::uint32_t GraphicsRecord = 2u; constexpr std::uint32_t ComputeRecord = 3u; @@ -182,6 +182,26 @@ void decodeTessellation(Reader& reader, ShaderRecompiler::TessellationConfigurat tessellation.mergedHull = reader.Bool(); } +void encodeGeometry(Writer& writer, const ShaderRecompiler::GeometryConfiguration& geometry) { + for (const auto value : {geometry.inputVertices, geometry.outputTopology, geometry.maxVertices, geometry.instances, geometry.esgsItemDwords, geometry.vertexDwords}) writer.U32(value); + writer.U32(static_cast(geometry.exports.size())); + for (const auto& copy : geometry.exports) { + for (const auto value : {copy.target, copy.enable, copy.constants, copy.values[0], copy.values[1], copy.values[2], copy.values[3]}) writer.U32(value); + writer.Bool(copy.done); + } +} + +void decodeGeometry(Reader& reader, ShaderRecompiler::GeometryConfiguration& geometry) { + for (auto* value : {&geometry.inputVertices, &geometry.outputTopology, &geometry.maxVertices, &geometry.instances, &geometry.esgsItemDwords, &geometry.vertexDwords}) *value = reader.U32(); + const auto count = reader.U32(); + if (count > 36u) throw std::runtime_error("pipeline journal: geometry copy export count exceeds the export targets"); + geometry.exports.resize(count); + for (auto& copy : geometry.exports) { + for (auto* value : {©.target, ©.enable, ©.constants, ©.values[0], ©.values[1], ©.values[2], ©.values[3]}) *value = reader.U32(); + copy.done = reader.Bool(); + } +} + void encodeState(Writer& writer, const State& state) { writer.U32(static_cast(state.stages.path)); writer.U32(state.stages.vertexWaveSize); @@ -192,6 +212,7 @@ void encodeState(Writer& writer, const State& state) { encodeOptional(writer, state.stages.tessellation, encodeTessellation); writer.U32(state.stages.hullWaveSize); encodeOptional(writer, state.stages.tessellationGeometry, encodeMesh); + encodeOptional(writer, state.stages.legacyGeometry, encodeGeometry); writer.Bool(state.depth.has_value()); if (state.depth) { writer.U32(static_cast(state.depth->format)); @@ -261,6 +282,7 @@ void decodeState(Reader& reader, State& state) { if (reader.Bool()) decodeTessellation(reader, state.stages.tessellation.emplace()); state.stages.hullWaveSize = reader.U32(); if (reader.Bool()) decodeMesh(reader, state.stages.tessellationGeometry.emplace()); + if (reader.Bool()) decodeGeometry(reader, state.stages.legacyGeometry.emplace()); if (reader.Bool()) { auto& depth = state.depth.emplace(); depth.format = static_cast(reader.U32()); @@ -1567,6 +1589,7 @@ State CanonicalPipelineState(const State& state) { canonical.stages.tessellation = state.stages.tessellation; canonical.stages.hullWaveSize = state.stages.hullWaveSize; canonical.stages.tessellationGeometry = state.stages.tessellationGeometry; + canonical.stages.legacyGeometry = state.stages.legacyGeometry; if (state.depth) { DepthTarget depth{}; depth.format = state.depth->format; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp index 8d5cbd25c76f..1ef5ab87cb75 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp @@ -2220,7 +2220,7 @@ std::uint32_t IrStage(ShaderRecompiler::ShaderStage stage) { case ShaderRecompiler::ShaderStage::Local: return static_cast(Ir::Local); case ShaderRecompiler::ShaderStage::TessellationControl: return static_cast(Ir::TessellationControl); case ShaderRecompiler::ShaderStage::TessellationEvaluation: return static_cast(Ir::TessellationEvaluation); - case ShaderRecompiler::ShaderStage::Geometry: break; + case ShaderRecompiler::ShaderStage::Geometry: return static_cast(Ir::Geometry); } return static_cast(Ir::Unknown); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index 757d3bc163cd..abb108e7b470 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -55,6 +55,7 @@ struct Module { bool meshCapability = false; std::uint32_t primitiveInputs = 0; bool pointSizeOutput = false; + bool copiedGeometry = false; bool pointSize = false; bool viewportOutput = false; std::map> modes; @@ -116,13 +117,15 @@ struct Module { Require(input == (stage == Stage::TessellationEvaluation), "invalid tessellation level direction"); return; } - if (stage == Stage::Geometry) { - Require(value == spv::BuiltInPosition && Signature(type) == "f32x4" && (input || !position), "unsupported geometry built-in"); + if (stage == Stage::Geometry && !(!input && (value == spv::BuiltInClipDistance || value == spv::BuiltInCullDistance) && copiedGeometry)) { + const auto signature = Signature(type); + if (copiedGeometry && input && (value == spv::BuiltInPrimitiveId || value == spv::BuiltInInvocationId) && (signature == "i32" || signature == "u32")) return; + Require(value == spv::BuiltInPosition && signature == "f32x4" && (input || !position) && !(copiedGeometry && input), "unsupported geometry built-in"); if (!input) position = true; return; } // One gl_ClipDistance array holds the guest clip distances and the recompiler's all-zero position distance. - if (!input && ((value == spv::BuiltInClipDistance && (vertex || stage == Stage::TessellationControl || stage == Stage::TessellationEvaluation || stage == Stage::Mesh)) || (value == spv::BuiltInCullDistance && (vertex || stage == Stage::TessellationEvaluation || stage == Stage::Mesh)))) { + if (!input && ((value == spv::BuiltInClipDistance && (vertex || stage == Stage::TessellationControl || stage == Stage::TessellationEvaluation || stage == Stage::Mesh || stage == Stage::Geometry)) || (value == spv::BuiltInCullDistance && (vertex || stage == Stage::TessellationEvaluation || stage == Stage::Mesh || stage == Stage::Geometry)))) { const auto signature = Signature(type); auto& count = value == spv::BuiltInClipDistance ? clipDistances : cullDistances; Require(count == 0 && signature.size() == 6 && signature.starts_with("f32[") && signature[4] >= '1' && signature[4] <= '8' && signature[5] == ']', "invalid or duplicate clip or cull distance output"); @@ -184,6 +187,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi const bool control = stage == Stage::TessellationControl; const bool evaluation = stage == Stage::TessellationEvaluation; const bool geometry = stage == Stage::Geometry; + const bool copiedGeometry = geometry && state.stages.legacyGeometry.has_value(); const bool rectListControl = state.rectList && control; if (rectListControl) { Require(shader.bdaAbiVersion == ShaderRecompiler::BdaAbi::Version, "incompatible rect-list fault ABI version"); @@ -203,6 +207,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi Module module; module.pointSizeOutput = (state.vertexPoints && stage == Stage::Vertex) || (mesh && state.stages.mesh.has_value() && state.stages.mesh->outputPrimitiveSize == 1u); module.viewportOutput = !state.extraViewports.empty(); + module.copiedGeometry = copiedGeometry; std::uint32_t entries = 0; std::uint32_t memoryModels = 0; std::uint32_t entryPoint = 0; @@ -276,10 +281,10 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi fragment && capability == spv::CapabilityStencilExportEXT; - if ((vertex || control || evaluation || mesh) && (capability == spv::CapabilityClipDistance || capability == spv::CapabilityCullDistance)) { + if ((vertex || control || evaluation || mesh || copiedGeometry) && (capability == spv::CapabilityClipDistance || capability == spv::CapabilityCullDistance)) { char word[16]; std::snprintf(word, sizeof(word), "0x%08x", state.paClVsOutCntl); - Require(capability == spv::CapabilityClipDistance ? shaderClipDistance : (vertex || evaluation || mesh) && shaderCullDistance, std::string("vertex clip or cull distance needs shaderClipDistance or shaderCullDistance, which the device lacks (PA_CL_VS_OUT_CNTL=") + word + ")"); + Require(capability == spv::CapabilityClipDistance ? shaderClipDistance : (vertex || evaluation || mesh || copiedGeometry) && shaderCullDistance, std::string("vertex clip or cull distance needs shaderClipDistance or shaderCullDistance, which the device lacks (PA_CL_VS_OUT_CNTL=") + word + ")"); } // Enabled unconditionally or by the device setup in VulkanDevice. @@ -290,14 +295,14 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi capability == spv::CapabilityImageQuery || (mesh && module.viewportOutput && capability == spv::CapabilityMultiViewport) || (shaderResourceMinLod && capability == spv::CapabilityMinLod) || - ((vertex || control || evaluation || mesh) && shaderClipDistance && capability == spv::CapabilityClipDistance) || + ((vertex || control || evaluation || mesh || copiedGeometry) && shaderClipDistance && capability == spv::CapabilityClipDistance) || (vertex && capability == spv::CapabilityDrawParameters) || (fragment && geometryShader && capability == spv::CapabilityGeometry) || (fragment && sampleRateShading && capability == spv::CapabilitySampleRateShading) || (fragment && sampleRateShading && capability == spv::CapabilityInterpolationFunction) || capability == spv::CapabilityImageMSArray || capability == spv::CapabilityStorageImageMultisample || - ((vertex || evaluation || mesh) && shaderCullDistance && capability == spv::CapabilityCullDistance) || + ((vertex || evaluation || mesh || copiedGeometry) && shaderCullDistance && capability == spv::CapabilityCullDistance) || capability == spv::CapabilityStorageImageWriteWithoutFormat || capability == spv::CapabilityStorageImageReadWithoutFormat || capability == spv::CapabilityInt64 || @@ -500,6 +505,13 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi mode(state.rectList || state.stages.tessellation->partitioning == 0u ? spv::ExecutionModeSpacingEqual : state.stages.tessellation->partitioning == 3u ? spv::ExecutionModeSpacingFractionalEven : spv::ExecutionModeSpacingFractionalOdd, {}); mode(counterClockwise ? spv::ExecutionModeVertexOrderCcw : spv::ExecutionModeVertexOrderCw, {}); Require(module.modes.size() == 3, "unsupported tessellation-evaluation execution mode"); + } else if (copiedGeometry) { + const auto& config = *state.stages.legacyGeometry; + mode(config.inputVertices == 1u ? spv::ExecutionModeInputPoints : config.inputVertices == 2u ? spv::ExecutionModeInputLines : spv::ExecutionModeTriangles, {}); + mode(spv::ExecutionModeInvocations, {config.instances}); + mode(config.outputTopology == 0u ? spv::ExecutionModeOutputPoints : config.outputTopology == 1u ? spv::ExecutionModeOutputLineStrip : spv::ExecutionModeOutputTriangleStrip, {}); + mode(spv::ExecutionModeOutputVertices, {config.maxVertices}); + Require(module.modes.size() == 4, "unsupported geometry execution mode"); } else if (geometry) { mode(spv::ExecutionModeTriangles, {}); mode(spv::ExecutionModeInvocations, {1u}); @@ -538,7 +550,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi const bool primitive = decoration.perPrimitive || module.perPrimitiveMembers.contains({outer[2], 0u}) || (decoration.builtin && (*decoration.builtin == spv::BuiltInPrimitivePointIndicesEXT || *decoration.builtin == spv::BuiltInPrimitiveLineIndicesEXT || *decoration.builtin == spv::BuiltInPrimitiveTriangleIndicesEXT || *decoration.builtin == spv::BuiltInCullPrimitiveEXT)); Require(length->second == (primitive ? state.stages.mesh->maxPrimitives : state.stages.mesh->maxVertices), "mesh interface array disagrees with output limits"); } else if (geometry) { - Require(length->second == 3u, "geometry interface array must hold the three vertices of a triangle"); + Require(length->second == (copiedGeometry ? state.stages.legacyGeometry->inputVertices : 3u), copiedGeometry ? "geometry interface array disagrees with the input primitive's vertex count" : "geometry interface array must hold the three vertices of a triangle"); } else { const auto expected = barycentricPatches ? 3u : state.rectList ? (control && input ? 3u : 4u) : control && input ? state.stages.tessellation->inputControlPoints : state.stages.tessellation->outputControlPoints; Require(length->second == expected, "tessellation interface array disagrees with control-point count"); @@ -657,7 +669,7 @@ Module Inspect(const CompiledShader& compiled, const State& state, const VkPhysi if (mesh) Require(module.primitiveIndices == state.stages.mesh->outputPrimitiveSize, "mesh shader does not export primitive indices"); if (fragment) Require(module.primitiveInputs == 0 || !primitiveLocations.empty(), "per-primitive pixel inputs need the barycentric emulation layout"); if (fragment) Require(!module.meshCapability || module.primitiveInputs != 0, "a pixel shader declares mesh shading without a per-primitive input"); - if (mesh || ((stage == Stage::Vertex || evaluation || geometry) && !state.rasterizerDiscard)) Require(module.position, "vertex shader does not export position"); + if (mesh || (((stage == Stage::Vertex && !state.stages.legacyGeometry) || evaluation || geometry) && !state.rasterizerDiscard)) Require(module.position, "vertex shader does not export position"); return module; } @@ -691,7 +703,8 @@ std::set ValidateShaders(std::span shaders, Require(!captured || state.rasterizerDiscard, "a captured tessellation pass must discard its primitives"); Require(geometry || shaders.size() == (tessellation || state.rectList || patches ? 4u : 2u), "incorrect graphics stage count"); if (patches) Require(state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, "emulated barycentrics through tessellation require a triangle list or strip"); - if (geometry) { + Require(!state.stages.legacyGeometry || geometry, "a GCN ES-GS-VS draw needs an export, a geometry and a pixel stage"); + if (geometry && !state.stages.legacyGeometry) { Require(shaders.back().program != nullptr && shaders.back().program->barycentricEmulation.active, "a geometry stage is generated only for emulated barycentrics"); Require(state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, "emulated barycentrics require triangle primitives"); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp index cbcabc964770..73b34d19f9d1 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp @@ -1316,6 +1316,37 @@ void ApplyPointSize(const State& state, ShaderRecompiler::ShaderVertexStageInfo& vertex.pointSizeMax = state.pointSizeMax; } +namespace { + +template +ShaderRecompiler::GeometryConfiguration decodeLegacyGeometry(const QueueState& queue, std::uint32_t primitive, const TValidate& validate) { + const auto optional = [&](std::uint32_t offset) { + const auto found = find(queue.context, offset); + return found == queue.context.end() ? 0u : found->second; + }; + const auto mode = read(queue.context, 0x290); + validate((mode & 7u) == 3u && (mode & ~0x001a0837u) == 0u, "VGT_GS_MODE other than GS_SCENARIO_G off chip, without ES pass-through, compute modes, element info or suppressed cuts, is not implemented"); + validate(optional(0x2e5) == 0u, "GCN stream-out (VGT_STRMOUT_CONFIG) from a geometry shader is not implemented"); + validate(optional(0x2d8) == 0u && optional(0x2d9) == 0u && optional(0x2da) == 0u, "GCN geometry output to vertex streams 1-3 (VGT_GS_VERT_ITEMSIZE_1-3) is not implemented"); + ShaderRecompiler::GeometryConfiguration geometry; + geometry.inputVertices = primitive == 1u ? 1u : primitive == 2u || primitive == 3u ? 2u : primitive == 4u || primitive == 5u || primitive == 6u ? 3u : 0u; + validate(geometry.inputVertices != 0u, "a GCN geometry shader over an adjacency, rectangle, quad or patch primitive is not implemented"); + geometry.outputTopology = read(queue.context, 0x29b) & 0x3fu; + validate(geometry.outputTopology == 1u || geometry.outputTopology == 2u, "VGT_GS_OUT_PRIM_TYPE other than a line strip or a triangle strip is not implemented for a GCN geometry shader"); + geometry.maxVertices = read(queue.context, 0x2ce) & 0x7ffu; + validate(geometry.maxVertices != 0u && geometry.maxVertices <= 1024u, "VGT_GS_MAX_VERT_OUT must be 1 to 1024"); + const auto instances = read(queue.context, 0x2e4); + geometry.instances = (instances & 1u) != 0u ? (instances >> 2u) & 0x7fu : 1u; + validate(geometry.instances != 0u && geometry.instances <= 32u, "VGT_GS_INSTANCE_CNT must be 1 to 32"); + geometry.esgsItemDwords = read(queue.context, 0x2ab) & 0x7fffu; + geometry.vertexDwords = read(queue.context, 0x2d7) & 0x7fffu; + validate(geometry.esgsItemDwords != 0u && geometry.vertexDwords != 0u, "VGT_ESGS_RING_ITEMSIZE and VGT_GS_VERT_ITEMSIZE must be nonzero"); + validate((read(queue.context, 0x2ac) & 0x7fffu) >= geometry.vertexDwords * geometry.maxVertices, "VGT_GSVS_RING_ITEMSIZE is smaller than VGT_GS_VERT_ITEMSIZE times VGT_GS_MAX_VERT_OUT"); + return geometry; +} + +} + ShaderStages DecodeShaderStages(const QueueState& queue, bool vertexWorkgroup) { const auto value = read(queue.context, 0x2d5); const auto validate = [&](bool condition, const char* reason) { @@ -1329,7 +1360,8 @@ ShaderStages DecodeShaderStages(const QueueState& queue, bool vertexWorkgroup) { const auto primitive = read(queue.userConfig, 0x242, RegisterBank::UserConfig); const bool tessellation = primitive == 9; validate(!vertexWorkgroup || ((value & 0x02002020u) == 0x2000u && !tessellation), "a vertex program that needs a workgroup requires PRIMGEN_EN without GS_EN, PRIMGEN_PASSTHRU_EN or tessellation"); - const bool geometry = (value & 0x20u) != 0 || vertexWorkgroup; + const bool legacyGeometry = ShaderRecompiler::GcnGuestShaders() && (value & 0x2000u) == 0 && (value & 0x20u) != 0 && !tessellation && !vertexWorkgroup; + const bool geometry = ((value & 0x20u) != 0 || vertexWorkgroup) && !legacyGeometry; validate(tessellation == ((value & 4u) != 0), "Patch topology and HS_EN disagree"); const auto path = tessellation ? geometry ? ShaderPath::TessellationGeometry : ShaderPath::Tessellation : geometry ? ShaderPath::Geometry : ShaderPath::Vertex; ShaderStages result{path, value, (value & 0x00400000u) != 0 ? 32u : 64u, (read(queue.context, 0x1b6) & 0x8000u) != 0 ? 32u : 64u, {}, {}}; @@ -1364,14 +1396,15 @@ ShaderStages DecodeShaderStages(const QueueState& queue, bool vertexWorkgroup) { return ShaderRecompiler::MeshConfiguration{inputPrimitive, groupPrimitives, (groupPrimitives - 1u) * inputStep + inputSize, maxVertices, maxPrimitives, ((threads + result.vertexWaveSize - 1u) / result.vertexWaveSize) * result.vertexWaveSize, ((resources >> 19u) & 0xffu) * 128u, provokingVertex, esgsItemSize, outputSize}; }; if (path == ShaderPath::Vertex && ShaderRecompiler::GcnGuestShaders() && (value & 0x2000u) == 0) { - validate(value == 0, "GCN vertex routing other than a plain VS is unsupported"); + validate(value == 0 || (legacyGeometry && value == 0xb0u), "GCN vertex routing other than a plain VS, or ES and GS with a copy shader on the VS stage, is unsupported"); const auto unitStepRate = [&](std::uint32_t offset) { const auto rate = find(queue.context, offset); return rate == queue.context.end() || rate->second == 1u; }; - const auto components = (read(queue.shader, 0x4a, RegisterBank::Shader) >> 24u) & 3u; + const auto components = (read(queue.shader, legacyGeometry ? 0xcau : 0x4au, RegisterBank::Shader) >> 24u) & 3u; validate(components == 0 || (unitStepRate(0x2a8) && (components == 1 || unitStepRate(0x2a9))), "GCN vertex instance step rates other than 1 are not implemented"); - result.legacyVertex = true; + if (legacyGeometry) result.legacyGeometry = decodeLegacyGeometry(queue, primitive, validate); + else result.legacyVertex = true; } else if (path == ShaderPath::Vertex) { validate((value & 0x2000u) != 0, "legacy vertex routing without PRIMGEN_EN is unsupported"); validate((value & ~0x0247a010u) == 0 || value == 0x02002008u, "unsupported vertex routing, scheduling or wave-ID state"); @@ -1405,6 +1438,11 @@ std::uint32_t StageWaveSize(const ShaderStages& stages, ShaderRecompiler::Shader return stages.vertexWaveSize; } +std::optional StageGeometryConfiguration(const ShaderStages& stages, ShaderRecompiler::ShaderStage stage) { + if (stage != ShaderRecompiler::ShaderStage::Vertex && stage != ShaderRecompiler::ShaderStage::Geometry) return std::nullopt; + return stages.legacyGeometry; +} + std::optional StageMeshConfiguration(const ShaderStages& stages, ShaderRecompiler::ShaderStage stage) { if (stages.mesh) return stages.mesh; if (stage == ShaderRecompiler::ShaderStage::TessellationEvaluation || stage == ShaderRecompiler::ShaderStage::Mesh) return stages.tessellationGeometry; @@ -1604,9 +1642,9 @@ void ApplyDepthRemap(const Context& context, State& state) { const bool inRange = withinUnitRange(state.viewport) && std::ranges::all_of(state.extraViewports, withinUnitRange); if (context.depthRangeUnrestricted || inRange) return; Require(state.extraViewports.empty(), "viewport depth outside [0, 1] is remapped for a single viewport only"); - const bool vertex = state.stages.path == ShaderPath::Vertex && !state.stages.tessellation; + const bool vertex = state.stages.path == ShaderPath::Vertex && !state.stages.tessellation && !state.stages.legacyGeometry; const bool tessellation = state.stages.path == ShaderPath::Tessellation && state.stages.tessellation.has_value(); - Require((vertex || tessellation) && !state.stages.mesh, "viewport depth outside [0, 1] is remapped on the vertex and tessellation paths only"); + Require((vertex || tessellation) && !state.stages.mesh, "viewport depth outside [0, 1] is remapped on the vertex and tessellation paths only, not through a geometry shader"); Require(context.depthClamp, "viewport depth outside [0, 1] needs depth clamping to stand in for the console's clamp"); const float clampMin = std::clamp(state.depthClampMin, 0.0f, 1.0f); const float clampMax = std::clamp(state.depthClampMax, 0.0f, 1.0f); @@ -1679,7 +1717,7 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) { case 1: Require(result.stages.mesh.has_value() || result.stages.path == ShaderPath::Vertex, "point lists are only drawn through the vertex and geometry paths"); result.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; - result.vertexPoints = result.stages.path == ShaderPath::Vertex; + result.vertexPoints = result.stages.path == ShaderPath::Vertex && !result.stages.legacyGeometry; break; case 2: result.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case 3: result.topology = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; break; @@ -2323,6 +2361,7 @@ std::array QuadSampleMasks(const State& state) { ShaderRecompiler::RasterPrimitive RasterPrimitiveOf(const State& state) { if (state.rectList) return ShaderRecompiler::RasterPrimitive::Rectangle; + if (state.stages.legacyGeometry) return state.stages.legacyGeometry->outputTopology == 1u ? ShaderRecompiler::RasterPrimitive::Line : ShaderRecompiler::RasterPrimitive::Triangle; if (state.stages.mesh.has_value() && state.stages.mesh->outputPrimitiveSize == 1u) return ShaderRecompiler::RasterPrimitive::Point; if (state.stages.mesh.has_value() && state.stages.mesh->outputPrimitiveSize == 2u) return ShaderRecompiler::RasterPrimitive::Line; if (state.stages.mesh.has_value() || state.stages.tessellation.has_value()) return ShaderRecompiler::RasterPrimitive::Triangle; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp new file mode 100644 index 000000000000..19bfd9e5fc35 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -0,0 +1,302 @@ +#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp" +#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "Recompiler.hpp" +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::GeometryConfiguration; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Width = 128; +constexpr std::uint32_t Height = 64; +constexpr std::array Background{16, 24, 40, 255}; +alignas(256) std::array Pixels{}; + +alignas(256) constexpr std::array GcnExport{ + 0x7e020d00, 0x060402f1, 0x100602f1, 0x060606f2, 0xe0704000, 0x04400200, 0xe0704004, 0x04400300, + 0xbf810000, +}; + +alignas(256) constexpr std::array GcnGeometry{ + 0x34100082, 0xe0305000, 0x80400908, 0xb0140100, 0xe0305000, 0x14400a08, 0xbf8c0000, 0x061612ff, + 0xbe800000, 0x061812ff, 0x3e800000, 0x7e1a02ff, 0xbe800000, 0x7e1c02ff, 0x3e800000, 0x7e1e0280, + 0x7e2002f2, 0xe0704000, 0x08410b00, 0xe0704010, 0x08410d00, 0xe0704020, 0x08410f00, 0xe0704030, + 0x08411000, 0xe0704040, 0x08410a00, 0xbf900022, 0xe0704004, 0x08410c00, 0xe0704014, 0x08410d00, + 0xe0704024, 0x08410f00, 0xe0704034, 0x08411000, 0xe0704044, 0x08410a00, 0xbf900022, 0xe0704008, + 0x08410b00, 0xe0704018, 0x08410e00, 0xe0704028, 0x08410f00, 0xe0704038, 0x08411000, 0xe0704048, + 0x08410a00, 0xbf900022, 0xe070400c, 0x08410c00, 0xe070401c, 0x08410e00, 0xe070402c, 0x08410f00, + 0xe070403c, 0x08411000, 0xe070404c, 0x08410a00, 0xbf900022, 0xbf900012, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnCopy{ + 0x34020082, 0xe0305000, 0x80400201, 0xe0305100, 0x80400301, 0xe0305200, 0x80400401, 0xb0040300, + 0xe0305000, 0x04400501, 0xe0305400, 0x80400601, 0xbf8c0000, 0x7e0e0280, 0x7e1002f2, 0xf80008cf, + 0x05040302, 0xf800020f, 0x08070706, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnCopyComputed{ + 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0x060604f2, 0xf80008cf, 0x02020302, 0xbf810000, +}; + +alignas(256) constexpr std::array PixelCode{ + 0xc8020002, 0xc8060102, 0xc80a0202, 0xc80e0302, 0xf800180f, 0x03020100, 0xbf810000, +}; + +alignas(256) constexpr std::array Indices{0u, 1u}; + +constexpr std::array RingUserData{0x1000u, 0u, 0u, 0u}; +constexpr std::array GeometryUserData{0x1000u, 0u, 0u, 0u, 0x2000u, 0u, 0u, 0u}; + +GeometryConfiguration Points() { + GeometryConfiguration geometry; + geometry.inputVertices = 1u; + geometry.outputTopology = 2u; + geometry.maxVertices = 4u; + geometry.instances = 1u; + geometry.esgsItemDwords = 2u; + geometry.vertexDwords = 5u; + geometry.exports = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopy, geometry.maxVertices, geometry.vertexDwords); + return geometry; +} + +ShaderRecompiler::RecompileResult Compile(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, std::span userData, std::uint32_t& pushCursor, const GeometryConfiguration& geometry) { + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + std::optional pixel; + std::optional vertex; + std::optional graphics; + if (stage == ShaderStage::Fragment) { + ShaderRecompiler::ShaderPixelStageInfo info{}; + info.interpolatorCount = 1; + info.interpolatorSettings[0] = 0x400u; + info.targetOutputMode[0] = 9; + info.targetExportMapping.fill(0xe4u); + pixel = info; + } else { + vertex = ShaderRecompiler::ShaderVertexStageInfo{}; + graphics = ShaderRecompiler::GraphicsCompileContext{0u, {}, std::nullopt, std::nullopt, {reinterpret_cast(Indices.data()), static_cast(Indices.size()), 2, 1}, std::nullopt, geometry}; + } + const auto layout = stage == ShaderStage::Fragment ? PixelPushLayout(pushCursor, target) : ShaderRecompiler::BindingLayout{0, 0, pushCursor, AgcDriver::Graphics::PipelinePushSlotBytes - pushCursor}; + ShaderRecompiler::RecompileRequest request{ + {stage, reinterpret_cast(code.data()), code, 0, {}}, + {64, 0u, userData, std::nullopt, pixel, vertex, memory}, + target, + layout, + graphics + }; + request.useCache = false; + auto result = ShaderRecompiler::Recompile(request); + pushCursor += static_cast(result.pushConstants.size()); + return result; +} + +std::array PixelAt(float x, float y) { + const auto column = static_cast((x + 1.0f) * 0.5f * Width); + const auto row = static_cast((1.0f - y) * 0.5f * Height); + const auto offset = (static_cast(row) * Width + column) * 4u; + return {std::to_integer(Pixels[offset]), std::to_integer(Pixels[offset + 1]), std::to_integer(Pixels[offset + 2]), std::to_integer(Pixels[offset + 3])}; +} + +std::string PixelText(const std::array& pixel) { + char text[64]; + std::snprintf(text, sizeof(text), "(%u, %u, %u, %u)", pixel[0], pixel[1], pixel[2], pixel[3]); + return text; +} + +void RequireQuads(AgcDriver::VulkanDevice& device) { + const auto target = device.Target(); + const auto geometry = Points(); + std::uint32_t cursor = 0; + auto exporter = Compile(target, ShaderStage::Vertex, GcnExport, RingUserData, cursor, geometry); + auto program = Compile(target, ShaderStage::Geometry, GcnGeometry, GeometryUserData, cursor, geometry); + auto fragment = Compile(target, ShaderStage::Fragment, PixelCode, {}, cursor, geometry); + for (std::size_t i = 0; i < Pixels.size(); i += 4) { + for (std::size_t c = 0; c < 4; ++c) Pixels[i + c] = std::byte{Background[c]}; + } + std::uint32_t offset = 0; + const auto push = [&](const ShaderRecompiler::RecompileResult& result) { + const auto at = result.pushConstants.empty() ? 0u : offset; + offset += static_cast(result.pushConstants.size()); + return at; + }; + const std::array shaders{{ + {ShaderStage::Vertex, &exporter, push(exporter)}, + {ShaderStage::Geometry, &program, push(program)}, + {ShaderStage::Fragment, &fragment, PixelPushOffset(offset, target)}, + }}; + AgcDriver::Graphics::State state{}; + state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0xb0u, 64, 64, std::nullopt, std::nullopt, 1.0f, 64.0f}; + state.stages.legacyGeometry = geometry; + state.color = {reinterpret_cast(Pixels.data()), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, Pixels.size(), 0xe4u}; + state.colors = {state.color}; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{0, 0}, {Width, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + state.blend.colorWriteMask = 15; + state.blends = {state.blend}; + state.blendConstants = {}; + device.Draw(state, {reinterpret_cast(Indices.data()), static_cast(Indices.size()), 2, 1, 0, true, 0, 0}, shaders); + device.WaitIdle(); + const auto first = PixelAt(-0.5f, 0.0f); + Require(first == std::array{255u, 0u, 0u, 255u}, "the first point's quad is " + PixelText(first) + ", expected (255, 0, 0, 255)"); + const auto second = PixelAt(0.5f, 0.0f); + Require(second[0] >= 127u && second[0] <= 128u && second[1] == 0u && second[2] == 0u && second[3] == 255u, "the second point's quad is " + PixelText(second) + ", expected half red"); + for (const auto [x, y] : {std::pair{0.0f, 0.0f}, std::pair{-0.5f, 0.4f}, std::pair{0.5f, -0.4f}, std::pair{-0.9f, 0.0f}}) { + const auto outside = PixelAt(x, y); + Require(outside == Background, "a pixel outside both quads at (" + std::to_string(x) + ", " + std::to_string(y) + ") is " + PixelText(outside)); + } +} + +void RequireCopyLayout() { + const auto exports = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopy, 4u, 5u); + Require(exports.size() == 2u, "the copy program did not yield a position and a parameter export"); + Require(exports[0].target == 0x0cu && exports[0].enable == 0xfu && exports[0].done && exports[0].constants == 0u && exports[0].values == std::array{0u, 1u, 2u, 3u}, "the position export did not read GSVS dwords 0-3"); + Require(exports[1].target == 0x20u && exports[1].constants == 0xeu && exports[1].values == std::array{4u, 0u, 0u, 0x3f800000u}, "the parameter export did not read GSVS dword 4 beside the constants 0, 0 and 1.0"); + bool refused = false; + try { + static_cast(ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyComputed, 4u, 5u)); + } catch (const std::exception& error) { + refused = std::string(error.what()).find("an exported value other than a GSVS ring dword or a constant") != std::string::npos; + } + Require(refused, "a copy program that exports a computed value was accepted"); + refused = false; + try { + static_cast(ShaderRecompiler::ParseGeometryCopyProgram(GcnCopy, 3u, 5u)); + } catch (const std::exception& error) { + refused = std::string(error.what()).find("which is not one of the 5 vertex dwords") != std::string::npos; + } + Require(refused, "a copy program read at a slot stride other than VGT_GS_MAX_VERT_OUT times 64 bytes was accepted"); +} + +void Bind(AgcDriver::QueueState& queue, const void* code, std::uint32_t program, std::uint32_t resources, std::span users) { + const auto address = reinterpret_cast(code); + queue.shader[program] = static_cast(address >> 8u); + queue.shader[program + 1u] = static_cast(address >> 40u); + queue.shader[resources] = static_cast(users.size()) << 1u; + for (std::size_t i = 0; i < users.size(); ++i) queue.shader[resources + 1u + static_cast(i)] = users[i]; +} + +AgcDriver::QueueState GeometryQueue() { + AgcDriver::QueueState queue{}; + queue.context[0x2d5] = 0xb0u; + queue.context[0x1b6] = 0u; + queue.context[0x290] = 0x00180033u; + queue.context[0x29b] = 2u; + queue.context[0x2ab] = 2u; + queue.context[0x2ac] = 20u; + queue.context[0x2ce] = 4u; + queue.context[0x2d7] = 5u; + queue.context[0x2e4] = 0u; + queue.userConfig[0x242] = 1u; + queue.shader[0xca] = 0u; + return queue; +} + +void RequireStageDecode() { + auto queue = GeometryQueue(); + const auto stages = AgcDriver::Graphics::DecodeShaderStages(queue); + Require(stages.path == AgcDriver::Graphics::ShaderPath::Vertex && stages.legacyGeometry.has_value() && !stages.legacyVertex && !stages.mesh, "VGT_SHADER_STAGES_EN 0xb0 did not decode as GCN ES-GS-VS routing"); + const auto& geometry = *stages.legacyGeometry; + Require(geometry.inputVertices == 1u && geometry.outputTopology == 2u && geometry.maxVertices == 4u && geometry.instances == 1u && geometry.esgsItemDwords == 2u && geometry.vertexDwords == 5u, "the GCN geometry registers decoded to another configuration"); + const auto refuses = [&](std::uint32_t offset, std::uint32_t value, const std::string& reason) { + auto refused = GeometryQueue(); + refused.context[offset] = value; + try { + static_cast(AgcDriver::Graphics::DecodeShaderStages(refused)); + } catch (const std::exception& error) { + Require(std::string(error.what()).find(reason) != std::string::npos, "the refusal named another reason: " + std::string(error.what())); + return; + } + Require(false, "a GCN geometry draw was accepted with register 0x" + std::to_string(offset) + " = " + std::to_string(value)); + }; + refuses(0x2e5, 1u, "stream-out"); + refuses(0x290, 0x00200033u, "VGT_GS_MODE"); + refuses(0x2d8, 4u, "vertex streams 1-3"); + refuses(0x29b, 0u, "VGT_GS_OUT_PRIM_TYPE"); + refuses(0x2ac, 19u, "VGT_GSVS_RING_ITEMSIZE"); +} + +void RequireProgramDecode() { + using namespace AgcDriver::DriverDetail; + using ShaderRecompiler::ProgramRole; + constexpr std::array exportUsers{0x11110001u, 0x11110002u, 0x11110003u, 0x11110004u}; + constexpr std::array geometryUsers{0x22220001u, 0x22220002u, 0x22220003u, 0x22220004u, 0x22220005u, 0x22220006u, 0x22220007u, 0x22220008u}; + constexpr std::array copyUsers{0x33330001u, 0x33330002u, 0x33330003u, 0x33330004u}; + AgcDriver::QueueState queue{}; + queue.context[0x8e] = 0xfu; + queue.context[0x8f] = 0xfu; + Bind(queue, GcnExport.data(), 0x0c8u, 0x0cbu, exportUsers); + Bind(queue, GcnGeometry.data(), 0x088u, 0x08bu, geometryUsers); + Bind(queue, GcnCopy.data(), 0x048u, 0x04bu, copyUsers); + Bind(queue, PixelCode.data(), 0x008u, 0x00bu, {}); + DrawDecode draw{}; + draw.state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0xb0u, 64u, 64u, std::nullopt, std::nullopt, 1.0f, 64.0f}; + auto geometry = Points(); + geometry.exports.clear(); + draw.state.stages.legacyGeometry = geometry; + draw.pixel.interpolatorCount = 1; + draw.pixel.interpolatorSettings[0] = 0x400u; + draw.pixel.targetOutputMode[0] = 9; + draw.pixel.targetExportMapping.fill(0xe4u); + const ShaderRegistry registry; + DecodeGraphicsPrograms(draw, queue, registry, false, true); + const std::vector roles{ProgramRole::Main, ProgramRole::Geometry, ProgramRole::Copy, ProgramRole::Fragment}; + Require(draw.roles == roles, "the GCN ES, GS, copy VS and PS programs did not decode as the export, geometry, copy and fragment roles"); + const std::array stages{ShaderStage::Vertex, ShaderStage::Geometry, ShaderStage::Vertex, ShaderStage::Fragment}; + const std::array codes{GcnExport.data(), GcnGeometry.data(), GcnCopy.data(), PixelCode.data()}; + const std::array, 4> users{exportUsers, geometryUsers, copyUsers, {}}; + for (std::size_t index = 0; index < draw.programs.size(); ++index) { + const auto& program = draw.programs[index]; + const auto name = "GCN program " + std::to_string(index); + Require(program.binary.stage == stages[index] && program.binary.codeAddress == reinterpret_cast(codes[index]), name + " was read from another program register"); + Require(program.firstUserSgpr == 0u && program.hiddenUserWords == 0u, name + " places its user data after hidden words"); + Require(std::ranges::equal(program.userData, users[index]), name + " did not read its own stage's user data"); + } + Require(draw.state.stages.legacyGeometry->exports == Points().exports, "the copy program's exports were not read into the geometry configuration"); +} + +} + +int main() { + try { + ShaderRecompiler::SetGcnGuestShaders(true); + RequireCopyLayout(); + RequireStageDecode(); + RequireProgramDecode(); + ShaderRecompiler::SetGcnGuestShaders(false); + auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + if (!device->GeometryLimits()) { + std::puts("GCN geometry: skipped, the device has no geometry shaders"); + return VulkanTestSkipped; + } + ShaderRecompiler::SetGcnGuestShaders(true); + RequireQuads(*device); + ShaderRecompiler::SetGcnGuestShaders(false); + device.reset(); + std::puts("GCN geometry tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/CMakeLists.txt b/core/shader/recompiler/CMakeLists.txt index 1bee82bc00bb..49fa8977ca1c 100644 --- a/core/shader/recompiler/CMakeLists.txt +++ b/core/shader/recompiler/CMakeLists.txt @@ -107,6 +107,7 @@ function(add_shader_recompiler target runtimeTarget) ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/HostInterpolationChecker.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/ReadLaneEliminator.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/MaskedSelectEliminator.cpp + ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/GeometryLowering.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/TessellationLowering.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/QuadHelperProof.cpp ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Optimization/src/ResourceTracker.cpp @@ -269,7 +270,9 @@ function(add_shader_recompiler target runtimeTarget) ExactF32Arithmetic HashBytes LayoutBarycentricEmulation + LinkedOnlyRole MeshBarycentricLayoutOf + ParseGeometryCopyProgram NativeCachePath_nid_no_patch ImageTableAbi::PoisonCode ImageTableAbi::PoisonReasonName diff --git a/core/shader/recompiler/CacheKey.hpp b/core/shader/recompiler/CacheKey.hpp index 0c3228419dc1..87912f59ee59 100644 --- a/core/shader/recompiler/CacheKey.hpp +++ b/core/shader/recompiler/CacheKey.hpp @@ -60,6 +60,7 @@ class RecompileCacheKey { appendFallbacks(key, request); appendMesh(key, request); appendTessellation(key, request); + appendGeometry(key, request); std::uint64_t hash = 0xcbf29ce484222325ull; for (const auto value : key) { hash ^= value; @@ -101,6 +102,7 @@ class RecompileCacheKey { appendFallbacks(key, request); appendMesh(key, request); appendTessellation(key, request); + appendGeometry(key, request); append(key, request.target); append(key, DebugProbeActive()); append(key, RayTracingStrict()); @@ -154,6 +156,19 @@ class RecompileCacheKey { append(key, TessellationInstancePatches(request)); } + static void appendGeometry(std::vector& key, const RecompileRequest& request) { + const auto* geometry = request.graphics && request.graphics->geometry ? &*request.graphics->geometry : nullptr; + append(key, geometry != nullptr); + if (geometry == nullptr) return; + for (const auto value : {geometry->inputVertices, geometry->outputTopology, geometry->maxVertices, geometry->instances, geometry->esgsItemDwords, geometry->vertexDwords}) append(key, value); + if (request.shader.stage != ShaderStage::Geometry) return; + append(key, geometry->exports.size()); + for (const auto& copy : geometry->exports) { + for (const auto value : {copy.target, copy.enable, copy.constants, static_cast(copy.done)}) append(key, value); + append(key, copy.values); + } + } + template static void append(std::vector& key, TValue value) requires (std::is_integral_v || std::is_enum_v) { key.push_back(static_cast(value)); diff --git a/core/shader/recompiler/ControlFlow/include/ControlFlow/RequestSerializer.hpp b/core/shader/recompiler/ControlFlow/include/ControlFlow/RequestSerializer.hpp index bf76e576bdd5..0032f52d1ea5 100644 --- a/core/shader/recompiler/ControlFlow/include/ControlFlow/RequestSerializer.hpp +++ b/core/shader/recompiler/ControlFlow/include/ControlFlow/RequestSerializer.hpp @@ -21,6 +21,7 @@ namespace ShaderRecompiler { std::vector linkedPrograms; std::optional mesh; std::optional tessellation; + std::optional geometry; GraphicsDrawParameters draw{}; }; diff --git a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp index 63ac303e6691..71cfef978258 100644 --- a/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp +++ b/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp @@ -229,7 +229,7 @@ ShaderStage readShaderStage(Reader& reader) { ProgramRole readProgramRole(Reader& reader) { const auto value = reader.ReadU8(); - if (value > static_cast(ProgramRole::Fragment)) { + if (value > static_cast(ProgramRole::Copy)) { throw std::runtime_error("RequestSerializer: invalid ProgramRole value"); } return static_cast(value); @@ -818,6 +818,38 @@ BindingLayout readBindingLayout(Reader& reader) { return layout; } +void writeGeometryConfiguration(Writer& writer, const std::optional& geometry) { + writer.WriteBool(geometry.has_value()); + if (!geometry.has_value()) return; + for (const auto value : {geometry->inputVertices, geometry->outputTopology, geometry->maxVertices, geometry->instances, geometry->esgsItemDwords, geometry->vertexDwords}) writer.WriteU32(value); + writer.WriteU64(geometry->exports.size()); + for (const auto& copy : geometry->exports) { + writer.WriteU32(copy.target); + writer.WriteU32(copy.enable); + writer.WriteU32(copy.constants); + for (const auto value : copy.values) writer.WriteU32(value); + writer.WriteBool(copy.done); + } +} + +std::optional readGeometryConfiguration(Reader& reader) { + if (!reader.ReadBool()) return std::nullopt; + GeometryConfiguration geometry; + for (auto* value : {&geometry.inputVertices, &geometry.outputTopology, &geometry.maxVertices, &geometry.instances, &geometry.esgsItemDwords, &geometry.vertexDwords}) *value = reader.ReadU32(); + const auto count = reader.ReadU64(); + reader.Require(count, 29u); + for (std::uint64_t i = 0; i < count; i++) { + GeometryCopyExport copy; + copy.target = reader.ReadU32(); + copy.enable = reader.ReadU32(); + copy.constants = reader.ReadU32(); + for (auto& value : copy.values) value = reader.ReadU32(); + copy.done = reader.ReadBool(); + geometry.exports.push_back(copy); + } + return geometry; +} + void writeGraphicsCompileContext(Writer& writer, const GraphicsCompileContext& graphics) { writer.WriteU32(graphics.firstUserSgpr); writer.WriteU64(graphics.linkedPrograms.size()); @@ -916,7 +948,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const std::string buffer; Writer writer(buffer); writer.WriteU32(0x41505335u); - writer.WriteU32(62u); + writer.WriteU32(63u); writeShaderBinary(writer, request.shader); writeGuestContext(writer, request.context); writeSpirvTarget(writer, request.target); @@ -970,6 +1002,7 @@ std::string RequestSerializer::Serialize(const RecompileRequest& request) const writer.WriteU32(request.target.maxImageArrayLayers); writer.WriteBool(request.target.fixedPushSlots); writer.WriteBool(request.target.spannedAnySubgroup); + if (request.graphics.has_value()) writeGeometryConfiguration(writer, request.graphics->geometry); return base64Encode(buffer); } @@ -978,7 +1011,7 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const Reader reader(decoded); if (reader.ReadU32() != 0x41505335u) throw std::runtime_error("invalid recompile request signature"); const auto version = reader.ReadU32(); - if (version < 1u || version > 62u || version == 50u || (version >= 58u && version <= 61u)) throw std::runtime_error("unsupported recompile request serialization version"); + if (version < 1u || version > 63u || version == 50u || (version >= 58u && version <= 61u)) throw std::runtime_error("unsupported recompile request serialization version"); DeserializedRequest result{}; result.request.shader = readShaderBinary(reader, result.shaderCode, result.shaderHeader); result.request.context = readGuestContext(reader, result, version); @@ -1054,6 +1087,10 @@ DeserializedRequest RequestSerializer::Deserialize(std::string_view text) const result.request.target.fixedPushSlots = reader.ReadBool(); } if (version >= 62u) result.request.target.spannedAnySubgroup = reader.ReadBool(); + if (version >= 63u && result.request.graphics.has_value()) { + result.graphicsStorage->geometry = readGeometryConfiguration(reader); + result.request.graphics->geometry = result.graphicsStorage->geometry; + } if (version >= 21u && reader.Remaining() != 0u) throw std::runtime_error("RequestSerializer: unexpected trailing data"); return result; } diff --git a/core/shader/recompiler/Deserialize.cpp b/core/shader/recompiler/Deserialize.cpp index d35dff0ccb70..fa460061a9b6 100644 --- a/core/shader/recompiler/Deserialize.cpp +++ b/core/shader/recompiler/Deserialize.cpp @@ -59,7 +59,7 @@ static ShaderStageKind ToShaderStageKind(ShaderStage stage) { case ShaderStage::Mesh: return ShaderStageKind::Mesh; case ShaderStage::Geometry: - throw std::runtime_error("unsupported geometry shader stage"); + return ShaderStageKind::Geometry; } throw std::runtime_error("invalid shader stage"); @@ -153,7 +153,7 @@ int main(int argc, char** argv) { std::cout << "Disassembly written to disasm.txt (" << disasm.size() << " bytes)\n"; const ShaderStageKind stageKind = ToShaderStageKind(request.shader.stage); - const auto inputInfo = BuildShaderStageInputInfo(stageKind, request.context, request.target.subgroupSize, request.graphics && request.graphics->mesh ? &*request.graphics->mesh : nullptr); + const auto inputInfo = BuildShaderStageInputInfo(stageKind, request.context, request.target.subgroupSize, request.graphics && request.graphics->mesh ? &*request.graphics->mesh : nullptr, nullptr, request.graphics && request.graphics->geometry ? &*request.graphics->geometry : nullptr); GraphBuilder graphBuilder; auto cfg = graphBuilder.Build(decoded); diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/ShaderStage.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/ShaderStage.hpp index 8d6fadebf014..3bd9ca896ab2 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/ShaderStage.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/ShaderStage.hpp @@ -12,7 +12,8 @@ enum class IrShaderStage { Mesh, Local, TessellationControl, - TessellationEvaluation + TessellationEvaluation, + Geometry }; } diff --git a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/StageIO.hpp b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/StageIO.hpp index 809e2543495b..a814c4ad5668 100644 --- a/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/StageIO.hpp +++ b/core/shader/recompiler/IntermediateRepresentation/include/IntermediateRepresentation/IrMetadata/StageIO.hpp @@ -18,14 +18,20 @@ enum class TessellationAttribute { InstanceOutput, InstanceInput, ControlShared, - GeometryOutput + GeometryOutput, + GeometryInput, + GeometryRing, + GeometryEmitted }; enum class TessellationBaseKind { OffChip, Factor, RelativeIndex, - PassthroughPrimitive + PassthroughPrimitive, + EsGsOffset, + GsVsOffset, + GeometryVertex }; enum class StageInputKind { diff --git a/core/shader/recompiler/IntermediateRepresentation/src/IrOpcode.cpp b/core/shader/recompiler/IntermediateRepresentation/src/IrOpcode.cpp index ef189a240860..098228ecaf86 100644 --- a/core/shader/recompiler/IntermediateRepresentation/src/IrOpcode.cpp +++ b/core/shader/recompiler/IntermediateRepresentation/src/IrOpcode.cpp @@ -106,7 +106,7 @@ constexpr std::array(IrOpcode::Count)> Meta makeMeta("LoadShared", U32, U32), makeMeta("StoreShared", Void, U32, U32), makeMeta("Barrier", Void), - makeMeta("EmitVertex", Void), + makeMeta("EmitVertex", Void, U1, U32), makeMeta("Discard", Void), makeMeta("ReadFirstLane", U32, U32, U1), makeMeta("ReadLane", U32, U32, U32), diff --git a/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp b/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp index 7046b20a4bd4..18239dbc49f5 100644 --- a/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp +++ b/core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp @@ -988,7 +988,7 @@ PositionExportComponent DecodePositionExportComponent(std::uint32_t control, std } std::uint32_t NativeBinding(IrShaderStage stage, DescriptorBindingKind kind) { - const std::uint32_t group = stage == IrShaderStage::Pixel ? 1u : stage == IrShaderStage::TessellationControl ? 2u : stage == IrShaderStage::TessellationEvaluation ? 3u : 0u; + const std::uint32_t group = stage == IrShaderStage::Pixel ? 1u : stage == IrShaderStage::TessellationControl ? 2u : stage == IrShaderStage::TessellationEvaluation || stage == IrShaderStage::Geometry ? 3u : 0u; return RuntimeAbi::BindingNumber(static_cast(group), kind); } diff --git a/core/shader/recompiler/Optimization/include/Optimization/GeometryLowering.hpp b/core/shader/recompiler/Optimization/include/Optimization/GeometryLowering.hpp new file mode 100644 index 000000000000..66990c923583 --- /dev/null +++ b/core/shader/recompiler/Optimization/include/Optimization/GeometryLowering.hpp @@ -0,0 +1,16 @@ +#ifndef CORE_SHADER_RECOMPILIER_OPTIMIZATION_INCLUDE_OPTIMIZATION_GEOMETRYLOWERING_HPP +#define CORE_SHADER_RECOMPILIER_OPTIMIZATION_INCLUDE_OPTIMIZATION_GEOMETRYLOWERING_HPP + +#include "IntermediateRepresentation/IrProgram.hpp" +#include "Optimization/ShaderStageInputInfo.hpp" + +namespace ShaderRecompiler { + +class GeometryLowering { +public: + void Lower(IrProgram& program, const ShaderGeometryInputInfo& geometry) const; +}; + +} + +#endif diff --git a/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp b/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp index 103a4c37279e..fa6a0ea410e4 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/ShaderStageInputInfo.hpp @@ -119,6 +119,17 @@ struct ShaderTessellationInputInfo { std::uint32_t geometryItemDwords = 0; }; +struct ShaderGeometryInputInfo { + bool active = false; + std::uint32_t inputVertices = 0; + std::uint32_t outputTopology = 0; + std::uint32_t maxVertices = 0; + std::uint32_t instances = 1; + std::uint32_t esgsItemDwords = 0; + std::uint32_t vertexDwords = 0; + std::vector exports; +}; + struct ShaderVertexInputInfo { static constexpr int MaxResources = 32; @@ -141,6 +152,7 @@ struct ShaderVertexInputInfo { ShaderDepthRemap depthRemap; ShaderMeshInputInfo mesh; ShaderTessellationInputInfo tess; + ShaderGeometryInputInfo geometry; bool fetchExternal = false; bool fetchEmbedded = false; }; diff --git a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp new file mode 100644 index 000000000000..f727bf417dbb --- /dev/null +++ b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp @@ -0,0 +1,376 @@ +#include "Optimization/GeometryLowering.hpp" +#include "Optimization/DeadCodeEliminator.hpp" +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ShaderRecompiler { +namespace { + +constexpr std::uint32_t GeometryVertexBases = 6u; +constexpr std::uint32_t EsGsComponentBytes = 256u; +constexpr std::uint32_t GsVsVertexBytes = 64u; + +[[noreturn]] void Fail(const char* reason, std::uint32_t pc) { + char text[320]; + std::snprintf(text, sizeof(text), "geometry lowering: %s at pc 0x%x", reason, pc); + throw std::runtime_error(text); +} + +[[noreturn]] void FailCopy(const std::string& reason, std::uint32_t pc) { + char text[64]; + std::snprintf(text, sizeof(text), " at pc 0x%x", pc); + throw std::runtime_error("geometry copy program: " + reason + text); +} + +std::optional BaseKind(const IrValue* raw) { + const IrValue* value = raw->Resolve(); + if (value->Opcode() != IrOpcode::TessellationBase || !value->Argument(0)->Resolve()->HasImmediate()) return std::nullopt; + return value->Argument(0)->Resolve()->ImmediateU32(); +} + +bool IsBase(const IrValue* raw, TessellationBaseKind kind) { + const auto found = BaseKind(raw); + return found && *found == static_cast(kind); +} + +std::optional GeometryVertexOf(const IrValue* raw) { + const auto kind = BaseKind(raw); + const auto first = static_cast(TessellationBaseKind::GeometryVertex); + if (!kind || *kind < first || *kind >= first + GeometryVertexBases) return std::nullopt; + return *kind - first; +} + +bool IsGeometryBase(const IrValue* raw) { + return IsBase(raw, TessellationBaseKind::EsGsOffset) || IsBase(raw, TessellationBaseKind::GsVsOffset) || GeometryVertexOf(raw).has_value(); +} + +struct Term { + std::optional vertex; + std::int64_t scale = 0; + std::int64_t constant = 0; +}; + +std::optional Evaluate(const IrValue* raw, std::uint32_t depth = 0u) { + if (depth > 32u) return std::nullopt; + const IrValue* value = raw->Resolve(); + if (value->HasImmediate()) return Term{std::nullopt, 0, static_cast(value->ImmediateU32())}; + if (const auto vertex = GeometryVertexOf(value)) return Term{vertex, 1, 0}; + const auto pair = [&]() -> std::optional> { + if (value->ArgumentCount() < 2u) return std::nullopt; + const auto left = Evaluate(value->Argument(0), depth + 1u); + const auto right = Evaluate(value->Argument(1), depth + 1u); + if (!left || !right) return std::nullopt; + return std::pair{*left, *right}; + }; + switch (value->Opcode()) { + case IrOpcode::IAdd32: { + const auto terms = pair(); + if (!terms || (terms->first.vertex && terms->second.vertex)) return std::nullopt; + return Term{terms->first.vertex ? terms->first.vertex : terms->second.vertex, terms->first.scale + terms->second.scale, terms->first.constant + terms->second.constant}; + } + case IrOpcode::ISub32: { + const auto terms = pair(); + if (!terms || terms->second.vertex) return std::nullopt; + return Term{terms->first.vertex, terms->first.scale, terms->first.constant - terms->second.constant}; + } + case IrOpcode::ShiftLeftLogical32: { + const auto terms = pair(); + if (!terms || terms->second.vertex || terms->second.constant < 0 || terms->second.constant > 31) return std::nullopt; + return Term{terms->first.vertex, terms->first.scale << terms->second.constant, terms->first.constant << terms->second.constant}; + } + case IrOpcode::IMul32: { + const auto terms = pair(); + if (!terms || (terms->first.vertex && terms->second.vertex)) return std::nullopt; + const auto& varying = terms->first.vertex ? terms->first : terms->second; + const auto& factor = terms->first.vertex ? terms->second : terms->first; + return Term{varying.vertex, varying.scale * factor.constant, varying.constant * factor.constant}; + } + default: + return std::nullopt; + } +} + +ExportTargetKind CopyTargetKind(std::uint32_t target, std::uint32_t& index) { + if (target >= 0x0cu && target <= 0x0fu) { + index = target - 0x0cu; + return ExportTargetKind::Position; + } + if (target >= 0x20u && target <= 0x3fu) { + index = target - 0x20u; + return ExportTargetKind::Parameter; + } + index = 0u; + return ExportTargetKind::Unknown; +} + +class Lowering { +public: + Lowering(IrProgram& program, const ShaderGeometryInputInfo& geometry) : program(program), geometry(geometry), stage(program.Resources().stage) {} + + void Run() { + if (stage != IrShaderStage::Vertex && stage != IrShaderStage::Geometry) Fail("a geometry configuration reached a stage other than the export or geometry program", 0u); + std::vector> accesses; + std::vector> emits; + for (IrBlock* block : program.BlockOrder()) { + for (IrValue* inst : block->Instructions()) { + if (stage == IrShaderStage::Geometry && SharedAccessOf(inst->Opcode()) != SharedAccess::None) Fail("a GCN geometry program that uses LDS is unsupported", inst->Flags().pc); + if (inst->Opcode() == IrOpcode::EmitVertex) emits.emplace_back(block, inst); + if (BufferAccessOf(inst->Opcode()) != BufferAccess::None && inst->ArgumentCount() > 3u && ringAccess(inst)) accesses.emplace_back(block, inst); + } + } + if (stage == IrShaderStage::Vertex && !emits.empty()) Fail("an export program emits geometry vertices", 0u); + for (const auto& [block, inst] : accesses) rewrite(*block, *inst); + if (stage == IrShaderStage::Geometry) { + std::vector exportIndices; + for (const auto& copy : geometry.exports) exportIndices.push_back(addExport(copy)); + for (const auto& [block, inst] : emits) copyOutputs(*block, *inst, exportIndices); + } + constexpr DeadCodeEliminator deadCodeEliminator; + deadCodeEliminator.Eliminate(program); + for (IrBlock* block : program.BlockOrder()) { + for (IrValue* inst : block->Instructions()) { + if (inst->Opcode() == IrOpcode::TessellationBase && inst->HasUses() && IsGeometryBase(inst)) Fail(GeometryVertexOf(inst) ? "an ES vertex offset is used other than as an ESGS ring read address" : "a geometry ring offset is used other than as a ring access offset", 0u); + } + } + program.Metadata().tessellationLocalStride = geometry.esgsItemDwords * 4u; + } + +private: + bool ringAccess(IrValue* inst) const { + const bool soffset = IsGeometryBase(inst->Argument(3)); + const auto offset = Evaluate(inst->Argument(2)); + const bool voffset = offset.has_value() && offset->vertex.has_value(); + const auto memory = program.Resources().memoryInfo.at(inst->Flags().index); + if (!soffset && !voffset) { + if (IsGeometryBase(inst->Argument(2))) Fail("a geometry ring offset is used as a buffer vector offset", inst->Flags().pc); + return false; + } + if (memory.kind != ResourceKind::Buffer || BufferComponentCount(inst->Opcode()) == 0u || memory.dataBits != 32u || memory.formatted || memory.typed || memory.d16 || memory.idxen) Fail("only untyped 32-bit geometry ring accesses without an index are supported", inst->Flags().pc); + return true; + } + + IrValue& constant(std::uint32_t value) { + IrValue& result = program.CreateValue(IrOpcode::Void, IrType::U32); + result.SetImmediateU32(value); + return result; + } + + IrValue& insert(IrBlock& block, IrValue& position, IrOpcode opcode, IrType type, std::initializer_list arguments) { + IrValue& value = program.CreateValue(opcode, type); + for (IrValue* argument : arguments) value.AddArgument(argument); + block.InsertInstructionBefore(&position, &value); + return value; + } + + IrValue& storeData(IrBlock& block, IrValue& inst, std::uint32_t components, std::uint32_t component) { + if (components == 1u) return *inst.Argument(4u); + const auto extract = components == 2u ? IrOpcode::CompositeExtractU32x2 : components == 3u ? IrOpcode::CompositeExtractU32x3 : IrOpcode::CompositeExtractU32x4; + return insert(block, inst, extract, IrType::U32, {inst.Argument(4u), &constant(component)}); + } + + void rewrite(IrBlock& block, IrValue& inst) { + const auto flags = inst.Flags(); + const auto memory = program.Resources().memoryInfo.at(flags.index); + const auto components = BufferComponentCount(inst.Opcode()); + const bool write = BufferAccessOf(inst.Opcode()) == BufferAccess::Write; + IrValue* predicate = inst.Argument(inst.ArgumentCount() - 1u); + if (!write && BufferAccessOf(inst.Opcode()) != BufferAccess::Read) Fail("an atomic geometry ring access is unsupported", flags.pc); + if (stage == IrShaderStage::Vertex) { + if (!write || !IsBase(inst.Argument(3), TessellationBaseKind::EsGsOffset)) Fail("an export program reads a geometry ring", flags.pc); + const auto offset = memory.offen ? Evaluate(inst.Argument(2)) : std::optional{Term{}}; + if (!offset || offset->vertex) Fail("an ESGS ring store at an address computed per lane is unsupported", flags.pc); + const auto address = offset->constant + memory.offset; + if (address < 0 || (address & 3) != 0 || address + 4 * static_cast(components) > static_cast(geometry.esgsItemDwords) * 4) Fail("an ESGS ring store outside VGT_ESGS_RING_ITEMSIZE", flags.pc); + for (std::uint32_t component = 0; component < components; ++component) { + static_cast(insert(block, inst, IrOpcode::SetTessellationAttribute, IrType::Void, {&constant(static_cast(TessellationAttribute::LocalOutput)), &constant(static_cast(address) + 4u * component), &storeData(block, inst, components, component), predicate})); + } + } else if (write) { + if (!IsBase(inst.Argument(3), TessellationBaseKind::GsVsOffset)) Fail("a geometry program writes the ESGS ring", flags.pc); + const auto offset = memory.offen ? Evaluate(inst.Argument(2)) : std::optional{Term{}}; + if (offset && offset->vertex) Fail("a GSVS ring store addressed by an ES vertex offset", flags.pc); + for (std::uint32_t component = 0; component < components; ++component) { + const auto bytes = memory.offset + 4u * component; + IrValue* address = nullptr; + if (offset) { + const auto value = offset->constant + bytes; + if (value < 0 || (value & 3) != 0) Fail("an unaligned GSVS ring store", flags.pc); + address = &constant(static_cast(value)); + } else { + address = bytes == 0u ? inst.Argument(2) : &insert(block, inst, IrOpcode::IAdd32, IrType::U32, {inst.Argument(2), &constant(bytes)}); + } + static_cast(insert(block, inst, IrOpcode::SetTessellationAttribute, IrType::Void, {&constant(static_cast(TessellationAttribute::GeometryRing)), address, &storeData(block, inst, components, component), predicate})); + } + } else { + if (components != 1u) Fail("only dword ESGS ring reads are supported", flags.pc); + if (IsGeometryBase(inst.Argument(3))) Fail("an ESGS ring read offset by a geometry ring base", flags.pc); + const auto offset = memory.offen ? Evaluate(inst.Argument(2)) : std::nullopt; + const auto scalar = Evaluate(inst.Argument(3)); + if (!offset || !offset->vertex || !scalar || scalar->vertex) Fail("an ESGS ring read whose vertex is not one of the primitive's input vertices", flags.pc); + if (offset->scale != 4) Fail("an ESGS ring read that does not scale the ES vertex offset by 4", flags.pc); + if (*offset->vertex >= geometry.inputVertices) Fail("an ESGS ring read of a vertex the input primitive does not have", flags.pc); + const auto bytes = offset->constant + scalar->constant + memory.offset; + if (bytes < 0 || bytes % EsGsComponentBytes != 0 || bytes / EsGsComponentBytes >= geometry.esgsItemDwords) Fail("an ESGS ring read outside VGT_ESGS_RING_ITEMSIZE or between components", flags.pc); + const auto address = *offset->vertex * geometry.esgsItemDwords * 4u + static_cast(bytes / EsGsComponentBytes) * 4u; + inst.ReplaceAllUsesWith(&insert(block, inst, IrOpcode::GetTessellationAttribute, IrType::U32, {&constant(static_cast(TessellationAttribute::GeometryInput)), &constant(address), predicate})); + } + block.RemoveInstruction(&inst); + inst.Invalidate(); + } + + std::uint32_t addExport(const GeometryCopyExport& copy) { + ExportInfo info; + info.kind = CopyTargetKind(copy.target, info.index); + if (info.kind == ExportTargetKind::Unknown) Fail("the copy program exports a target other than a position or a parameter", 0u); + info.target = copy.target; + info.en = copy.enable; + info.done = copy.done; + const auto index = static_cast(program.Metadata().exportInfo.size()); + program.Metadata().exportInfo.push_back(info); + return index; + } + + void copyOutputs(IrBlock& block, IrValue& emit, const std::vector& exportIndices) { + if (!emit.Argument(1)->Resolve()->HasImmediate()) Fail("a geometry emit message without an immediate operation", 0u); + if ((emit.Argument(1)->Resolve()->ImmediateU32() & 2u) == 0u) return; + IrValue* exec = emit.Argument(0); + for (std::size_t index = 0; index < geometry.exports.size(); ++index) { + const auto& copy = geometry.exports[index]; + std::array values{}; + for (std::uint32_t component = 0; component < 4u; ++component) { + if ((copy.enable & (1u << component)) == 0u) { + values[component] = &constant(0u); + } else if ((copy.constants & (1u << component)) != 0u) { + values[component] = &constant(copy.values[component]); + } else { + values[component] = &insert(block, emit, IrOpcode::GetTessellationAttribute, IrType::U32, {&constant(static_cast(TessellationAttribute::GeometryEmitted)), &constant(copy.values[component] * 4u), exec}); + } + } + IrValue& data = insert(block, emit, IrOpcode::CompositeConstructU32x4, IrType::U32x4, {values[0], values[1], values[2], values[3]}); + IrValue& store = insert(block, emit, IrOpcode::SetAttribute, IrType::Void, {&data, exec}); + store.SetFlags(ExportFlags{exportIndices[index], 0u}); + } + } + + IrProgram& program; + const ShaderGeometryInputInfo& geometry; + IrShaderStage stage; +}; + +struct CopySource { + bool vertexOffset = false; + bool constant = false; + std::optional slot; + std::uint32_t value = 0; +}; + +std::optional OperandConstant(const RdnaOperand& operand) { + if (operand.kind == RdnaOperandKind::IntegerInlineConstant || operand.kind == RdnaOperandKind::FloatInlineConstant || operand.kind == RdnaOperandKind::LiteralConstant) return operand.value; + return std::nullopt; +} + +void Forget(std::map& vectors, std::map& scalars, const RdnaInstruction& instruction) { + for (const auto* destination : {&instruction.destination, &instruction.destination2}) { + const auto count = std::max(instruction.dataDwordCount, 1u) + (instruction.is64Bit ? 1u : 0u); + for (std::uint32_t reg = 0; reg < count; ++reg) { + if (destination->kind == RdnaOperandKind::VectorRegister) vectors.erase(destination->reg + reg); + if (destination->kind == RdnaOperandKind::ScalarRegister) scalars.erase(destination->reg + reg); + } + } +} + +} + +void GeometryLowering::Lower(IrProgram& program, const ShaderGeometryInputInfo& geometry) const { + Lowering(program, geometry).Run(); +} + +std::vector ParseGeometryCopyProgram(std::span code, std::uint32_t maxVertices, std::uint32_t vertexDwords) { + if (maxVertices == 0u || vertexDwords == 0u) throw std::runtime_error("geometry copy program: VGT_GS_MAX_VERT_OUT and VGT_GS_VERT_ITEMSIZE must be nonzero"); + const auto program = RdnaInstructionDecoder{}.Decode(code); + std::map vectors; + std::map scalars; + std::vector exports; + const auto slotBytes = maxVertices * GsVsVertexBytes; + for (const auto& instruction : program.instructions) { + const auto pc = instruction.programCounter; + if (instruction.op == RdnaOpcode::SEndpgm) break; + if (instruction.op == RdnaOpcode::SMovkI32 || instruction.op == RdnaOpcode::SMovB32) { + const auto value = OperandConstant(instruction.source0); + Forget(vectors, scalars, instruction); + if (value && instruction.destination.kind == RdnaOperandKind::ScalarRegister) scalars[instruction.destination.reg] = *value; + continue; + } + if (instruction.op == RdnaOpcode::VLshlrevB32 && instruction.source1.kind == RdnaOperandKind::VectorRegister && instruction.source1.reg == 0u && OperandConstant(instruction.source0) == 2u && !vectors.contains(0u)) { + Forget(vectors, scalars, instruction); + vectors[instruction.destination.reg] = CopySource{true}; + continue; + } + if (instruction.op == RdnaOpcode::VMovB32) { + const auto value = OperandConstant(instruction.source0); + const auto source = instruction.source0.kind == RdnaOperandKind::VectorRegister ? vectors.find(instruction.source0.reg) : vectors.end(); + const auto copied = source != vectors.end() ? std::optional(source->second) : std::nullopt; + Forget(vectors, scalars, instruction); + if (value) vectors[instruction.destination.reg] = CopySource{false, true, std::nullopt, *value}; + else if (copied) vectors[instruction.destination.reg] = *copied; + continue; + } + if (instruction.op == RdnaOpcode::BufferLoadDword && instruction.family == RdnaInstructionFamily::MUBUF) { + Forget(vectors, scalars, instruction); + const auto address = vectors.find(instruction.source0.reg); + if (!instruction.offen || instruction.idxen || address == vectors.end() || !address->second.vertexOffset) FailCopy("a GSVS ring read not addressed by the vertex index times 4", pc); + std::optional soffset = OperandConstant(instruction.source2); + if (instruction.source2.kind == RdnaOperandKind::ScalarRegister) { + const auto found = scalars.find(instruction.source2.reg); + if (found != scalars.end()) soffset = found->second; + } + if (!soffset) FailCopy("a GSVS ring read whose scalar offset is not a constant", pc); + const auto bytes = static_cast(*soffset) + instruction.memoryOffset; + if (bytes % slotBytes != 0u || bytes / slotBytes >= vertexDwords) FailCopy("a GSVS ring read at " + std::to_string(bytes) + " bytes, which is not one of the " + std::to_string(vertexDwords) + " vertex dwords of " + std::to_string(slotBytes) + " bytes each", pc); + vectors[instruction.destination.reg] = CopySource{false, false, static_cast(bytes / slotBytes)}; + continue; + } + if (instruction.op == RdnaOpcode::Exp) { + if (instruction.exportIsCompressed) FailCopy("a compressed export", pc); + GeometryCopyExport copy; + copy.target = instruction.exportTarget; + copy.enable = instruction.exportEnableMask & 0xfu; + copy.done = instruction.exportIsLast; + std::uint32_t index = 0; + if (CopyTargetKind(copy.target, index) == ExportTargetKind::Unknown) FailCopy("an export to target " + std::to_string(copy.target) + ", which is not a position or a parameter", pc); + const std::array sources{&instruction.source0, &instruction.source1, &instruction.source2, &instruction.source3}; + for (std::uint32_t component = 0; component < 4u; ++component) { + if ((copy.enable & (1u << component)) == 0u) continue; + const auto found = vectors.find(sources[component]->reg); + if (found == vectors.end() || found->second.vertexOffset) FailCopy("an exported value other than a GSVS ring dword or a constant", pc); + if (found->second.constant) { + copy.constants |= 1u << component; + copy.values[component] = found->second.value; + } else { + copy.values[component] = *found->second.slot; + } + } + for (const auto& previous : exports) { + if (previous.target == copy.target) FailCopy("the export target " + std::to_string(copy.target) + " is written twice", pc); + } + exports.push_back(copy); + continue; + } + Forget(vectors, scalars, instruction); + } + bool position = false; + for (const auto& copy : exports) position = position || copy.target == 0x0cu; + if (!position) throw std::runtime_error("geometry copy program: no position 0 export"); + return exports; +} + +} diff --git a/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp b/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp index 4c475098ba05..0d368795eca3 100644 --- a/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp +++ b/core/shader/recompiler/Optimization/src/ShaderInfoCollector.cpp @@ -45,6 +45,7 @@ void ValidateOptions(const IrProgram& program, ShaderStageInputInfo inputInfo) { case IrShaderStage::Local: case IrShaderStage::TessellationControl: case IrShaderStage::TessellationEvaluation: + case IrShaderStage::Geometry: case IrShaderStage::Mesh: if (inputInfo.vertex == nullptr) { return Fail("vertex shader has no input metadata"); @@ -234,7 +235,7 @@ void ValidateValueReferences(const IrProgram& program, ShaderStageInputInfo inpu const auto& exportInfo = program.Metadata().exportInfo[index]; const auto stage = program.Resources().stage; if (exportInfo.kind == ExportTargetKind::Position && exportInfo.index != 0u && exportInfo.en != 0u && - stage != IrShaderStage::Vertex && stage != IrShaderStage::Mesh && stage != IrShaderStage::TessellationEvaluation) { + stage != IrShaderStage::Vertex && stage != IrShaderStage::Mesh && stage != IrShaderStage::TessellationEvaluation && stage != IrShaderStage::Geometry) { return Fail("auxiliary position export requires a vertex, mesh, or tessellation evaluation shader"); } break; @@ -637,6 +638,7 @@ void ShaderInfoCollector::Collect(IrProgram& program, const ShaderStageInputInfo break; case IrShaderStage::TessellationControl: case IrShaderStage::TessellationEvaluation: + case IrShaderStage::Geometry: break; case IrShaderStage::Mesh: AddInput(next, StageInputKind::LocalInvocationIndex, 0, 1, "gl_LocalInvocationIndex"); diff --git a/core/shader/recompiler/Recompiler.cpp b/core/shader/recompiler/Recompiler.cpp index 5e70c4b95608..0e4fa8af702d 100644 --- a/core/shader/recompiler/Recompiler.cpp +++ b/core/shader/recompiler/Recompiler.cpp @@ -50,6 +50,7 @@ #include "Optimization/include/Optimization/ShaderInfoCollector.hpp" #include "Optimization/include/Optimization/SrtWalker.hpp" #include "Optimization/include/Optimization/SsaBuilder.hpp" +#include "Optimization/include/Optimization/GeometryLowering.hpp" #include "Optimization/include/Optimization/TessellationLowering.hpp" #include "SpirvBackend/include/SpirvBackend/SpirvEmitter.hpp" #if ANYPS5_ENABLE_SPIRV_TOOLS @@ -84,7 +85,7 @@ ShaderStageKind toShaderStageKind(ShaderStage stage) { case ShaderStage::Mesh: return ShaderStageKind::Mesh; case ShaderStage::Geometry: - break; + return ShaderStageKind::Geometry; } throw std::runtime_error("ShaderRecompiler::Recompile: unsupported shader stage"); } @@ -105,6 +106,7 @@ std::uint32_t HostSubgroupSize(const RecompileRequest& request) { if (vertexStage && !request.target.vertexSubgroups) return 1u; if (request.shader.stage == ShaderStage::TessellationEvaluation && !request.target.tessellationEvaluationSubgroups && !(request.graphics && request.graphics->mesh)) return 1u; if (request.shader.stage == ShaderStage::TessellationControl && MergedHullStage(request)) return 1u; + if (request.shader.stage == ShaderStage::Geometry) return 1u; static const std::string list = [] { const char* text = std::getenv("APS5_SINGLE_LANE"); return text ? std::string(text) : std::string(); }(); if (!list.empty()) { if (list == "all") return 64u; @@ -153,19 +155,21 @@ ShaderStageInputInfo RequestInputInfo(const RecompileRequest& request) { tessellationCopy->drawParameters = std::find(capabilities.begin(), capabilities.end(), static_cast(spv::CapabilityDrawParameters)) != capabilities.end(); } const auto* tessellation = tessellationCopy ? &*tessellationCopy : nullptr; - return BuildShaderStageInputInfo(toShaderStageKind(request.shader.stage), request.context, HostSubgroupSize(request), mesh, tessellation); + const auto* geometry = request.graphics && request.graphics->geometry ? &*request.graphics->geometry : nullptr; + return BuildShaderStageInputInfo(toShaderStageKind(request.shader.stage), request.context, HostSubgroupSize(request), mesh, tessellation, geometry); } void ValidateRequestInputs(const RecompileRequest& request) { const auto stage = toShaderStageKind(request.shader.stage); - const bool vertexFamily = stage == ShaderStageKind::Vertex || stage == ShaderStageKind::Local || stage == ShaderStageKind::TessellationControl || stage == ShaderStageKind::TessellationEvaluation || stage == ShaderStageKind::Mesh; + const bool vertexFamily = stage == ShaderStageKind::Vertex || stage == ShaderStageKind::Local || stage == ShaderStageKind::TessellationControl || stage == ShaderStageKind::TessellationEvaluation || stage == ShaderStageKind::Mesh || stage == ShaderStageKind::Geometry; if (!vertexFamily) { static_cast(RequestInputInfo(request)); return; } const auto* mesh = request.graphics && request.graphics->mesh ? &*request.graphics->mesh : nullptr; const auto* tessellation = request.graphics && request.graphics->tessellation ? &*request.graphics->tessellation : nullptr; - ValidateVertexStageInputs(stage, request.context, mesh, tessellation); + const auto* geometry = request.graphics && request.graphics->geometry ? &*request.graphics->geometry : nullptr; + ValidateVertexStageInputs(stage, request.context, mesh, tessellation, geometry); } std::uint32_t DeviceMemoryLdsBytes(const RecompileRequest& request) { @@ -378,6 +382,10 @@ IrProgram PrepareResourceProgram(const RecompileRequest& request, ShaderPreparat if (nanPayloadEliminator.Eliminate(program).removedSelects != 0u) deadCodeEliminator.Eliminate(program); } + if (inputInfo.vertex != nullptr && inputInfo.vertex->geometry.active) { + constexpr GeometryLowering geometryLowering; + geometryLowering.Lower(program, inputInfo.vertex->geometry); + } if (inputInfo.vertex != nullptr) { constexpr TessellationLowering tessellationLowering; tessellationLowering.Lower(program, inputInfo.vertex->tess, request.target.tessellation ? &*request.target.tessellation : nullptr); diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index c46af2af968d..62a4d5ffd075 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -402,9 +402,15 @@ enum class ProgramRole { Local, Hull, Domain, - Fragment + Fragment, + Geometry, + Copy }; +constexpr bool LinkedOnlyRole(ProgramRole role) { + return role == ProgramRole::GeometryBack || role == ProgramRole::Copy; +} + struct LinkedProgram { ProgramRole role; ShaderBinary binary; @@ -426,6 +432,28 @@ struct MeshConfiguration { std::uint32_t outputPrimitiveSize = 3; }; +struct GeometryCopyExport { + std::uint32_t target = 0; + std::uint32_t enable = 0; + std::uint32_t constants = 0; + std::array values{}; + bool done = false; + bool operator==(const GeometryCopyExport&) const = default; +}; + +struct GeometryConfiguration { + std::uint32_t inputVertices = 3; + std::uint32_t outputTopology = 2; + std::uint32_t maxVertices = 1; + std::uint32_t instances = 1; + std::uint32_t esgsItemDwords = 0; + std::uint32_t vertexDwords = 0; + std::vector exports; + bool operator==(const GeometryConfiguration&) const = default; +}; + +[[nodiscard]] std::vector ParseGeometryCopyProgram(std::span code, std::uint32_t maxVertices, std::uint32_t vertexDwords); + struct TessellationConfiguration { std::uint32_t inputControlPoints; std::uint32_t outputControlPoints; @@ -504,6 +532,7 @@ struct GraphicsCompileContext { std::optional tessellation; GraphicsDrawParameters draw; std::optional meshBarycentrics; + std::optional geometry; }; struct RecompileRequest { diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp index f6188a05bc91..eb5f63682fd1 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterHelpers.hpp @@ -91,6 +91,7 @@ void DefineDescriptors(SpirvEmitterState& state); void DefineModule(SpirvEmitterState& state); void DefineTessellationInterfaces(SpirvEmitterState& state); void DefineTessellationExecutionModes(SpirvEmitterState& state); +void DefineGeometryExecutionModes(SpirvEmitterState& state); void DefineMeshOutputs(SpirvEmitterState& state); void EmitMeshEntryPoint(SpirvEmitterState& state); void EmitMeshAllocate(SpirvValueEmitContext& ctx, const IrValue& inst); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterInstructions.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterInstructions.hpp index 79addfc7619d..3b11b2b2a1c0 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterInstructions.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterInstructions.hpp @@ -80,6 +80,7 @@ std::uint32_t EmitMeshRestartStart(SpirvValueEmitContext& ctx, const IrValue& in std::uint32_t EmitMeshCapturedWord(SpirvValueEmitContext& ctx, const IrValue& inst); std::uint32_t EmitGetTessellationAttribute(SpirvValueEmitContext& ctx, const IrValue& inst); void EmitSetTessellationAttribute(SpirvValueEmitContext& ctx, const IrValue& inst); +void EmitGeometryVertex(SpirvValueEmitContext& ctx, const IrValue& inst); std::uint32_t EmitGetUserData(SpirvEmitterState& state, ScalarReg reg); std::uint32_t EmitGetBuiltin(SpirvValueEmitContext& ctx, const IrValue* kind, const IrValue* index); std::uint32_t EmitUndefU1(SpirvEmitterState& state, const IrValue& inst); diff --git a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp index f6d7d81c14bc..16563a4f9715 100644 --- a/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp +++ b/core/shader/recompiler/SpirvBackend/include/SpirvBackend/SpirvEmitterState.hpp @@ -96,8 +96,9 @@ struct SpirvEmitterState { const IrProgram& program; ShaderStageInputInfo inputInfo; std::unordered_map>> normalizedSampleImages; - std::array tessVariables {}; + std::array tessVariables {}; std::uint32_t tessInnerVariable = 0; + std::uint32_t geometryCountVariable = 0; SpirvRequirements requirements; std::uint32_t laneCount = 1; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvAlu/SpirvAluEmitterMath.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvAlu/SpirvAluEmitterMath.cpp index 69089cd29a64..3953bbf0dbce 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvAlu/SpirvAluEmitterMath.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvAlu/SpirvAluEmitterMath.cpp @@ -341,7 +341,7 @@ bool HelperOrFalseConjunct(const IrValue* bit) { } bool EveryInvocationEnters(IrShaderStage stage) { - return stage == IrShaderStage::Vertex || stage == IrShaderStage::Local || stage == IrShaderStage::TessellationControl || stage == IrShaderStage::TessellationEvaluation; + return stage == IrShaderStage::Vertex || stage == IrShaderStage::Local || stage == IrShaderStage::TessellationControl || stage == IrShaderStage::TessellationEvaluation || stage == IrShaderStage::Geometry; } class EntryLaneWalk { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp index a6c90173d944..d5ba97ebb1bf 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvEmitter.cpp @@ -249,7 +249,7 @@ std::vector SpirvEmitter::Emit(const IrProgram& program, const Co } std::vector SpirvEmitter::Emit(const IrProgram& program, const ShaderStageInputInfo& inputInfo, const CompiledBindingLayout& bindings, const SpirvTargetOptions& target, SpirvEmitInfo* info) const { - if (program.Resources().stage != IrShaderStage::Compute && program.Resources().stage != IrShaderStage::Vertex && program.Resources().stage != IrShaderStage::Pixel && program.Resources().stage != IrShaderStage::Mesh && program.Resources().stage != IrShaderStage::Local && program.Resources().stage != IrShaderStage::TessellationControl && program.Resources().stage != IrShaderStage::TessellationEvaluation) { + if (program.Resources().stage != IrShaderStage::Compute && program.Resources().stage != IrShaderStage::Vertex && program.Resources().stage != IrShaderStage::Pixel && program.Resources().stage != IrShaderStage::Mesh && program.Resources().stage != IrShaderStage::Local && program.Resources().stage != IrShaderStage::TessellationControl && program.Resources().stage != IrShaderStage::TessellationEvaluation && program.Resources().stage != IrShaderStage::Geometry) { FailProgram(program, "binary SPIR-V emitter received an unsupported shader stage"); } if (!program.Resources().srtPlanComplete || !program.Resources().resourceTrackingComplete || !program.Metadata().shaderInfoComplete || !program.Metadata().bindingLayoutComplete) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp index 3f5baea97e7d..4aad07de0f4f 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp @@ -325,6 +325,7 @@ void EmitDirectInstruction(SpirvValueEmitContext& ctx, const IrValue& inst) { case IrOpcode::TessellationBase: return Invoke(EmitTessellationBase, ctx, inst); case IrOpcode::GetTessellationAttribute: return Invoke(EmitGetTessellationAttribute, ctx, inst); case IrOpcode::SetTessellationAttribute: return Invoke(EmitSetTessellationAttribute, ctx, inst); + case IrOpcode::EmitVertex: return Invoke(EmitGeometryVertex, ctx, inst); case IrOpcode::GetBuiltin: return Invoke(EmitGetBuiltin, ctx, inst); case IrOpcode::GetThreadBitScalarRegister: return Invoke(EmitGetThreadBitScalarRegister, ctx, inst); case IrOpcode::SetThreadBitScalarRegister: return Invoke(EmitSetThreadBitScalarRegister, ctx, inst); diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp index 63e75e3a2951..31b11b2f4af7 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvEmitterHelpers.cpp @@ -408,7 +408,7 @@ void DefineOutputs(SpirvEmitterState& state) { } const auto stage = state.program.Resources().stage; const bool exportsPosition = std::ranges::any_of(state.outputs, [](const SpirvOutputBinding& output) { return output.kind == StageOutputKind::Position; }); - if (exportsPosition && (stage == IrShaderStage::Vertex || stage == IrShaderStage::TessellationEvaluation) && clipDistanceCount + cullDistanceCount < MaxClipDistances) { + if (exportsPosition && (stage == IrShaderStage::Vertex || stage == IrShaderStage::TessellationEvaluation || stage == IrShaderStage::Geometry) && clipDistanceCount + cullDistanceCount < MaxClipDistances) { if (std::ranges::find(state.supportedCapabilities, spv::CapabilityClipDistance) == state.supportedCapabilities.end()) { FailEmit("clipping a primitive with an all-zero clip position needs shaderClipDistance on the target device"); } diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp index 3ff4f6fec117..347236fafe64 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvModuleSetup.cpp @@ -32,6 +32,7 @@ std::uint32_t ExecutionModelForStage(IrShaderStage stage) { case IrShaderStage::Vertex: return spv::ExecutionModelVertex; case IrShaderStage::TessellationControl: return spv::ExecutionModelTessellationControl; case IrShaderStage::TessellationEvaluation: return spv::ExecutionModelTessellationEvaluation; + case IrShaderStage::Geometry: return spv::ExecutionModelGeometry; case IrShaderStage::Mesh: return spv::ExecutionModelMeshEXT; case IrShaderStage::Pixel: return spv::ExecutionModelFragment; case IrShaderStage::Compute: return spv::ExecutionModelGLCompute; @@ -369,6 +370,9 @@ void DefineModule(SpirvEmitterState& state) { if (StageOf(state) == IrShaderStage::TessellationControl || StageOf(state) == IrShaderStage::TessellationEvaluation) { DefineTessellationExecutionModes(state); } + if (StageOf(state) == IrShaderStage::Geometry) { + DefineGeometryExecutionModes(state); + } state.entryLabel = state.module.AllocateId(); EmitBaseHeader(state.module, state.program, state.requirements.imageAtomicLocks || state.requirements.bufferAtomicLocks); for (const auto capability : state.requirements.capabilities) { diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp index 5e4822cbf3a4..ec4cf0d64553 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp @@ -1112,6 +1112,38 @@ std::uint32_t TessellationOuterFactors(const SpirvEmitterState& state) { return state.inputInfo.vertex->tess.domain == 2u ? 4u : 3u; } +std::uint32_t GeometryRingElement(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index) { + const auto& geometry = state.inputInfo.vertex->geometry; + const auto clamped = state.module.AllocateId(); + state.module.AddFunction(spv::OpExtInst, TypeU32(state), clamped, GlslStd450(state), GLSLstd450UMin, index, ConstantU32(state, geometry.vertexDwords * geometry.maxVertices - 1u)); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassPrivate, TypeU32(state)), pointer, variable, clamped); + return pointer; +} + +std::uint32_t GeometryPointer(SpirvValueEmitContext& ctx, const IrValue& inst, TessellationAttribute kind, std::uint32_t variable) { + auto& state = ctx.state; + const auto& geometry = state.inputInfo.vertex->geometry; + const auto address = ctx.Arg(inst, 1); + const auto dword = EmitBinaryU32(state, spv::OpShiftRightLogical, address, ConstantU32(state, 2u)); + if (kind == TessellationAttribute::GeometryRing) return GeometryRingElement(state, variable, dword); + if (kind == TessellationAttribute::GeometryEmitted) { + const auto count = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), count, state.geometryCountVariable); + return GeometryRingElement(state, variable, EmitBinaryU32(state, spv::OpIAdd, EmitBinaryU32(state, spv::OpIMul, dword, ConstantU32(state, geometry.maxVertices)), count)); + } + const auto stride = state.program.Metadata().tessellationLocalStride; + if (stride == 0u || stride % 4u != 0u) ctx.Fail(inst, "reads an ES record without its ESGS item size"); + const auto vertex = state.module.AllocateId(); + state.module.AddFunction(spv::OpExtInst, TypeU32(state), vertex, GlslStd450(state), GLSLstd450UMin, EmitBinaryU32(state, spv::OpUDiv, address, ConstantU32(state, stride)), ConstantU32(state, geometry.inputVertices - 1u)); + const auto offset = EmitBinaryU32(state, spv::OpUMod, address, ConstantU32(state, stride)); + const auto attribute = EmitBinaryU32(state, spv::OpShiftRightLogical, offset, ConstantU32(state, 4u)); + const auto component = EmitBinaryU32(state, spv::OpBitwiseAnd, EmitBinaryU32(state, spv::OpShiftRightLogical, offset, ConstantU32(state, 2u)), ConstantU32(state, 3u)); + const auto pointer = state.module.AllocateId(); + state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassInput, TypeU32(state)), pointer, variable, vertex, attribute, component); + return pointer; +} + std::uint32_t TessellationPointer(SpirvValueEmitContext& ctx, const IrValue& inst) { auto& state = ctx.state; const auto kind = static_cast(inst.Argument(0)->ImmediateU32()); @@ -1119,6 +1151,12 @@ std::uint32_t TessellationPointer(SpirvValueEmitContext& ctx, const IrValue& ins if (variable == 0u) { throw std::runtime_error("tessellation attribute has no interface variable"); } + if (kind == TessellationAttribute::GeometryInput || kind == TessellationAttribute::GeometryRing || kind == TessellationAttribute::GeometryEmitted) { + if (state.program.Resources().stage != IrShaderStage::Geometry) ctx.Fail(inst, "accesses a geometry record outside a geometry program"); + if (kind == TessellationAttribute::GeometryEmitted && inst.Opcode() != IrOpcode::GetTessellationAttribute) ctx.Fail(inst, "writes the emitted vertex record"); + if (kind == TessellationAttribute::GeometryInput && inst.Opcode() != IrOpcode::GetTessellationAttribute) ctx.Fail(inst, "writes an ES record"); + return GeometryPointer(ctx, inst, kind, variable); + } const bool input = kind == TessellationAttribute::ControlInput || kind == TessellationAttribute::EvaluationInput || kind == TessellationAttribute::PatchInput || kind == TessellationAttribute::InstanceInput; const auto storage = input ? spv::StorageClassInput : spv::StorageClassOutput; if (kind == TessellationAttribute::InstanceOutput) { @@ -1194,7 +1232,7 @@ std::uint32_t TessellationPointer(SpirvValueEmitContext& ctx, const IrValue& ins } void DefineTessellationInterfaces(SpirvEmitterState& state) { - std::array used {}; + std::array used {}; for (const IrBlock* block : state.program.BlockOrder()) { for (const IrValue* inst : block->Instructions()) { if (inst->Opcode() != IrOpcode::GetTessellationAttribute && inst->Opcode() != IrOpcode::SetTessellationAttribute) { @@ -1203,6 +1241,10 @@ void DefineTessellationInterfaces(SpirvEmitterState& state) { used.at(inst->Argument(0)->ImmediateU32()) = true; } } + if (state.program.Resources().stage == IrShaderStage::Geometry) { + state.geometryCountVariable = state.module.DefineInitializedGlobalVariable(TypePointer(state, spv::StorageClassPrivate, TypeU32(state)), spv::StorageClassPrivate, ConstantU32(state, 0u)); + if (state.spirvVersion >= 0x00010400u) state.interfaceVariables.push_back(state.geometryCountVariable); + } if (std::none_of(used.begin(), used.end(), [](bool value) { return value; })) { return; } @@ -1215,6 +1257,27 @@ void DefineTessellationInterfaces(SpirvEmitterState& state) { continue; } const auto kind = static_cast(index); + if (kind == TessellationAttribute::GeometryRing || kind == TessellationAttribute::GeometryEmitted) { + const auto ring = static_cast(TessellationAttribute::GeometryRing); + const auto emitted = static_cast(TessellationAttribute::GeometryEmitted); + if (state.tessVariables.at(ring) == 0u) { + const auto& geometry = state.inputInfo.vertex->geometry; + const auto ringType = array(TypeU32(state), geometry.vertexDwords * geometry.maxVertices); + const auto variable = state.module.DefineInitializedGlobalVariable(TypePointer(state, spv::StorageClassPrivate, ringType), spv::StorageClassPrivate, state.module.Constant(spv::OpConstantNull, ringType)); + if (state.spirvVersion >= 0x00010400u) state.interfaceVariables.push_back(variable); + state.tessVariables.at(ring) = variable; + state.tessVariables.at(emitted) = variable; + } + continue; + } + if (kind == TessellationAttribute::GeometryInput) { + const auto& geometry = state.inputInfo.vertex->geometry; + const auto type = array(array(TypeU32Vector(state, 4u), (state.program.Metadata().tessellationLocalStride + 15u) / 16u), geometry.inputVertices); + auto& variable = state.tessVariables.at(index); + variable = DefineInterfaceVariable(state, type, spv::StorageClassInput, "geometry_inputs"); + state.module.AddAnnotation(spv::OpDecorate, variable, spv::DecorationLocation, 0u); + continue; + } const bool input = kind == TessellationAttribute::ControlInput || kind == TessellationAttribute::EvaluationInput || kind == TessellationAttribute::PatchInput || kind == TessellationAttribute::InstanceInput; const bool patch = kind == TessellationAttribute::PatchOutput || kind == TessellationAttribute::PatchInput; const auto storage = input ? spv::StorageClassInput : spv::StorageClassOutput; @@ -1273,6 +1336,18 @@ void DefineTessellationExecutionModes(SpirvEmitterState& state) { } } +void DefineGeometryExecutionModes(SpirvEmitterState& state) { + const auto& geometry = state.inputInfo.vertex->geometry; + if (!geometry.active || geometry.inputVertices == 0u || geometry.inputVertices > 3u || geometry.outputTopology > 2u || geometry.maxVertices == 0u || geometry.instances == 0u) { + throw std::runtime_error("unsupported geometry input primitive, output topology, vertex count or instance count"); + } + state.module.EmitCapability(spv::CapabilityGeometry); + state.module.AddExecutionMode(state.mainFunc, geometry.inputVertices == 1u ? spv::ExecutionModeInputPoints : geometry.inputVertices == 2u ? spv::ExecutionModeInputLines : spv::ExecutionModeTriangles); + state.module.AddExecutionMode(state.mainFunc, spv::ExecutionModeInvocations, geometry.instances); + state.module.AddExecutionMode(state.mainFunc, geometry.outputTopology == 0u ? spv::ExecutionModeOutputPoints : geometry.outputTopology == 1u ? spv::ExecutionModeOutputLineStrip : spv::ExecutionModeOutputTriangleStrip); + state.module.AddExecutionMode(state.mainFunc, spv::ExecutionModeOutputVertices, geometry.maxVertices); +} + void DefineMeshOutputs(SpirvEmitterState& state) { if (state.inputInfo.vertex == nullptr) { throw std::runtime_error("vertex input info is missing for mesh output definition"); @@ -2280,6 +2355,25 @@ void EmitSetTessellationAttribute(SpirvValueEmitContext& ctx, const IrValue& ins }); } +void EmitGeometryVertex(SpirvValueEmitContext& ctx, const IrValue& inst) { + auto& state = ctx.state; + if (state.program.Resources().stage != IrShaderStage::Geometry || state.geometryCountVariable == 0u || !inst.Argument(1)->HasImmediate()) ctx.Fail(inst, "emits a geometry vertex outside a geometry program"); + const auto operation = inst.Argument(1)->ImmediateU32(); + EmitIfCondition(state, ctx.Arg(inst, 0), [&]() { + if ((operation & 2u) != 0u) { + const auto count = state.module.AllocateId(); + state.module.AddFunction(spv::OpLoad, TypeU32(state), count, state.geometryCountVariable); + const auto room = state.module.AllocateId(); + state.module.AddFunction(spv::OpULessThan, TypeBool(state), room, count, ConstantU32(state, state.inputInfo.vertex->geometry.maxVertices)); + EmitIfCondition(state, room, [&]() { + state.module.AddFunction(spv::OpEmitVertex); + state.module.AddFunction(spv::OpStore, state.geometryCountVariable, EmitBinaryU32(state, spv::OpIAdd, count, ConstantU32(state, 1u))); + }); + } + if ((operation & 1u) != 0u) state.module.AddFunction(spv::OpEndPrimitive); + }); +} + std::uint32_t EmitGetUserData(SpirvEmitterState& state, ScalarReg reg) { std::uint32_t dwordIndex = 0; if (!UserDataDwordIndex(state, reg, dwordIndex)) { diff --git a/core/shader/recompiler/Translation/include/Translation/InstructionTranslator.hpp b/core/shader/recompiler/Translation/include/Translation/InstructionTranslator.hpp index e51be494fe20..add7d3779d0e 100644 --- a/core/shader/recompiler/Translation/include/Translation/InstructionTranslator.hpp +++ b/core/shader/recompiler/Translation/include/Translation/InstructionTranslator.hpp @@ -21,7 +21,8 @@ enum class ShaderStageKind { Mesh, Local, TessellationControl, - TessellationEvaluation + TessellationEvaluation, + Geometry }; struct TranslateOptions { diff --git a/core/shader/recompiler/Translation/include/Translation/ShaderInputInfoBuilder.hpp b/core/shader/recompiler/Translation/include/Translation/ShaderInputInfoBuilder.hpp index 4f7c73ee5c01..de3445322f89 100644 --- a/core/shader/recompiler/Translation/include/Translation/ShaderInputInfoBuilder.hpp +++ b/core/shader/recompiler/Translation/include/Translation/ShaderInputInfoBuilder.hpp @@ -9,8 +9,8 @@ namespace ShaderRecompiler { // hostSubgroupSize is the device subgroup width; wave64 workgroups on 32-wide subgroups run each // invocation as two guest lanes so a guest wave stays one host subgroup. -ShaderStageInputInfo BuildShaderStageInputInfo(ShaderStageKind stage, const GuestContext& context, std::uint32_t hostSubgroupSize, const MeshConfiguration* mesh = nullptr, const TessellationConfiguration* tessellation = nullptr); -void ValidateVertexStageInputs(ShaderStageKind stage, const GuestContext& context, const MeshConfiguration* mesh = nullptr, const TessellationConfiguration* tessellation = nullptr); +ShaderStageInputInfo BuildShaderStageInputInfo(ShaderStageKind stage, const GuestContext& context, std::uint32_t hostSubgroupSize, const MeshConfiguration* mesh = nullptr, const TessellationConfiguration* tessellation = nullptr, const GeometryConfiguration* geometry = nullptr); +void ValidateVertexStageInputs(ShaderStageKind stage, const GuestContext& context, const MeshConfiguration* mesh = nullptr, const TessellationConfiguration* tessellation = nullptr, const GeometryConfiguration* geometry = nullptr); } diff --git a/core/shader/recompiler/Translation/src/ControlFlowInstructions.cpp b/core/shader/recompiler/Translation/src/ControlFlowInstructions.cpp index 4cbfb0585ce8..0fda8d5e798c 100644 --- a/core/shader/recompiler/Translation/src/ControlFlowInstructions.cpp +++ b/core/shader/recompiler/Translation/src/ControlFlowInstructions.cpp @@ -257,6 +257,16 @@ void TranslationContext::sSendmsg(const RdnaInstruction& inst) { (void)ir.Emit(IrOpcode::MeshAllocate, IrType::Void, {&ir.GetM0()}); return; } + constexpr std::uint32_t GsMessage = 2u; + constexpr std::uint32_t GsDoneMessage = 3u; + const auto simm = inst.rawWords[0] & 0xffffu; + if (program.Resources().stage == IrShaderStage::Geometry && ((simm & 0xfu) == GsMessage || (simm & 0xfu) == GsDoneMessage)) { + if ((simm & 0xfu) == GsDoneMessage) return; + if (((simm >> 8u) & 3u) != 0u) throw std::runtime_error("a GCN geometry program emits to vertex stream " + std::to_string((simm >> 8u) & 3u) + ", and only stream 0 is rasterized without stream-out"); + const auto operation = (simm >> 4u) & 3u; + if (operation != 0u) (void)ir.Emit(IrOpcode::EmitVertex, IrType::Void, {&ir.GetExec(), &ir.Constant(operation)}); + return; + } (void)ir.Emit(IrOpcode::Sendmsg, IrType::Void, {}); } diff --git a/core/shader/recompiler/Translation/src/InstructionTranslator.cpp b/core/shader/recompiler/Translation/src/InstructionTranslator.cpp index 4ba4522c1430..69b93b051f6b 100644 --- a/core/shader/recompiler/Translation/src/InstructionTranslator.cpp +++ b/core/shader/recompiler/Translation/src/InstructionTranslator.cpp @@ -2,6 +2,7 @@ #include "Recompiler.hpp" #include "Translation/TranslationContext.hpp" #include +#include #include #include #include @@ -34,6 +35,8 @@ IrShaderStage toIrShaderStage(ShaderStageKind stage) { return IrShaderStage::TessellationControl; case ShaderStageKind::TessellationEvaluation: return IrShaderStage::TessellationEvaluation; + case ShaderStageKind::Geometry: + return IrShaderStage::Geometry; } throw std::runtime_error("InstructionTranslator::Translate unknown shader stage kind"); } @@ -56,6 +59,14 @@ void validateTranslateOptions(const TranslateOptions& options) { throw std::runtime_error("vertex shader translation has no vertex input metadata"); } return; + case ShaderStageKind::Geometry: + if (options.inputInfo.vertex == nullptr || !options.inputInfo.vertex->geometry.active) { + throw std::runtime_error("geometry shader translation has no geometry input metadata"); + } + if (!options.gcnLegacyVertexInputs) { + throw std::runtime_error("a geometry program outside a GCN guest's ES-GS-VS routing is unsupported"); + } + return; case ShaderStageKind::Pixel: if (options.inputInfo.pixel == nullptr) { throw std::runtime_error("pixel shader translation has no pixel input metadata"); @@ -527,10 +538,23 @@ void emitEntryPrologue(IrProgram& program, IrBlock& entryBlock, const TranslateO if (options.gcnLegacyVertexInputs) { setVector(static_cast(0), drawIndex(StageInputKind::VertexIndex)); for (std::uint32_t reg = 1u; reg <= 3u; reg++) setVector(static_cast(reg), drawIndex(StageInputKind::InstanceIndex)); + if (options.inputInfo.vertex->geometry.active) entryIr.SetScalarReg(static_cast(options.userDataBaseRegister + options.userDataCount), tessellationBase(TessellationBaseKind::EsGsOffset)); } else { setVector(static_cast(5), drawIndex(StageInputKind::VertexIndex)); setVector(static_cast(8), drawIndex(StageInputKind::InstanceIndex)); } + } else if (options.stage == ShaderStageKind::Geometry) { + const auto& geometry = options.inputInfo.vertex->geometry; + const auto reg = options.userDataBaseRegister + options.userDataCount; + entryIr.SetScalarReg(static_cast(reg), tessellationBase(TessellationBaseKind::GsVsOffset)); + entryIr.SetScalarReg(static_cast(reg + 1u), entryIr.Constant(0u)); + constexpr std::array vertexRegisters{0u, 1u, 3u, 4u, 5u, 6u}; + for (std::uint32_t vertex = 0; vertex < vertexRegisters.size(); ++vertex) { + IrValue& offset = vertex < geometry.inputVertices ? tessellationBase(static_cast(static_cast(TessellationBaseKind::GeometryVertex) + vertex)) : entryIr.Constant(0u); + setVector(static_cast(vertexRegisters[vertex]), offset); + } + setVector(static_cast(2), builtin(StageInputKind::PrimitiveId)); + setVector(static_cast(7), builtin(StageInputKind::InvocationId)); } } diff --git a/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp b/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp index 19414421c6d9..1c70e4f323b3 100644 --- a/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp +++ b/core/shader/recompiler/Translation/src/ShaderInputInfoBuilder.cpp @@ -15,6 +15,7 @@ IrShaderStage _toIrShaderStage(ShaderStageKind stage) { case ShaderStageKind::TessellationControl: return IrShaderStage::TessellationControl; case ShaderStageKind::TessellationEvaluation: return IrShaderStage::TessellationEvaluation; case ShaderStageKind::Mesh: return IrShaderStage::Mesh; + case ShaderStageKind::Geometry: return IrShaderStage::Geometry; default: throw std::runtime_error("ShaderInputInfoBuilder: unexpected vertex-family stage"); } } @@ -68,6 +69,17 @@ void _validateTessellation(const TessellationConfiguration* tessellation) { if (tessellation->patchesPerGroup == 0u || tessellation->patchesPerGroup > 256u) throw std::runtime_error("ShaderInputInfoBuilder: invalid tessellation patches per group"); } +void _validateGeometry(ShaderStageKind stage, const GeometryConfiguration* geometry) { + if (geometry == nullptr) { + if (stage == ShaderStageKind::Geometry) throw std::runtime_error("ShaderInputInfoBuilder: a geometry program has no geometry configuration"); + return; + } + if (stage != ShaderStageKind::Vertex && stage != ShaderStageKind::Geometry) throw std::runtime_error("ShaderInputInfoBuilder: a geometry configuration is given to a stage other than the export or geometry program"); + if (geometry->inputVertices == 0u || geometry->inputVertices > 3u || geometry->outputTopology > 2u || geometry->maxVertices == 0u || geometry->maxVertices > 1024u || geometry->instances == 0u || geometry->instances > 127u) throw std::runtime_error("ShaderInputInfoBuilder: invalid geometry configuration"); + if (geometry->esgsItemDwords == 0u || geometry->esgsItemDwords > 0x7fffu || geometry->vertexDwords == 0u || geometry->vertexDwords > 0x7fffu) throw std::runtime_error("ShaderInputInfoBuilder: invalid geometry ring item sizes"); + if (stage == ShaderStageKind::Geometry && geometry->exports.empty()) throw std::runtime_error("ShaderInputInfoBuilder: a geometry program has no copy-shader exports"); +} + void _validateMesh(const MeshConfiguration* mesh) { if (mesh == nullptr) throw std::runtime_error("ShaderInputInfoBuilder: a mesh-stage program has no mesh configuration"); if (mesh->threadsPerGroup == 0u || mesh->maxVertices == 0u || mesh->maxPrimitives == 0u || (mesh->outputPrimitiveSize != 1u && mesh->outputPrimitiveSize != 2u && mesh->outputPrimitiveSize != 3u) || mesh->provokingVertex >= mesh->outputPrimitiveSize) throw std::runtime_error("ShaderInputInfoBuilder: invalid mesh configuration"); @@ -75,7 +87,7 @@ void _validateMesh(const MeshConfiguration* mesh) { } -ShaderStageInputInfo BuildShaderStageInputInfo(ShaderStageKind stage, const GuestContext& context, std::uint32_t hostSubgroupSize, const MeshConfiguration* mesh, const TessellationConfiguration* tessellation) { +ShaderStageInputInfo BuildShaderStageInputInfo(ShaderStageKind stage, const GuestContext& context, std::uint32_t hostSubgroupSize, const MeshConfiguration* mesh, const TessellationConfiguration* tessellation, const GeometryConfiguration* geometry) { switch (stage) { case ShaderStageKind::Compute: { if (!context.compute.has_value()) { @@ -192,6 +204,7 @@ ShaderStageInputInfo BuildShaderStageInputInfo(ShaderStageKind stage, const Gues case ShaderStageKind::Local: case ShaderStageKind::TessellationControl: case ShaderStageKind::TessellationEvaluation: + case ShaderStageKind::Geometry: case ShaderStageKind::Mesh: { if (!context.vertex.has_value()) { throw std::runtime_error("ShaderInputInfoBuilder: GuestContext.vertex is not set"); @@ -259,6 +272,18 @@ ShaderStageInputInfo BuildShaderStageInputInfo(ShaderStageKind stage, const Gues if (target.outputPrimitiveSize == 1u) vertexStorage.pointList = true; target.capturedInput = tessellation != nullptr; } + _validateGeometry(stage, geometry); + if (geometry != nullptr) { + auto& target = vertexStorage.geometry; + target.active = true; + target.inputVertices = geometry->inputVertices; + target.outputTopology = geometry->outputTopology; + target.maxVertices = geometry->maxVertices; + target.instances = geometry->instances; + target.esgsItemDwords = geometry->esgsItemDwords; + target.vertexDwords = geometry->vertexDwords; + target.exports = geometry->exports; + } ShaderStageInputInfo result; result.vertex = &vertexStorage; return result; @@ -270,7 +295,7 @@ ShaderStageInputInfo BuildShaderStageInputInfo(ShaderStageKind stage, const Gues throw std::runtime_error("ShaderInputInfoBuilder: unexpected stage"); } -void ValidateVertexStageInputs(ShaderStageKind stage, const GuestContext& context, const MeshConfiguration* mesh, const TessellationConfiguration* tessellation) { +void ValidateVertexStageInputs(ShaderStageKind stage, const GuestContext& context, const MeshConfiguration* mesh, const TessellationConfiguration* tessellation, const GeometryConfiguration* geometry) { if (!context.vertex.has_value()) { throw std::runtime_error("ShaderInputInfoBuilder: GuestContext.vertex is not set"); } @@ -315,6 +340,7 @@ void ValidateVertexStageInputs(ShaderStageKind stage, const GuestContext& contex if (stage == ShaderStageKind::Mesh) { _validateMesh(mesh); } + _validateGeometry(stage, geometry); } } diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index a4460e375b3a..39c09a7c2356 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -198,12 +198,37 @@ void VerifyTessellationInstancePatches() { Require(ShaderRecompiler::TessellationInstancePatches(request) == 4u); } +void VerifyGeometryConfiguration() { + const ShaderRecompiler::RequestSerializer serializer; + ShaderRecompiler::RecompileRequest request{}; + request.graphics.emplace(); + ShaderRecompiler::GeometryConfiguration geometry; + geometry.inputVertices = 1u; + geometry.outputTopology = 2u; + geometry.maxVertices = 40u; + geometry.instances = 3u; + geometry.esgsItemDwords = 60u; + geometry.vertexDwords = 12u; + geometry.exports = {{0x0cu, 0xfu, 0u, {8u, 9u, 10u, 11u}, true}, {0x21u, 0xfu, 0xcu, {4u, 5u, 0u, 0x3f800000u}, false}}; + request.graphics->geometry = geometry; + const auto encoded = serializer.Serialize(request); + const auto replay = serializer.Deserialize(encoded); + Require(replay.request.graphics && replay.request.graphics->geometry == geometry); + Require(serializer.Serialize(replay.request) == encoded); + auto version62 = DecodeBase64(encoded); + Require(version62[4] == 63u); + version62.resize(version62.size() - (1u + 6u * 4u + 8u + 2u * 29u)); + version62[4] = 62u; + const auto replay62 = serializer.Deserialize(EncodeBase64(version62)); + Require(replay62.request.graphics && !replay62.request.graphics->geometry); +} + } std::string SerializeVersion56(const ShaderRecompiler::RecompileRequest& request) { auto bytes = DecodeBase64(ShaderRecompiler::RequestSerializer{}.Serialize(request)); - Require(bytes.size() > 14u && bytes[4] == 62u); - bytes.resize(bytes.size() - 6u); + Require(bytes.size() > 14u && bytes[4] == 63u && (!request.graphics || !request.graphics->geometry)); + bytes.resize(bytes.size() - (request.graphics ? 7u : 6u)); bytes[4] = 56u; return EncodeBase64(bytes); } @@ -226,7 +251,7 @@ void VerifyTargetOptions() { Require(replay.request.target.float16WidenNans == widen && replay.request.target.float16NarrowNans == narrow); Require(serializer.Serialize(replay.request) == encoded); auto bytes = DecodeBase64(encoded); - Require(bytes[4] == 62u && bytes.back() == 0u); + Require(bytes[4] == 63u && bytes.back() == 0u); for (std::size_t missing = 1u; missing <= 6u; ++missing) { auto truncated = bytes; truncated.resize(truncated.size() - missing); @@ -776,7 +801,7 @@ int VerifyVersion56Compatibility() { version40[4] = 40u; const auto replay40 = serializer.Deserialize(EncodeBase64(version40)); Require(!replay40.request.target.float32DenormPreserve && replay40.request.target.float32FlushToZero == !preserve); - for (const std::uint8_t unwritten : {58u, 59u, 60u, 61u, 63u}) { + for (const std::uint8_t unwritten : {58u, 59u, 60u, 61u, 64u}) { auto future = bytes; future[4] = unwritten; bool futureRejected = false; @@ -891,10 +916,10 @@ int VerifyVersion56Compatibility() { const auto replay35 = serializer.Deserialize(EncodeBase64(version35)); Require(replay35.request.target.spannedWaves == spanned && !replay35.request.target.float32FlushToZero); request.target.spannedAnySubgroup = spanned; - const auto version62 = DecodeBase64(serializer.Serialize(request)); - Require(version62[4] == 62u && version62.back() == (spanned ? 1u : 0u)); - Require(serializer.Deserialize(EncodeBase64(version62)).request.target.spannedAnySubgroup == spanned); - auto version57 = version62; + const auto current = DecodeBase64(serializer.Serialize(request)); + Require(current[4] == 63u && current.back() == (spanned ? 1u : 0u)); + Require(serializer.Deserialize(EncodeBase64(current)).request.target.spannedAnySubgroup == spanned); + auto version57 = current; version57[4] = 57u; version57.pop_back(); const auto replay57 = serializer.Deserialize(EncodeBase64(version57)); @@ -1170,6 +1195,7 @@ int VerifyVersion56Compatibility() { } int main() { + VerifyGeometryConfiguration(); VerifyTargetOptions(); return VerifyVersion56Compatibility(); } diff --git a/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md b/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md new file mode 100644 index 000000000000..56957811edeb --- /dev/null +++ b/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md @@ -0,0 +1,11 @@ +# shader + +## add Functional + +- [PS4 (GCN) geometry shaders](../../../core/shader/recompiler/Optimization/src/GeometryLowering.cpp) (shader recompiler, PS4) - not measured on a console. The ES is drawn as a Vulkan vertex shader and the GS as a Vulkan geometry shader; ESGS ring stores and reads become the record between them, and GSVS ring stores go to a per-invocation array that each emit copies out through the copy VS's exports. A copy VS export that is neither a GSVS ring dword nor a constant, an ESGS read whose vertex is not a constant input vertex or that loads more than one dword, an ESGS store at a per-lane address, LDS in the GS, and emits to vertex streams 1-3 throw. A GSVS store beyond the ring item is clamped to its last dword; on the console it would land in a neighbouring primitive's item. + +# libSceAgcDriver + +## add Functional + +- [PS4 (GCN) ES-GS-VS routing](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver, PS4) - not measured on a console. `VGT_SHADER_STAGES_EN` 0xb0 is drawn when `VGT_GS_MODE` is `GS_SCENARIO_G` off chip. On-chip GS (`VGT_GS_MODE.ONCHIP`), ES pass-through, the compute modes, `ELEMENT_INFO_EN`, `SUPPRESS_CUTS`, stream-out, vertex streams 1-3, point output (`VGT_GS_OUT_PRIM_TYPE` POINTLIST), adjacency, rectangle, quad and patch input primitives, LS-HS-ES-GS routing and viewport depth remapping through a geometry shader throw. The copy VS is read once per draw decode; a title that rewrites it in place at the same address keeps the old layout until the draw registers change. From 8b64e1c900b5219be696b87c7b7897f0fdf779cc Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:09:39 -0500 Subject: [PATCH 07/34] fix(shader): fold scalar adds, shifts and bit masks in GCN copy program offsets A copy VS can build a GSVS ring scalar offset with s_addk_i32, s_lshl_b32, s_bfm_b32 or s_mul_i32 rather than one s_movk_i32, as shadPS4 143b58aa48 ParseCopyShader handles. Fold those when their sources are known constants. Co-Authored-By: Claude Opus 5.5 --- .../tests/execution/GcnGeometry.cpp | 7 ++++ .../Optimization/src/GeometryLowering.cpp | 35 ++++++++++++++----- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index a2e2392b3f9f..db9df49a6326 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -49,6 +49,11 @@ alignas(256) constexpr std::array GcnCopy{ 0x05040302, 0xf800020f, 0x08070706, 0xbf810000, }; +alignas(256) constexpr std::array GcnCopyFolded{ + 0x34020082, 0xb0040200, 0xb7840100, 0x8f058881, 0x92068a81, 0xe0305000, 0x04400201, 0xe0305000, + 0x05400301, 0xe0305000, 0x06400401, 0xbf8c0000, 0xf80008cf, 0x02040302, 0xbf810000, +}; + alignas(256) constexpr std::array GcnCopyComputed{ 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0x060604f2, 0xf80008cf, 0x02020302, 0xbf810000, }; @@ -171,6 +176,8 @@ void RequireCopyLayout() { Require(exports.size() == 2u, "the copy program did not yield a position and a parameter export"); Require(exports[0].target == 0x0cu && exports[0].enable == 0xfu && exports[0].done && exports[0].constants == 0u && exports[0].values == std::array{0u, 1u, 2u, 3u}, "the position export did not read GSVS dwords 0-3"); Require(exports[1].target == 0x20u && exports[1].constants == 0xeu && exports[1].values == std::array{4u, 0u, 0u, 0x3f800000u}, "the parameter export did not read GSVS dword 4 beside the constants 0, 0 and 1.0"); + const auto folded = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyFolded, 4u, 5u); + Require(folded.size() == 1u && folded[0].constants == 0u && folded[0].values == std::array{3u, 1u, 4u, 3u}, "scalar offsets built by s_addk_i32, s_lshl_b32 and s_bfm_b32 did not select GSVS dwords 3, 1 and 4"); bool refused = false; try { static_cast(ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyComputed, 4u, 5u)); diff --git a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp index f727bf417dbb..06fd7ad97793 100644 --- a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp +++ b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp @@ -278,6 +278,30 @@ std::optional OperandConstant(const RdnaOperand& operand) { return std::nullopt; } +std::optional ScalarValue(const RdnaOperand& operand, const std::map& scalars) { + if (const auto value = OperandConstant(operand)) return value; + if (operand.kind != RdnaOperandKind::ScalarRegister) return std::nullopt; + const auto found = scalars.find(operand.reg); + return found == scalars.end() ? std::nullopt : std::optional(found->second); +} + +std::optional FoldScalar(const RdnaInstruction& instruction, const std::map& scalars) { + if (instruction.is64Bit) return std::nullopt; + const auto first = ScalarValue(instruction.source0, scalars); + if (instruction.op == RdnaOpcode::SMovkI32 || instruction.op == RdnaOpcode::SMovB32) return first; + const auto second = ScalarValue(instruction.source1, scalars); + if (!first || !second) return std::nullopt; + switch (instruction.op) { + case RdnaOpcode::SAddI32: + case RdnaOpcode::SAddU32: return *first + *second; + case RdnaOpcode::SMulI32: + case RdnaOpcode::SMulkI32: return *first * *second; + case RdnaOpcode::SLshlB32: return *first << (*second & 31u); + case RdnaOpcode::SBfmB32: return ((*first & 31u) == 0u ? 0u : (0xffffffffu >> (32u - (*first & 31u)))) << (*second & 31u); + default: return std::nullopt; + } +} + void Forget(std::map& vectors, std::map& scalars, const RdnaInstruction& instruction) { for (const auto* destination : {&instruction.destination, &instruction.destination2}) { const auto count = std::max(instruction.dataDwordCount, 1u) + (instruction.is64Bit ? 1u : 0u); @@ -304,10 +328,9 @@ std::vector ParseGeometryCopyProgram(std::span ParseGeometryCopyProgram(std::spansecond.vertexOffset) FailCopy("a GSVS ring read not addressed by the vertex index times 4", pc); - std::optional soffset = OperandConstant(instruction.source2); - if (instruction.source2.kind == RdnaOperandKind::ScalarRegister) { - const auto found = scalars.find(instruction.source2.reg); - if (found != scalars.end()) soffset = found->second; - } + const auto soffset = ScalarValue(instruction.source2, scalars); if (!soffset) FailCopy("a GSVS ring read whose scalar offset is not a constant", pc); const auto bytes = static_cast(*soffset) + instruction.memoryOffset; if (bytes % slotBytes != 0u || bytes / slotBytes >= vertexDwords) FailCopy("a GSVS ring read at " + std::to_string(bytes) + " bytes, which is not one of the " + std::to_string(vertexDwords) + " vertex dwords of " + std::to_string(slotBytes) + " bytes each", pc); From de3aca117bb6a73fe75d84bca5e1716b91133216 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:03:52 -0500 Subject: [PATCH 08/34] fix(shader): refuse GCN copy programs with control flow and keep stray GSVS stores apart The copy VS parser read every program as straight-line code. A branch, s_setpc, s_swappc, s_call or a write to EXEC now throws instead of being skipped. A GSVS store at a constant address past VGT_GS_VERT_ITEMSIZE times VGT_GS_MAX_VERT_OUT dwords throws; a computed one past it goes to a spare dword that no output reads instead of the item's last dword. Co-Authored-By: Claude Opus 5.5 --- .../tests/execution/GcnGeometry.cpp | 17 +++++++++++++++++ .../Optimization/src/GeometryLowering.cpp | 5 +++++ .../SpirvBackend/src/SpirvModuleEmitter.cpp | 4 ++-- .../debt/changes/claude-gcn-es-gs-copy-vs.md | 2 +- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index db9df49a6326..0ece4758706f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -54,6 +54,14 @@ alignas(256) constexpr std::array GcnCopyFolded{ 0x05400301, 0xe0305000, 0x06400401, 0xbf8c0000, 0xf80008cf, 0x02040302, 0xbf810000, }; +alignas(256) constexpr std::array GcnCopyBranch{ + 0x34020082, 0xe0305000, 0x80400201, 0xbf880001, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnCopyExec{ + 0x34020082, 0xe0305000, 0x80400201, 0xbefe04c1, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xbf810000, +}; + alignas(256) constexpr std::array GcnCopyComputed{ 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0x060604f2, 0xf80008cf, 0x02020302, 0xbf810000, }; @@ -192,6 +200,15 @@ void RequireCopyLayout() { refused = std::string(error.what()).find("which is not one of the 5 vertex dwords") != std::string::npos; } Require(refused, "a copy program read at a slot stride other than VGT_GS_MAX_VERT_OUT times 64 bytes was accepted"); + for (const auto& [code, reason] : {std::pair{std::span(GcnCopyBranch), "control flow in a copy program"}, std::pair{std::span(GcnCopyExec), "a copy program that writes EXEC"}}) { + refused = false; + try { + static_cast(ShaderRecompiler::ParseGeometryCopyProgram(code, 4u, 5u)); + } catch (const std::exception& error) { + refused = std::string(error.what()).find(reason) != std::string::npos; + } + Require(refused, std::string("a copy program was accepted that should fail with: ") + reason); + } } void Bind(AgcDriver::QueueState& queue, const void* code, std::uint32_t program, std::uint32_t resources, std::span users) { diff --git a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp index 06fd7ad97793..dd814e003741 100644 --- a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp +++ b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp @@ -204,6 +204,7 @@ class Lowering { if (offset) { const auto value = offset->constant + bytes; if (value < 0 || (value & 3) != 0) Fail("an unaligned GSVS ring store", flags.pc); + if (value / 4 >= static_cast(geometry.vertexDwords) * geometry.maxVertices) Fail("a GSVS ring store outside VGT_GS_VERT_ITEMSIZE times VGT_GS_MAX_VERT_OUT dwords", flags.pc); address = &constant(static_cast(value)); } else { address = bytes == 0u ? inst.Argument(2) : &insert(block, inst, IrOpcode::IAdd32, IrType::U32, {inst.Argument(2), &constant(bytes)}); @@ -328,6 +329,10 @@ std::vector ParseGeometryCopyProgram(std::spankind == RdnaOperandKind::ExecLo || destination->kind == RdnaOperandKind::ExecHi) FailCopy("a copy program that writes EXEC", pc); + } if (const auto folded = FoldScalar(instruction, scalars)) { Forget(vectors, scalars, instruction); if (instruction.destination.kind == RdnaOperandKind::ScalarRegister) scalars[instruction.destination.reg] = *folded; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp index ec4cf0d64553..7245b1abde9b 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp @@ -1115,7 +1115,7 @@ std::uint32_t TessellationOuterFactors(const SpirvEmitterState& state) { std::uint32_t GeometryRingElement(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index) { const auto& geometry = state.inputInfo.vertex->geometry; const auto clamped = state.module.AllocateId(); - state.module.AddFunction(spv::OpExtInst, TypeU32(state), clamped, GlslStd450(state), GLSLstd450UMin, index, ConstantU32(state, geometry.vertexDwords * geometry.maxVertices - 1u)); + state.module.AddFunction(spv::OpExtInst, TypeU32(state), clamped, GlslStd450(state), GLSLstd450UMin, index, ConstantU32(state, geometry.vertexDwords * geometry.maxVertices)); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassPrivate, TypeU32(state)), pointer, variable, clamped); return pointer; @@ -1262,7 +1262,7 @@ void DefineTessellationInterfaces(SpirvEmitterState& state) { const auto emitted = static_cast(TessellationAttribute::GeometryEmitted); if (state.tessVariables.at(ring) == 0u) { const auto& geometry = state.inputInfo.vertex->geometry; - const auto ringType = array(TypeU32(state), geometry.vertexDwords * geometry.maxVertices); + const auto ringType = array(TypeU32(state), geometry.vertexDwords * geometry.maxVertices + 1u); const auto variable = state.module.DefineInitializedGlobalVariable(TypePointer(state, spv::StorageClassPrivate, ringType), spv::StorageClassPrivate, state.module.Constant(spv::OpConstantNull, ringType)); if (state.spirvVersion >= 0x00010400u) state.interfaceVariables.push_back(variable); state.tessVariables.at(ring) = variable; diff --git a/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md b/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md index 56957811edeb..1f5c322fe2ff 100644 --- a/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md +++ b/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md @@ -2,7 +2,7 @@ ## add Functional -- [PS4 (GCN) geometry shaders](../../../core/shader/recompiler/Optimization/src/GeometryLowering.cpp) (shader recompiler, PS4) - not measured on a console. The ES is drawn as a Vulkan vertex shader and the GS as a Vulkan geometry shader; ESGS ring stores and reads become the record between them, and GSVS ring stores go to a per-invocation array that each emit copies out through the copy VS's exports. A copy VS export that is neither a GSVS ring dword nor a constant, an ESGS read whose vertex is not a constant input vertex or that loads more than one dword, an ESGS store at a per-lane address, LDS in the GS, and emits to vertex streams 1-3 throw. A GSVS store beyond the ring item is clamped to its last dword; on the console it would land in a neighbouring primitive's item. +- [PS4 (GCN) geometry shaders](../../../core/shader/recompiler/Optimization/src/GeometryLowering.cpp) (shader recompiler, PS4) - not measured on a console. The ES is drawn as a Vulkan vertex shader and the GS as a Vulkan geometry shader; ESGS ring stores and reads become the record between them, and GSVS ring stores go to a per-invocation array that each emit copies out through the copy VS's exports. A copy VS export that is neither a GSVS ring dword nor a constant, an ESGS read whose vertex is not a constant input vertex or that loads more than one dword, an ESGS store at a per-lane address, LDS in the GS, and emits to vertex streams 1-3 throw. A GSVS store at a constant address beyond `VGT_GS_VERT_ITEMSIZE` times `VGT_GS_MAX_VERT_OUT` dwords throws; one at a computed address beyond it goes to a spare dword that no output reads, where on the console it would land in a neighbouring primitive's item. The copy VS is read as straight-line code: a branch, an EXEC write, or a GSVS read whose slot spacing is not `VGT_GS_MAX_VERT_OUT` times 64 bytes throws; a `v_cmpx`, which writes EXEC implicitly, is not detected. # libSceAgcDriver From 099c38cf5e4418cf724e82b91bd3f11eb81e2305 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:05:20 -0500 Subject: [PATCH 09/34] docs(debt): shorten the GCN geometry shader entry Co-Authored-By: Claude Opus 5.5 --- docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md b/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md index 1f5c322fe2ff..f8efec548277 100644 --- a/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md +++ b/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md @@ -2,7 +2,7 @@ ## add Functional -- [PS4 (GCN) geometry shaders](../../../core/shader/recompiler/Optimization/src/GeometryLowering.cpp) (shader recompiler, PS4) - not measured on a console. The ES is drawn as a Vulkan vertex shader and the GS as a Vulkan geometry shader; ESGS ring stores and reads become the record between them, and GSVS ring stores go to a per-invocation array that each emit copies out through the copy VS's exports. A copy VS export that is neither a GSVS ring dword nor a constant, an ESGS read whose vertex is not a constant input vertex or that loads more than one dword, an ESGS store at a per-lane address, LDS in the GS, and emits to vertex streams 1-3 throw. A GSVS store at a constant address beyond `VGT_GS_VERT_ITEMSIZE` times `VGT_GS_MAX_VERT_OUT` dwords throws; one at a computed address beyond it goes to a spare dword that no output reads, where on the console it would land in a neighbouring primitive's item. The copy VS is read as straight-line code: a branch, an EXEC write, or a GSVS read whose slot spacing is not `VGT_GS_MAX_VERT_OUT` times 64 bytes throws; a `v_cmpx`, which writes EXEC implicitly, is not detected. +- [PS4 (GCN) geometry shaders](../../../core/shader/recompiler/Optimization/src/GeometryLowering.cpp) (shader recompiler, PS4) - not measured on a console. These throw: a copy VS export that is neither a GSVS ring dword nor a constant, copy VS control flow or EXEC writes, copy VS GSVS reads not spaced `VGT_GS_MAX_VERT_OUT` times 64 bytes apart, ESGS reads of a non-constant input vertex or of more than one dword, ESGS stores at a per-lane address, LDS in the GS, emits to streams 1-3, and GSVS stores at a constant address past `VGT_GS_VERT_ITEMSIZE` times `VGT_GS_MAX_VERT_OUT` dwords. A GSVS store at a computed address past that goes to a spare dword no output reads; on the console it lands in a neighbouring primitive's item. A `v_cmpx` in the copy VS, which writes EXEC implicitly, is not detected. # libSceAgcDriver From 8e00caff80790de33de6c207fd46e819a1036b23 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:42:34 -0500 Subject: [PATCH 10/34] fix(shader): follow GCN copy program stream branches on a known SCC A PS4 copy VS selects its stream block with s_lshr_b32 of the stream-out configuration SGPR, s_cmpk_eq_u32 and s_cbranch_scc0. With SPI_SHADER_PGM_RSRC2_VS.SO_EN set, that SGPR follows the user SGPRs; it is read as 0, since only stream 0 without stream-out is drawn. Scalar compares now set a known SCC, forward s_branch and s_cbranch_scc0/1 on a known SCC are followed, and any other control flow still throws. The GSVS read address must also come from the incoming v0, not one written earlier in the program. Co-Authored-By: Claude Opus 5.5 --- .../Execution/src/Driver/Draw/DrawDecode.cpp | 5 +- .../tests/execution/GcnGeometry.cpp | 31 +++++++--- .../Optimization/src/GeometryLowering.cpp | 62 ++++++++++++++++++- core/shader/recompiler/Recompiler.hpp | 2 +- .../debt/changes/claude-gcn-es-gs-copy-vs.md | 2 +- 5 files changed, 89 insertions(+), 13 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp index 4c9491477825..50fd360220b4 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp @@ -187,7 +187,10 @@ void DecodeGraphicsPrograms(DrawDecode& decoded, const QueueState& queue, const append(0x088, 6, Stage::Geometry, 0x08b, 0x08c, Role::Geometry); append(0x048, 2, Stage::Vertex, 0x04b, 0x04c, Role::Copy); auto& geometry = *graphics.stages.legacyGeometry; - geometry.exports = ShaderRecompiler::ParseGeometryCopyProgram(programs.back().binary.code, geometry.maxVertices, geometry.vertexDwords); + const auto copyResources = queue.shader.find(0x04bu); + const auto copyRsrc2 = copyResources == queue.shader.end() ? 0u : copyResources->second; + const auto streamConfig = (copyRsrc2 & 0x1000u) != 0u ? std::optional((copyRsrc2 >> 1u) & 0x1fu) : std::nullopt; + geometry.exports = ShaderRecompiler::ParseGeometryCopyProgram(programs.back().binary.code, geometry.maxVertices, geometry.vertexDwords, streamConfig); } else if (graphics.stages.legacyVertex) { append(0x48, 2, Stage::Vertex, 0x4b, 0x4c, Role::Main); } else { diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index 0ece4758706f..e2562654a104 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -62,6 +62,14 @@ alignas(256) constexpr std::array GcnCopyExec{ 0x34020082, 0xe0305000, 0x80400201, 0xbefe04c1, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xbf810000, }; +alignas(256) constexpr std::array GcnCopyMovedIndex{ + 0x4a000081, 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnCopyStreams{ + 0x34000082, 0x900a9802, 0xb48a0000, 0xbf840005, 0xe0305000, 0x80400200, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xbf810000, +}; + alignas(256) constexpr std::array GcnCopyComputed{ 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0x060604f2, 0xf80008cf, 0x02020302, 0xbf810000, }; @@ -83,7 +91,7 @@ GeometryConfiguration Points() { geometry.instances = 1u; geometry.esgsItemDwords = 2u; geometry.vertexDwords = 5u; - geometry.exports = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopy, geometry.maxVertices, geometry.vertexDwords); + geometry.exports = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopy, geometry.maxVertices, geometry.vertexDwords, std::nullopt); return geometry; } @@ -180,30 +188,39 @@ void RequireQuads(AgcDriver::VulkanDevice& device) { } void RequireCopyLayout() { - const auto exports = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopy, 4u, 5u); + const auto exports = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopy, 4u, 5u, std::nullopt); Require(exports.size() == 2u, "the copy program did not yield a position and a parameter export"); Require(exports[0].target == 0x0cu && exports[0].enable == 0xfu && exports[0].done && exports[0].constants == 0u && exports[0].values == std::array{0u, 1u, 2u, 3u}, "the position export did not read GSVS dwords 0-3"); Require(exports[1].target == 0x20u && exports[1].constants == 0xeu && exports[1].values == std::array{4u, 0u, 0u, 0x3f800000u}, "the parameter export did not read GSVS dword 4 beside the constants 0, 0 and 1.0"); - const auto folded = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyFolded, 4u, 5u); + const auto folded = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyFolded, 4u, 5u, std::nullopt); Require(folded.size() == 1u && folded[0].constants == 0u && folded[0].values == std::array{3u, 1u, 4u, 3u}, "scalar offsets built by s_addk_i32, s_lshl_b32 and s_bfm_b32 did not select GSVS dwords 3, 1 and 4"); bool refused = false; try { - static_cast(ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyComputed, 4u, 5u)); + static_cast(ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyComputed, 4u, 5u, std::nullopt)); } catch (const std::exception& error) { refused = std::string(error.what()).find("an exported value other than a GSVS ring dword or a constant") != std::string::npos; } Require(refused, "a copy program that exports a computed value was accepted"); refused = false; try { - static_cast(ShaderRecompiler::ParseGeometryCopyProgram(GcnCopy, 3u, 5u)); + static_cast(ShaderRecompiler::ParseGeometryCopyProgram(GcnCopy, 3u, 5u, std::nullopt)); } catch (const std::exception& error) { refused = std::string(error.what()).find("which is not one of the 5 vertex dwords") != std::string::npos; } Require(refused, "a copy program read at a slot stride other than VGT_GS_MAX_VERT_OUT times 64 bytes was accepted"); - for (const auto& [code, reason] : {std::pair{std::span(GcnCopyBranch), "control flow in a copy program"}, std::pair{std::span(GcnCopyExec), "a copy program that writes EXEC"}}) { + const auto streams = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyStreams, 4u, 5u, 2u); + Require(streams.size() == 1u && streams[0].constants == 0u && streams[0].values == std::array{0u, 0u, 0u, 0u}, "the stream 0 block of a copy program that selects its stream from the stream-out configuration SGPR was not read"); + refused = false; + try { + static_cast(ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyStreams, 4u, 5u, std::nullopt)); + } catch (const std::exception& error) { + refused = std::string(error.what()).find("a copy program branch on a condition not known at draw time") != std::string::npos; + } + Require(refused, "a copy program branch on the stream ID was followed without the stream-out configuration SGPR"); + for (const auto& [code, reason] : {std::pair{std::span(GcnCopyBranch), "control flow other than a scalar condition in a copy program"}, std::pair{std::span(GcnCopyExec), "a copy program that writes EXEC"}, std::pair{std::span(GcnCopyMovedIndex), "not addressed by the vertex index times 4"}}) { refused = false; try { - static_cast(ShaderRecompiler::ParseGeometryCopyProgram(code, 4u, 5u)); + static_cast(ShaderRecompiler::ParseGeometryCopyProgram(code, 4u, 5u, std::nullopt)); } catch (const std::exception& error) { refused = std::string(error.what()).find(reason) != std::string::npos; } diff --git a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp index dd814e003741..612430366c88 100644 --- a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp +++ b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp @@ -298,11 +298,42 @@ std::optional FoldScalar(const RdnaInstruction& instruction, cons case RdnaOpcode::SMulI32: case RdnaOpcode::SMulkI32: return *first * *second; case RdnaOpcode::SLshlB32: return *first << (*second & 31u); + case RdnaOpcode::SLshrB32: return *first >> (*second & 31u); + case RdnaOpcode::SAndB32: return *first & *second; + case RdnaOpcode::SOrB32: return *first | *second; case RdnaOpcode::SBfmB32: return ((*first & 31u) == 0u ? 0u : (0xffffffffu >> (32u - (*first & 31u)))) << (*second & 31u); default: return std::nullopt; } } +std::optional> CompareScalar(const RdnaInstruction& instruction, const std::map& scalars) { + const auto first = ScalarValue(instruction.source0, scalars); + const auto second = ScalarValue(instruction.source1, scalars); + const auto known = [&](auto compare) -> std::optional { + if (!first || !second) return std::nullopt; + return compare(*first, *second, static_cast(*first), static_cast(*second)); + }; + switch (instruction.op) { + case RdnaOpcode::SCmpEqU32: + case RdnaOpcode::SCmpEqI32: return known([](auto a, auto b, auto, auto) { return a == b; }); + case RdnaOpcode::SCmpLgU32: + case RdnaOpcode::SCmpLgI32: return known([](auto a, auto b, auto, auto) { return a != b; }); + case RdnaOpcode::SCmpGtU32: return known([](auto a, auto b, auto, auto) { return a > b; }); + case RdnaOpcode::SCmpGeU32: return known([](auto a, auto b, auto, auto) { return a >= b; }); + case RdnaOpcode::SCmpLtU32: return known([](auto a, auto b, auto, auto) { return a < b; }); + case RdnaOpcode::SCmpLeU32: return known([](auto a, auto b, auto, auto) { return a <= b; }); + case RdnaOpcode::SCmpGtI32: return known([](auto, auto, auto a, auto b) { return a > b; }); + case RdnaOpcode::SCmpGeI32: return known([](auto, auto, auto a, auto b) { return a >= b; }); + case RdnaOpcode::SCmpLtI32: return known([](auto, auto, auto a, auto b) { return a < b; }); + case RdnaOpcode::SCmpLeI32: return known([](auto, auto, auto a, auto b) { return a <= b; }); + default: return std::nullopt; + } +} + +bool KeepsScc(RdnaOpcode opcode) { + return opcode == RdnaOpcode::SMovB32 || opcode == RdnaOpcode::SMovkI32 || opcode == RdnaOpcode::SBfmB32 || opcode == RdnaOpcode::SMulI32 || opcode == RdnaOpcode::SMulkI32; +} + void Forget(std::map& vectors, std::map& scalars, const RdnaInstruction& instruction) { for (const auto* destination : {&instruction.destination, &instruction.destination2}) { const auto count = std::max(instruction.dataDwordCount, 1u) + (instruction.is64Bit ? 1u : 0u); @@ -319,26 +350,51 @@ void GeometryLowering::Lower(IrProgram& program, const ShaderGeometryInputInfo& Lowering(program, geometry).Run(); } -std::vector ParseGeometryCopyProgram(std::span code, std::uint32_t maxVertices, std::uint32_t vertexDwords) { +std::vector ParseGeometryCopyProgram(std::span code, std::uint32_t maxVertices, std::uint32_t vertexDwords, std::optional streamConfigSgpr) { if (maxVertices == 0u || vertexDwords == 0u) throw std::runtime_error("geometry copy program: VGT_GS_MAX_VERT_OUT and VGT_GS_VERT_ITEMSIZE must be nonzero"); const auto program = RdnaInstructionDecoder{}.Decode(code); std::map vectors; std::map scalars; + if (streamConfigSgpr) scalars[*streamConfigSgpr] = 0u; + bool vertexIndex = true; + std::optional scc; + std::optional skipTo; std::vector exports; const auto slotBytes = maxVertices * GsVsVertexBytes; for (const auto& instruction : program.instructions) { const auto pc = instruction.programCounter; + if (skipTo) { + if (pc < *skipTo) continue; + if (pc > *skipTo) FailCopy("a branch into the middle of an instruction", pc); + skipTo.reset(); + } if (instruction.op == RdnaOpcode::SEndpgm) break; - if (IsBranchOpcode(instruction.op) || instruction.op == RdnaOpcode::SSetpcB64 || instruction.op == RdnaOpcode::SSwappcB64 || instruction.op == RdnaOpcode::SCallB64) FailCopy("control flow in a copy program", pc); + if (instruction.op == RdnaOpcode::SBranch || instruction.op == RdnaOpcode::SCbranchScc0 || instruction.op == RdnaOpcode::SCbranchScc1) { + if (instruction.branchTarget <= pc) FailCopy("a backward branch in a copy program", pc); + if (instruction.op != RdnaOpcode::SBranch && !scc) FailCopy("a copy program branch on a condition not known at draw time", pc); + if (instruction.op == RdnaOpcode::SBranch || *scc == (instruction.op == RdnaOpcode::SCbranchScc1)) skipTo = instruction.branchTarget; + continue; + } + if (IsBranchOpcode(instruction.op) || instruction.op == RdnaOpcode::SSetpcB64 || instruction.op == RdnaOpcode::SSwappcB64 || instruction.op == RdnaOpcode::SCallB64) FailCopy("control flow other than a scalar condition in a copy program", pc); + if (const auto compared = CompareScalar(instruction, scalars)) { + scc = *compared; + continue; + } + const auto family = instruction.family; + if ((family == RdnaInstructionFamily::SOP1 || family == RdnaInstructionFamily::SOP2 || family == RdnaInstructionFamily::SOPK || family == RdnaInstructionFamily::SOPC) && !KeepsScc(instruction.op)) scc.reset(); for (const auto* destination : {&instruction.destination, &instruction.destination2}) { if (destination->kind == RdnaOperandKind::ExecLo || destination->kind == RdnaOperandKind::ExecHi) FailCopy("a copy program that writes EXEC", pc); } + const bool indexLive = vertexIndex; + for (const auto* destination : {&instruction.destination, &instruction.destination2}) { + if (destination->kind == RdnaOperandKind::VectorRegister && destination->reg == 0u) vertexIndex = false; + } if (const auto folded = FoldScalar(instruction, scalars)) { Forget(vectors, scalars, instruction); if (instruction.destination.kind == RdnaOperandKind::ScalarRegister) scalars[instruction.destination.reg] = *folded; continue; } - if (instruction.op == RdnaOpcode::VLshlrevB32 && instruction.source1.kind == RdnaOperandKind::VectorRegister && instruction.source1.reg == 0u && OperandConstant(instruction.source0) == 2u && !vectors.contains(0u)) { + if (instruction.op == RdnaOpcode::VLshlrevB32 && instruction.source1.kind == RdnaOperandKind::VectorRegister && instruction.source1.reg == 0u && OperandConstant(instruction.source0) == 2u && indexLive) { Forget(vectors, scalars, instruction); vectors[instruction.destination.reg] = CopySource{true}; continue; diff --git a/core/shader/recompiler/Recompiler.hpp b/core/shader/recompiler/Recompiler.hpp index 699c33bbdb17..47474b501c68 100644 --- a/core/shader/recompiler/Recompiler.hpp +++ b/core/shader/recompiler/Recompiler.hpp @@ -452,7 +452,7 @@ struct GeometryConfiguration { bool operator==(const GeometryConfiguration&) const = default; }; -[[nodiscard]] std::vector ParseGeometryCopyProgram(std::span code, std::uint32_t maxVertices, std::uint32_t vertexDwords); +[[nodiscard]] std::vector ParseGeometryCopyProgram(std::span code, std::uint32_t maxVertices, std::uint32_t vertexDwords, std::optional streamConfigSgpr); struct TessellationConfiguration { std::uint32_t inputControlPoints; diff --git a/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md b/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md index f8efec548277..96b406152d41 100644 --- a/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md +++ b/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md @@ -2,7 +2,7 @@ ## add Functional -- [PS4 (GCN) geometry shaders](../../../core/shader/recompiler/Optimization/src/GeometryLowering.cpp) (shader recompiler, PS4) - not measured on a console. These throw: a copy VS export that is neither a GSVS ring dword nor a constant, copy VS control flow or EXEC writes, copy VS GSVS reads not spaced `VGT_GS_MAX_VERT_OUT` times 64 bytes apart, ESGS reads of a non-constant input vertex or of more than one dword, ESGS stores at a per-lane address, LDS in the GS, emits to streams 1-3, and GSVS stores at a constant address past `VGT_GS_VERT_ITEMSIZE` times `VGT_GS_MAX_VERT_OUT` dwords. A GSVS store at a computed address past that goes to a spare dword no output reads; on the console it lands in a neighbouring primitive's item. A `v_cmpx` in the copy VS, which writes EXEC implicitly, is not detected. +- [PS4 (GCN) geometry shaders](../../../core/shader/recompiler/Optimization/src/GeometryLowering.cpp) (shader recompiler, PS4) - not measured on a console. These throw: a copy VS export that is neither a GSVS ring dword nor a constant, copy VS EXEC writes, backward branches, and branches other than on an SCC known at draw time, copy VS GSVS reads not spaced `VGT_GS_MAX_VERT_OUT` times 64 bytes apart, ESGS reads of a non-constant input vertex or of more than one dword, ESGS stores at a per-lane address, LDS in the GS, emits to streams 1-3, and GSVS stores at a constant address past `VGT_GS_VERT_ITEMSIZE` times `VGT_GS_MAX_VERT_OUT` dwords. The copy VS's stream-out configuration SGPR (after its user SGPRs when `SPI_SHADER_PGM_RSRC2_VS.SO_EN` is set) is read as 0: stream 0 and no stream-out, the only modeled case. A GSVS store at a computed address past that goes to a spare dword no output reads; on the console it lands in a neighbouring primitive's item. # libSceAgcDriver From c89e3c5819e60b67c7ec4d333f0ab7da0d3c67c6 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:55:09 -0500 Subject: [PATCH 11/34] test(agc): cover a taken copy program branch and an SCC overwritten before it Co-Authored-By: Claude Opus 5.5 --- .../tests/execution/GcnGeometry.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index e2562654a104..f1c6ca4df910 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -70,6 +70,14 @@ alignas(256) constexpr std::array GcnCopyStreams{ 0x34000082, 0x900a9802, 0xb48a0000, 0xbf840005, 0xe0305000, 0x80400200, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xbf810000, }; +alignas(256) constexpr std::array GcnCopySkip{ + 0x34000082, 0xb00a0001, 0xb48a0000, 0xbf840002, 0xf80008cf, 0x00000000, 0xe0305000, 0x80400200, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnCopySccClobbered{ + 0x34000082, 0x900a9802, 0xb48a0000, 0x80058105, 0xbf840005, 0xe0305000, 0x80400200, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xbf810000, +}; + alignas(256) constexpr std::array GcnCopyComputed{ 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0x060604f2, 0xf80008cf, 0x02020302, 0xbf810000, }; @@ -210,6 +218,15 @@ void RequireCopyLayout() { Require(refused, "a copy program read at a slot stride other than VGT_GS_MAX_VERT_OUT times 64 bytes was accepted"); const auto streams = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyStreams, 4u, 5u, 2u); Require(streams.size() == 1u && streams[0].constants == 0u && streams[0].values == std::array{0u, 0u, 0u, 0u}, "the stream 0 block of a copy program that selects its stream from the stream-out configuration SGPR was not read"); + const auto skipped = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopySkip, 4u, 5u, std::nullopt); + Require(skipped.size() == 1u && skipped[0].values == std::array{0u, 0u, 0u, 0u}, "a taken s_cbranch_scc0 did not skip the export it jumps over"); + refused = false; + try { + static_cast(ShaderRecompiler::ParseGeometryCopyProgram(GcnCopySccClobbered, 4u, 5u, 2u)); + } catch (const std::exception& error) { + refused = std::string(error.what()).find("a copy program branch on a condition not known at draw time") != std::string::npos; + } + Require(refused, "a branch was followed on an SCC that s_add_u32 overwrote after the compare"); refused = false; try { static_cast(ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyStreams, 4u, 5u, std::nullopt)); From 258b59324504f290c4ba614e2ab47af902bee4a1 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:11:39 -0500 Subject: [PATCH 12/34] fix(agc): update the Linux pipeline journal layout guards for the geometry configuration ShaderStages gained legacyGeometry, so the Linux x86_64 libstdc++ guards no longer matched and the build failed there. The sizes are read from a GCC 11.4 Linux build. The new GeometryConfiguration and GeometryCopyExport get guards like the mesh and tessellation configurations. Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp index 51b004731b26..0b93fdbb7fff 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/PipelineJournal.cpp @@ -47,10 +47,12 @@ static_assert(sizeof(VkStencilOpState) == 28, "VkStencilOpState changed: update static_assert(sizeof(VkVertexInputBindingDescription) == 12, "VkVertexInputBindingDescription changed: update the recipe codec"); static_assert(sizeof(VkVertexInputAttributeDescription) == 16, "VkVertexInputAttributeDescription changed: update the recipe codec"); #if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__) -static_assert(sizeof(State) == 1008, "State changed: update CanonicalPipelineState and the recipe codec"); -static_assert(sizeof(ShaderStages) == 164, "ShaderStages changed: update the recipe codec"); +static_assert(sizeof(State) == 1064, "State changed: update CanonicalPipelineState and the recipe codec"); +static_assert(sizeof(ShaderStages) == 224, "ShaderStages changed: update the recipe codec"); static_assert(sizeof(ShaderRecompiler::MeshConfiguration) == 40, "MeshConfiguration changed: update the recipe codec"); static_assert(sizeof(ShaderRecompiler::TessellationConfiguration) == 40, "TessellationConfiguration changed: update the recipe codec"); +static_assert(sizeof(ShaderRecompiler::GeometryConfiguration) == 48, "GeometryConfiguration changed: update the recipe codec"); +static_assert(sizeof(ShaderRecompiler::GeometryCopyExport) == 32, "GeometryCopyExport changed: update the recipe codec"); #endif constexpr std::uint32_t FileMagic = 0x4c4a5041u; From b2129045df62c40b0a4a11ce77d74cfdc42e9b30 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:25:50 -0500 Subject: [PATCH 13/34] test(agc): give the GCN program decode fixture a formatted color target Since #21747, PixelProgramSkipped also needs a color target with a format, so without CB_COLOR0_INFO the fixture's pixel program decoded as the null program. Co-Authored-By: Claude Opus 5.5 --- .../libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp index 4d55750f8f30..262affde6453 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp @@ -236,6 +236,7 @@ void RequireProgramDecode() { constexpr std::array hullUsers{0x22220001u, 0x22220002u, 0x22220003u, 0x22220004u}; constexpr std::array domainUsers{0x33330001u, 0x33330002u, 0x33330003u}; AgcDriver::QueueState queue{}; + queue.context[0x31c] = 10u << 2u; queue.context[0x8e] = 0xfu; queue.context[0x8f] = 0xfu; Bind(queue, GcnLocal.data(), 0x148u, 0x14bu, localUsers); From 358fbde48467ce92d9d78e357c1a598003d14426 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:28:53 -0500 Subject: [PATCH 14/34] test(agc): give the GCN geometry program decode fixture a formatted color target Since #21747, PixelProgramSkipped also needs a color target with a format, so without CB_COLOR0_INFO the fixture's pixel program decoded as the null program. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index 06d9bde0a41b..9d8dc6b0d6da 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -300,6 +300,7 @@ void RequireProgramDecode() { constexpr std::array geometryUsers{0x22220001u, 0x22220002u, 0x22220003u, 0x22220004u, 0x22220005u, 0x22220006u, 0x22220007u, 0x22220008u}; constexpr std::array copyUsers{0x33330001u, 0x33330002u, 0x33330003u, 0x33330004u}; AgcDriver::QueueState queue{}; + queue.context[0x31c] = 10u << 2u; queue.context[0x8e] = 0xfu; queue.context[0x8f] = 0xfu; Bind(queue, GcnExport.data(), 0x0c8u, 0x0cbu, exportUsers); From 25063d71f6897d5d73d23ee1dccc2e2f2848509c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 08:19:40 +0400 Subject: [PATCH 15/34] feat(agc): render PS4 color views of several slices through the vertex render target index A single-sample CB_COLOR_VIEW of several slices with PA_CL_VS_OUT_CNTL USE_VTX_RENDER_TARGET_INDX now decodes as a layered view of the array at CB_COLOR_BASE and draws through its resident array image, each layer placed with its own GCN bank rotation. Multisampled views still throw. Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/Graphics/src/Draw.cpp | 2 +- .../libSceAgcDriver/Graphics/src/State.cpp | 10 +- .../prx/libSceAgcDriver/tests/Graphics.cpp | 6 +- .../tests/execution/GcnLayeredColorTarget.cpp | 326 ++++++++++++++++++ .../changes/claude-ps4-gcn-layered-color.md | 5 + 5 files changed, 346 insertions(+), 3 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/execution/GcnLayeredColorTarget.cpp create mode 100644 docs/dev/debt/changes/claude-ps4-gcn-layered-color.md diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 70d9d9146ffa..5ed627e9470f 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -4075,7 +4075,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara Require(color.dccAddress == 0 && color.cmaskAddress == 0 && AttachmentProxyFormat(context, color.format) == VK_FORMAT_UNDEFINED, "a slice of a 2D array color target with DCC, CMASK or an attachment proxy has no resident array image"); const auto array = ArraySurfaceForTarget(color); // DecodeColorBuffer offsets slice s by s times this size; every slice the image stores must agree. - const auto sliceBytes = ComputeSurfaceSize(ComputeElementMipLayout(ColorTextureTileMode(color.tileMode), color.elementBytes, color.surfaceExtent.width, color.surfaceExtent.height, color.mipCount), 1); + const auto sliceBytes = ColorTileModeIsGcn(color.tileMode) ? static_cast(color.bytes) : ComputeSurfaceSize(ComputeElementMipLayout(ColorTextureTileMode(color.tileMode), color.elementBytes, color.surfaceExtent.width, color.surfaceExtent.height, color.mipCount), 1); const auto geometry = DescribeSurface(array); for (std::uint32_t slice = 0; slice <= color.arrayLastSlice; ++slice) Require(geometry.GuestLayerOffset(slice) == slice * sliceBytes, "the array image's layer pitch differs from the color view's slice offset"); Require(color.surfaceAddress == color.arrayAddress + color.arraySlice * sliceBytes, "the array image's layer pitch differs from the color view's slice offset"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp index 3849a708c1da..a4d33c4a7fea 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp @@ -2461,7 +2461,8 @@ ColorTarget DecodeGcnColorBuffer(const Registers& cx, std::uint32_t slot) { const auto lastSlice = (view >> 13u) & 0x7ffu; Require(lastSlice >= slice, "the color view ends before its first slice"); const auto exports = find(cx, 0x207); - Require(lastSlice == slice || exports == cx.end() || (exports->second & (1u << 18u)) == 0, "GCN layered rendering into several array slices through the vertex render target index is not implemented"); + const bool layered = lastSlice != slice && exports != cx.end() && (exports->second & (1u << 18u)) != 0; + Require(!layered || color.coverageSamples == 1u, "GCN layered rendering into several slices of a multisampled color array through the vertex render target index is not implemented"); const auto pitch = ((read(cx, 0x319 + stride) & 0x7ffu) + 1u) * 8u; const auto sliceElements = ((read(cx, 0x31a + stride) & 0x3fffffu) + 1u) * 64u; color.extent = {pitch, sliceElements / pitch}; @@ -2484,6 +2485,12 @@ ColorTarget DecodeGcnColorBuffer(const Registers& cx, std::uint32_t slot) { color.surfaceAddress = (static_cast(read(cx, 0x318 + stride)) << 8u) + static_cast(slice) * layout.Bytes() * fragments; color.address = color.surfaceAddress; color.bytes = layout.Bytes(); + if (layered) { + color.arrayAddress = static_cast(read(cx, 0x318 + stride)) << 8u; + color.arraySlice = slice; + color.arrayLastSlice = lastSlice; + color.layers = lastSlice + 1u - slice; + } color.format = decoded.format; color.componentMapping = decoded.componentMapping; color.packing = decoded.packing; @@ -2519,6 +2526,7 @@ GuestTextureResource ArraySurfaceForTarget(const ColorTarget& color) { surface.height = color.surfaceExtent.height; surface.depthOrLastArray = color.arrayLastSlice; surface.dimension = TextureDimension::k2DArray; + if (ColorTileModeIsGcn(color.tileMode)) surface.pipeBankXor = 0; return surface; } diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index 3fe29cdc5044..38e1878ed01b 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -4011,7 +4011,11 @@ void gcnColorSliceTests() { queue.context[0x31b] = 1u | (2u << 13u); Require(DecodeColorBuffer(queue.context, 0).address == base + GcnSliceBytes, "a GCN color view of several slices decoded without PA_CL_VS_OUT_CNTL does not draw into its first slice"); queue.context[0x207] = 1u << 18u; - expectFailure([&] { static_cast(DecodeColorBuffer(queue.context, 0)); }, "GCN layered rendering into several array slices through the vertex render target index is not implemented"); + const auto layered = DecodeColorBuffer(queue.context, 0); + Require(layered.address == base + GcnSliceBytes && layered.bytes == GcnSliceBytes && layered.layers == 2u && layered.arrayAddress == base && layered.arraySlice == 1u && layered.arrayLastSlice == 2u, "a GCN color view of slices 1 to 2 with a vertex render target index does not decode as two layers of the array at CB_COLOR_BASE"); + queue.context[0x31d] = 5u | (1u << 12u) | (1u << 15u); + expectFailure([&] { static_cast(DecodeColorBuffer(queue.context, 0)); }, "GCN layered rendering into several slices of a multisampled color array through the vertex render target index is not implemented"); + queue.context[0x31d] = 5u; queue.context[0x31b] = 1u | (1u << 13u); Require(DecodeColorBuffer(queue.context, 0).address == base + GcnSliceBytes, "a GCN color view of one slice is refused for a vertex render target index"); queue.context[0x207] = 0; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnLayeredColorTarget.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnLayeredColorTarget.cpp new file mode 100644 index 000000000000..ccb96baf9a76 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnLayeredColorTarget.cpp @@ -0,0 +1,326 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "prx/libSceAgcDriver/Graphics/include/State.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp" +#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp" +#include "prx/libc/include/GuestAllocations.hpp" +#include "prx/libc/include/GuestArena.hpp" +#include "prx/libc/include/GuestWriteWatch.hpp" +#include "Recompiler.hpp" +#include "RdnaDecoder/RdnaInstructionDecoder.hpp" +#include "VulkanTestDevice.hpp" +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; +using Triangle = std::array, 3>; + +constexpr std::uint32_t Width = 128; +constexpr std::uint32_t Height = 64; +constexpr std::uint32_t Slices = 4; +constexpr std::uint32_t FirstSlice = 1; +constexpr std::uint32_t LastSlice = 3; +constexpr std::uint32_t ElementBytes = 4; +constexpr std::uint32_t Format8888 = 10u; +constexpr std::uint32_t BlendClamp = 1u << 15u; +constexpr std::uint32_t LayerExports = (1u << 18u) | (1u << 21u); +constexpr std::size_t SliceBytes = std::size_t{Width} * Height * ElementBytes; +constexpr std::size_t ArrayBytes = SliceBytes * Slices; +constexpr std::size_t ArrayStride = 0x20000; +constexpr std::size_t Modes = 2; +constexpr std::size_t Vertices = Modes * ArrayStride; +constexpr std::size_t BlockBytes = Vertices + 0x10000; +constexpr std::uint64_t GcnAddressLimit = std::uint64_t{1} << 40u; +constexpr std::array DrawnLayers{0u, 2u}; + +alignas(256) constexpr std::array VertexCode{ + 0xe0382000u, 0x80000000u, 0xbf8c0f70u, 0xf80000cfu, 0x03020100u, + 0x7e080204u, 0x7e0a0280u, 0xf80008dfu, 0x05040505u, 0xbf810000u, +}; + +constexpr Triangle Lower{{{-1.0f, -1.0f, 0.5f, 1.0f}, {0.9f, -1.0f, 0.5f, 1.0f}, {-1.0f, 0.7f, 0.5f, 1.0f}}}; + +std::uint8_t DrawnBlue(std::uint32_t slice) { + return static_cast(16u + 16u * slice); +} + +alignas(256) std::array, DrawnLayers.size()> Programs{}; + +std::span Program(std::size_t index, std::uint32_t slice) { + constexpr std::uint32_t inverse255 = 0x3b808081u; + auto& code = Programs.at(index); + code = { + 0x7e084900u, 0x7e0a4901u, + 0x100808ffu, inverse255, 0x100a0affu, inverse255, + 0x7e0c02ffu, std::bit_cast(static_cast(DrawnBlue(slice)) / 255.0f), + 0x7e0e02f2u, + 0xf800180fu, 0x07060504u, + 0xbf810000u, + }; + return std::span(code.data(), 12); +} + +class LowBlock { +public: + LowBlock() { +#if defined(_WIN32) || defined(__APPLE__) + data = static_cast(GuestArena::GuestArenaAllocate_nid_postfix(BlockBytes, 65536)); +#ifdef _WIN32 + if (data != nullptr) GuestArena::GuestArenaCommit_nid_postfix(data, BlockBytes, PAGE_READWRITE, BlockBytes); +#else + constexpr std::uint32_t ReadWriteProtection = 0x04; + if (data != nullptr) GuestArena::GuestArenaCommit_nid_postfix(data, BlockBytes, ReadWriteProtection, BlockBytes); +#endif +#else +#ifdef ANYPS5_ENABLE_ASAN + constexpr std::uintptr_t FirstHint = 0x60000000; +#else + constexpr std::uintptr_t FirstHint = std::uintptr_t{1} << 32u; +#endif + for (std::uintptr_t hint = FirstHint; data == nullptr && hint < GcnAddressLimit; hint += std::uintptr_t{1} << 32u) { + void* mapped = mmap(reinterpret_cast(hint), BlockBytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0); + if (mapped != MAP_FAILED) data = static_cast(mapped); + } + if (data != nullptr && AgcDriver::GuestMemory::WriteWatched()) GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(data, BlockBytes); +#endif + if (data == nullptr) return; + std::memset(data, 0, BlockBytes); + GuestAllocations::Mutation().Add(data, BlockBytes, true, true, true); + AgcDriver::GuestMemory::CollectWritesUncached(Address(), BlockBytes); + } + + ~LowBlock() { + if (data == nullptr) return; + AgcDriver::Graphics::StorageTexture::FlushPending(Address(), BlockBytes, nullptr, "test release"); + GuestAllocations::Mutation().Remove(data); +#if defined(_WIN32) || defined(__APPLE__) + GuestArena::GuestArenaReset_nid_postfix(data, BlockBytes); + GuestArena::GuestArenaRelease_nid_postfix(data, BlockBytes); +#else + munmap(data, BlockBytes); + if (AgcDriver::GuestMemory::WriteWatched()) GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(data, BlockBytes); +#endif + } + + LowBlock(const LowBlock&) = delete; + LowBlock& operator=(const LowBlock&) = delete; + + bool Usable() const { return data != nullptr && Address() + BlockBytes <= GcnAddressLimit; } + std::uint64_t Address() const { return static_cast(reinterpret_cast(data)); } + std::uint64_t At(std::size_t offset) const { return Address() + offset; } + std::uint8_t* Data(std::size_t offset) const { return data + offset; } + +private: + std::uint8_t* data = nullptr; +}; + +struct ArrayLayout { + AgcDriver::Graphics::GcnTileGeometry geometry; + AgcDriver::Graphics::SurfaceGeometry surface; +}; + +ArrayLayout TexturePlacement(AgcDriver::Graphics::TextureTileMode mode, std::uint64_t base) { + AgcDriver::Graphics::GuestTextureResource array{}; + array.baseAddress = base; + array.width = Width; + array.height = Height; + array.depthOrLastArray = Slices - 1u; + array.mipCount = 1u; + array.allocatedMipCount = 1u; + array.tileMode = mode; + array.dimension = AgcDriver::Graphics::TextureDimension::k2DArray; + array.format = 56u; + array.gcnPitch = Width; + ArrayLayout layout{AgcDriver::Graphics::GcnTiling(mode, ElementBytes), AgcDriver::Graphics::DescribeSurface(array)}; + Require(layout.surface.layers == Slices && layout.surface.guestBytes == ArrayBytes, "the texture path does not see the GCN array as four whole slices"); + return layout; +} + +std::size_t TextureOffset(const ArrayLayout& layout, std::uint32_t slice, std::uint32_t x, std::uint32_t y) { + const auto& geometry = layout.geometry; + const auto& mip = layout.surface.mips[0]; + std::uint32_t inBlock = 0; + for (std::uint32_t bit = 0; bit < 16u; ++bit) inBlock |= static_cast(std::popcount((x & geometry.equation[bit] & 0xfffu) ^ ((y << 12u) & geometry.equation[bit] & 0xfff000u)) & 1) << bit; + const auto block = static_cast(y / geometry.blockHeight) * mip.blocksPerRow + x / geometry.blockWidth; + return static_cast(layout.surface.GuestOffset(slice, mip) + block * geometry.blockBytes + (inBlock ^ AgcDriver::Graphics::GcnLayerBankXor(geometry, slice))); +} + +ShaderRecompiler::ShaderPixelStageInfo PixelInfo() { + ShaderRecompiler::ShaderPixelStageInfo pixel{}; + pixel.inputAddr = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionX) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionY); + pixel.posX = true; + pixel.posY = true; + pixel.targetOutputMode[0] = 9; + pixel.targetExportMapping.fill(0xe4u); + return pixel; +} + +void Draw(AgcDriver::VulkanDevice& device, const LowBlock& block, const AgcDriver::Graphics::ColorTarget& color, std::uint32_t layer, std::span pixelCode) { + const auto target = device.Target(); + std::memcpy(block.Data(Vertices), Lower.data(), sizeof(Lower)); + const auto address = block.At(Vertices); + const std::vector vertexUserData{static_cast(address), static_cast((address >> 32u) & 0xffffu) | (16u << 16u), static_cast(sizeof(Lower)), 0xfacu | (7u << 12u) | (14u << 15u), layer}; + ShaderRecompiler::ShaderVertexStageInfo vertexInfo{}; + vertexInfo.paClVsOutCntl = LayerExports; + const std::array vertexMemory{{{reinterpret_cast(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}}; + ShaderRecompiler::RecompileRequest vertex{ + {ShaderStage::Vertex, reinterpret_cast(VertexCode.data()), VertexCode, 0, {}}, + {64u, 0, vertexUserData, std::nullopt, std::nullopt, vertexInfo, vertexMemory}, + target, + {0, 0, 0, 64} + }; + vertex.useCache = false; + const auto vertexResult = ShaderRecompiler::Recompile(vertex); + const auto vertexPush = static_cast(vertexResult.pushConstants.size()); + const std::vector pixelUserData(8, 0u); + const std::array pixelMemory{{{reinterpret_cast(pixelCode.data()), std::as_bytes(pixelCode)}}}; + ShaderRecompiler::RecompileRequest fragment{ + {ShaderStage::Fragment, reinterpret_cast(pixelCode.data()), pixelCode, 0, {}}, + {64u, 0, pixelUserData, std::nullopt, PixelInfo(), std::nullopt, pixelMemory}, + target, + PixelPushLayout(vertexPush, target) + }; + fragment.useCache = false; + const auto pixelResult = ShaderRecompiler::Recompile(fragment); + const std::array shaders{{ + {ShaderStage::Vertex, &vertexResult, 0}, + {ShaderStage::Fragment, &pixelResult, PixelPushOffset(vertexPush, target)} + }}; + AgcDriver::Graphics::State state{}; + state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, 64u, 64u, std::nullopt, std::nullopt}; + state.colors = {color}; + state.color = color; + state.hasColorTarget = true; + state.renderExtent = {Width, Height}; + state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + state.viewport = {0, static_cast(Height), static_cast(Width), -static_cast(Height), 0, 1}; + state.negativeOneToOne = false; + state.scissor = {{0, 0}, {Width, Height}}; + state.cullMode = VK_CULL_MODE_NONE; + state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + VkPipelineColorBlendAttachmentState blend{}; + blend.colorWriteMask = 0xf; + state.blends = {blend}; + state.blend = blend; + state.blendConstants = {}; + state.samples = 1u; + state.renderLayers = color.layers; + const AgcDriver::Pm4::DrawParameters draw{0, static_cast(Lower.size()), 0, 1, 0, false}; + device.Draw(state, draw, shaders); + device.WaitIdle(); +} + +std::array Background(std::uint32_t slice, std::uint32_t x, std::uint32_t y) { + return {static_cast(x), static_cast(y), static_cast(200u + slice), 0u}; +} + +std::array Drawn(std::uint32_t slice, std::uint32_t x, std::uint32_t y) { + return {static_cast(x), static_cast(y), DrawnBlue(slice), 255u}; +} + +AgcDriver::Graphics::ColorTarget DecodeLayeredView(std::uint64_t base, std::uint32_t tileIndex) { + AgcDriver::Registers cx; + cx[0x207] = LayerExports; + cx[0x318] = static_cast(base >> 8u); + cx[0x319] = Width / 8u - 1u; + cx[0x31a] = Width * Height / 64u - 1u; + cx[0x31b] = FirstSlice | (LastSlice << 13u); + cx[0x31c] = (Format8888 << 2u) | BlendClamp; + cx[0x31d] = tileIndex; + const auto target = AgcDriver::Graphics::DecodeColorBuffer(cx, 0); + Require(target.format == VK_FORMAT_R8G8B8A8_UNORM && target.samples == 1u && target.layers == LastSlice + 1u - FirstSlice && target.arraySlice == FirstSlice && target.arrayLastSlice == LastSlice && target.arrayAddress == base && target.address == base + FirstSlice * SliceBytes && target.bytes == SliceBytes, "the GCN view of slices 1 to 3 with a vertex render target index did not decode as a three-layer view of the array at its base"); + return target; +} + +std::string Describe(const char* mode, std::uint32_t slice, std::uint32_t x, std::uint32_t y, const std::uint8_t* texel) { + char text[192]; + std::snprintf(text, sizeof(text), "%s slice %u: the texel the texture path places at (%u, %u) holds %02x %02x %02x %02x", mode, slice, x, y, texel[0], texel[1], texel[2], texel[3]); + return text; +} + +std::size_t CheckArray(AgcDriver::VulkanDevice& device, const LowBlock& block, std::size_t offset, std::uint32_t tileIndex, AgcDriver::Graphics::TextureTileMode mode, const char* name) { + const auto base = block.At(offset); + const auto layout = TexturePlacement(mode, base); + std::vector guest(ArrayBytes); + for (std::uint32_t slice = 0; slice < Slices; ++slice) { + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) std::memcpy(guest.data() + TextureOffset(layout, slice, x, y), Background(slice, x, y).data(), ElementBytes); + } + } + AgcDriver::GuestMemory::Write(base, std::as_bytes(std::span(guest)), 256); + const auto target = DecodeLayeredView(base, tileIndex); + for (std::size_t index = 0; index < DrawnLayers.size(); ++index) Draw(device, block, target, DrawnLayers[index], Program(index, FirstSlice + DrawnLayers[index])); + AgcDriver::Graphics::StorageTexture::FlushPending(base, ArrayBytes, nullptr, "test read-back"); + device.WaitIdle(); + AgcDriver::GuestMemory::Read(base, std::as_writable_bytes(std::span(guest)), 256); + std::size_t drawnTotal = 0; + for (std::uint32_t slice = 0; slice < Slices; ++slice) { + const bool drawnSlice = slice >= FirstSlice && std::ranges::find(DrawnLayers, slice - FirstSlice) != DrawnLayers.end(); + std::size_t drawn = 0; + for (std::uint32_t y = 0; y < Height; ++y) { + for (std::uint32_t x = 0; x < Width; ++x) { + const auto* texel = guest.data() + TextureOffset(layout, slice, x, y); + const bool kept = std::memcmp(texel, Background(slice, x, y).data(), ElementBytes) == 0; + const bool written = drawnSlice && std::memcmp(texel, Drawn(slice, x, y).data(), ElementBytes) == 0; + Require(kept || written, Describe(name, slice, x, y, texel) + (drawnSlice ? ", neither its background nor the color drawn for it" : ", which no layer index chose, but not its background")); + drawn += written ? 1u : 0u; + } + } + const auto texels = std::size_t{Width} * Height; + Require(!drawnSlice || (drawn > texels / 4u && drawn < texels * 3u / 4u), std::string(name) + " slice " + std::to_string(slice) + ": the triangle covers " + std::to_string(drawn) + " of " + std::to_string(texels) + " texels"); + drawnTotal += drawn; + } + return drawnTotal; +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + ShaderRecompiler::SetGcnGuestShaders(true); + const LowBlock block; + if (!block.Usable()) { + std::printf("skipped, no guest block below the 40-bit GCN color base range (0x%llx)\n", static_cast(block.Address())); + return VulkanTestSkipped; + } + struct Mode { std::uint32_t index; AgcDriver::Graphics::TextureTileMode mode; const char* name; }; + constexpr std::array modes{{ + {13u, AgcDriver::Graphics::TextureTileMode::kGcnThin1D, "Thin1D"}, + {14u, AgcDriver::Graphics::TextureTileMode::kGcnThin2D, "Thin2D"}, + }}; + std::string counts; + for (std::size_t index = 0; index < modes.size(); ++index) { + const auto drawn = CheckArray(*device, block, index * ArrayStride, modes[index].index, modes[index].mode, modes[index].name); + counts += (index == 0 ? "" : ", ") + std::to_string(drawn) + " " + modes[index].name; + } + std::printf("GCN layered color target tests passed: in a view of slices 1 to 3 of four-slice thin 1D and 2D arrays, draws exporting render target index 0 and 2 land in slices 1 and 3 where the texture path places those layers (%s texels), and slices 0 and 2 keep their background\n", counts.c_str()); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/docs/dev/debt/changes/claude-ps4-gcn-layered-color.md b/docs/dev/debt/changes/claude-ps4-gcn-layered-color.md new file mode 100644 index 000000000000..e14bb8104630 --- /dev/null +++ b/docs/dev/debt/changes/claude-ps4-gcn-layered-color.md @@ -0,0 +1,5 @@ +# libSceAgcDriver + +## change [PS4 color array slices] + +- [PS4 color array slices](../../../core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp) (libSceAgcDriver, PS4) - not checked on a console. A `CB_COLOR_VIEW` of one slice renders into that slice, at the surface address plus the slice index times the slice size. A view of several slices renders into its first slice when `PA_CL_VS_OUT_CNTL` bit 18 (USE_VTX_RENDER_TARGET_INDX) is clear; with it set, a single-sample view renders into the slice the vertex render target index selects, counted from the slice start, through the array's resident image (see Layered color targets), and a multisampled one throws, as does a slice max below the slice start. Bits [12:11] and [31:24] are ignored: shadPS4 defines no fields there. Later slices of `GcnDisplay2D` and `GcnThin2D` take the bank rotation the texture path gives that layer (see PS4 (GCN) array layer banks), and such a single-slice view of a multisampled target throws. From f7e55e69066fe973706658ac3f474b0bc703b960 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:17:58 -0500 Subject: [PATCH 16/34] fix(agc): decode restarted ES-GS-VS clip layout from the copy program Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index eaa57b3c660c..dbc3a5e229d3 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -1525,7 +1525,8 @@ void Driver::restartFinishedDraw(DrawTail& tail) { if (program.binary.stage == Stage::Fragment || ShaderRecompiler::LinkedOnlyRole(roles[i])) continue; tail.vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, tail.decodeReads[i], 8u - program.firstUserSgpr); if (!tail.vertexInfos[i]) continue; - tail.vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, tail.reg207, program.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; + const auto& exporter = roles[i] == Role::Geometry && i + 1u < count && roles[i + 1u] == Role::Copy ? programs[i + 1u] : program; + tail.vertexInfos[i]->paClVsOutCntl = PositionExportLayout(exporter.snapshot.get(), exporter.codeOffset, exporter.binary.code, tail.reg207, exporter.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; tail.vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode; Graphics::ApplyPointSize(graphics, *tail.vertexInfos[i]); } From 73f688b955aa91988d1a0799cd720750c541db85 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:37:20 -0500 Subject: [PATCH 17/34] refactor(agc): share the GS position-export program choice across draw decode sites Co-Authored-By: Claude Opus 5.5 --- .../Execution/include/Driver/Draw/DrawCache.hpp | 1 + .../prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp | 6 +++--- .../Execution/src/Driver/Draw/DrawDecode.cpp | 7 +++++++ .../prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp | 6 ++++++ 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp index e0646962df33..c638ac83bf41 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp @@ -50,6 +50,7 @@ void DecodeGraphicsPrograms(DrawDecode& decoded, const QueueState& queue, const ShaderRecompiler::ShaderVertexStageInfo DecodeOrderedVertexStageInfo(std::span header, std::uint64_t headerAddress, std::span userData, std::vector& reads, std::uint32_t hiddenUserWords); void AppendProgramMemory(std::vector& memory, const std::vector& programs); +const DrawProgram& PositionExportProgram(const std::vector& programs, const std::vector& roles, std::size_t index); std::vector> UserDataWords(const std::vector& programs, const std::vector& roles, std::uint32_t location); struct PreparedGraphicsStage { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index a499cc855868..f8968aee7045 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -641,7 +641,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe if (program.binary.stage == Stage::Fragment || ShaderRecompiler::LinkedOnlyRole(roles[i])) return; vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, decodeReads[i], 8u - program.firstUserSgpr); if (vertexInfos[i]) { - const auto& exporter = roles[i] == Role::Geometry && i + 1u < programs.size() && roles[i + 1u] == Role::Copy ? programs[i + 1u] : program; + const auto& exporter = PositionExportProgram(programs, roles, i); vertexInfos[i]->paClVsOutCntl = PositionExportLayout(exporter.snapshot.get(), exporter.codeOffset, exporter.binary.code, readRegister(queue.context, 0x207), exporter.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode; Graphics::ApplyPointSize(graphics, *vertexInfos[i]); @@ -905,7 +905,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { decodeReads[i].clear(); vertexInfos[i] = Graphics::DecodeVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, &decodeReads[i], false, 8u - program.firstUserSgpr); if (vertexInfos[i]) { - const auto& exporter = roles[i] == Role::Geometry && i + 1u < programs.size() && roles[i + 1u] == Role::Copy ? programs[i + 1u] : program; + const auto& exporter = PositionExportProgram(programs, roles, i); vertexInfos[i]->paClVsOutCntl = PositionExportLayout(exporter.snapshot.get(), exporter.codeOffset, exporter.binary.code, tail.reg207, exporter.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode; Graphics::ApplyPointSize(graphics, *vertexInfos[i]); @@ -1526,7 +1526,7 @@ void Driver::restartFinishedDraw(DrawTail& tail) { if (program.binary.stage == Stage::Fragment || ShaderRecompiler::LinkedOnlyRole(roles[i])) continue; tail.vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, tail.decodeReads[i], 8u - program.firstUserSgpr); if (!tail.vertexInfos[i]) continue; - const auto& exporter = roles[i] == Role::Geometry && i + 1u < count && roles[i + 1u] == Role::Copy ? programs[i + 1u] : program; + const auto& exporter = PositionExportProgram(programs, roles, i); tail.vertexInfos[i]->paClVsOutCntl = PositionExportLayout(exporter.snapshot.get(), exporter.codeOffset, exporter.binary.code, tail.reg207, exporter.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; tail.vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode; Graphics::ApplyPointSize(graphics, *tail.vertexInfos[i]); diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp index 2e0cfe11408e..7d9498b58cff 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp @@ -91,6 +91,13 @@ void AppendProgramMemory(std::vector& memory, co } } +const DrawProgram& PositionExportProgram(const std::vector& programs, const std::vector& roles, std::size_t index) { + using Role = ShaderRecompiler::ProgramRole; + require(roles.size() == programs.size() && index < programs.size(), "draw program roles are incomplete"); + if (roles[index] == Role::Geometry && index + 1u < programs.size() && roles[index + 1u] == Role::Copy) return programs[index + 1u]; + return programs[index]; +} + std::vector> UserDataWords(const std::vector& programs, const std::vector& roles, std::uint32_t location) { using Role = ShaderRecompiler::ProgramRole; require(roles.size() == programs.size(), "draw program roles are incomplete"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index 9d8dc6b0d6da..07ce17abd58c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -331,6 +331,12 @@ void RequireProgramDecode() { Require(std::ranges::equal(program.userData, users[index]), name + " did not read its own stage's user data"); } Require(draw.state.stages.legacyGeometry->exports == Points().exports, "the copy program's exports were not read into the geometry configuration"); + Require(&PositionExportProgram(draw.programs, draw.roles, 1u) == &draw.programs[2], "the GS position export layout was not read from the copy program that exports the GS vertices"); + Require(&PositionExportProgram(draw.programs, draw.roles, 0u) == &draw.programs[0], "the ES position export layout was not read from the ES program"); + Require(&PositionExportProgram(draw.programs, draw.roles, 2u) == &draw.programs[2], "the copy program's position export layout was not read from itself"); + const std::vector alone{draw.programs[0], draw.programs[1]}; + const std::vector aloneRoles{ProgramRole::Main, ProgramRole::Geometry}; + Require(&PositionExportProgram(alone, aloneRoles, 1u) == &alone[1], "a geometry program without a following copy program read its position export layout from another program"); } } From c2ea4d4c0de0468f6a64b8ac75bd4b1778103bfb Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:36:27 -0500 Subject: [PATCH 18/34] fix(agc): close GCN geometry review gaps in decode, keys and lowering - A restarted ES-GS-VS draw rereads the copy program's exports when the copy program changed, through the same GeometryCopyExports the decode uses. - Draw keys cover the geometry configuration and every register the GCN geometry decode reads (the ES program registers, VGT_GS_MODE, VGT_GSVS_RING_ITEMSIZE, VGT_GS_VERT_ITEMSIZE_0-3, VGT_GS_INSTANCE_CNT, VGT_STRMOUT_CONFIG). - Indirect-draw user-data words use each program's hidden word count, so a GCN program's first user SGPR maps to word 0. - MSG_GS_DONE keeps its emit and cut operations; s_barrier in a geometry program no longer emits a workgroup control barrier. - The copy program parser reads a load's address before forgetting its destination; ring address terms refuse on 64-bit overflow. - Line or point polygon modes follow the geometry program's output primitive, not the point input topology. Co-Authored-By: Claude Opus 5.5 --- .../include/Driver/Draw/DrawCache.hpp | 3 + .../Execution/src/Driver/Draw/Draw.cpp | 10 ++- .../Execution/src/Driver/Draw/DrawDecode.cpp | 34 +++++++- .../Execution/src/Driver/Draw/DrawLookup.cpp | 1 + .../Graphics/include/State.hpp | 7 +- .../libSceAgcDriver/Graphics/src/State.cpp | 7 +- .../tests/execution/GcnGeometry.cpp | 78 ++++++++++++++++++- .../Optimization/src/GeometryLowering.cpp | 22 ++++-- .../SpirvBackend/src/SpirvFlowEmitter.cpp | 5 +- .../src/ControlFlowInstructions.cpp | 6 +- 10 files changed, 153 insertions(+), 20 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp index c638ac83bf41..c7250a9cbc18 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp @@ -42,6 +42,7 @@ struct DrawDecode { ShaderRecompiler::ShaderPixelStageInfo pixel; std::vector programs; std::vector roles; + std::optional copyStreamConfig; }; void ReadUserWords(const QueueState& queue, DrawProgram& program, bool staticAbi); @@ -51,6 +52,8 @@ ShaderRecompiler::ShaderVertexStageInfo DecodeOrderedVertexStageInfo(std::span& memory, const std::vector& programs); const DrawProgram& PositionExportProgram(const std::vector& programs, const std::vector& roles, std::size_t index); +std::vector GeometryCopyExports(const DrawDecode& decoded, const std::vector& programs); +std::uint64_t GeometryConfigurationKey(const std::optional& geometry); std::vector> UserDataWords(const std::vector& programs, const std::vector& roles, std::uint32_t location); struct PreparedGraphicsStage { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index f8968aee7045..40592a7b8edb 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -894,7 +894,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { if (location == 0x280u) return std::nullopt; for (std::size_t i = 0; i < programs.size(); ++i) { if (roles[i] == Role::Fragment || ShaderRecompiler::LinkedOnlyRole(roles[i]) || location < programs[i].userDataBase) continue; - const auto word = location - programs[i].userDataBase + (8u - programs[i].firstUserSgpr); + const auto word = location - programs[i].userDataBase + programs[i].hiddenUserWords; if (word < programs[i].userData.size()) return std::make_pair(i, static_cast(word)); } return std::nullopt; @@ -1484,6 +1484,14 @@ void Driver::restartFinishedDraw(DrawTail& tail) { if (fresh.header.empty()) NoteRawGraphicsDraw(fresh); program.snapshot = std::move(snapshot); } + if (tail.decode->state.stages.legacyGeometry) { + auto exports = GeometryCopyExports(*tail.decode, tail.writablePrograms); + if (exports != tail.decode->state.stages.legacyGeometry->exports) { + auto refreshed = std::make_shared(*tail.decode); + refreshed->state.stages.legacyGeometry->exports = std::move(exports); + tail.decode = std::move(refreshed); + } + } } if (tail.drawHit && !tail.userPatches.empty()) { if (verifyDrawRecipe()) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp index 7d9498b58cff..629df0744a86 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp @@ -98,6 +98,34 @@ const DrawProgram& PositionExportProgram(const std::vector& program return programs[index]; } +std::vector GeometryCopyExports(const DrawDecode& decoded, const std::vector& programs) { + const auto& geometry = decoded.state.stages.legacyGeometry; + require(geometry.has_value() && decoded.roles.size() == programs.size(), "GCN geometry copy exports were requested for a draw without a geometry configuration"); + for (std::size_t i = 0; i < programs.size(); ++i) { + if (decoded.roles[i] == ShaderRecompiler::ProgramRole::Copy) return ShaderRecompiler::ParseGeometryCopyProgram(programs[i].binary.code, geometry->maxVertices, geometry->vertexDwords, decoded.copyStreamConfig); + } + require(false, "a GCN geometry draw has no copy program"); + return {}; +} + +std::uint64_t GeometryConfigurationKey(const std::optional& geometry) { + std::uint64_t key = 0xcbf29ce484222325ull; + const auto mix = [&](std::uint64_t value) { + key ^= value; + key *= 0x100000001b3ull; + }; + mix(geometry.has_value()); + if (!geometry) return key; + for (const auto value : {geometry->inputVertices, geometry->outputTopology, geometry->maxVertices, geometry->instances, geometry->esgsItemDwords, geometry->vertexDwords}) mix(value); + mix(geometry->exports.size()); + for (const auto& copy : geometry->exports) { + for (const auto value : {copy.target, copy.enable, copy.constants}) mix(value); + for (const auto value : copy.values) mix(value); + mix(copy.done); + } + return key; +} + std::vector> UserDataWords(const std::vector& programs, const std::vector& roles, std::uint32_t location) { using Role = ShaderRecompiler::ProgramRole; require(roles.size() == programs.size(), "draw program roles are incomplete"); @@ -105,7 +133,7 @@ std::vector> UserDataWords(const std::vector if (location == 0x280u) return words; for (std::size_t i = 0; i < programs.size(); ++i) { if (roles[i] == Role::Fragment || ShaderRecompiler::LinkedOnlyRole(roles[i]) || location < programs[i].userDataBase) continue; - const auto word = location - programs[i].userDataBase + (8u - programs[i].firstUserSgpr); + const auto word = location - programs[i].userDataBase + programs[i].hiddenUserWords; if (word < programs[i].userData.size()) words.emplace_back(i, static_cast(word)); } return words; @@ -202,8 +230,8 @@ void DecodeGraphicsPrograms(DrawDecode& decoded, const QueueState& queue, const auto& geometry = *graphics.stages.legacyGeometry; const auto copyResources = queue.shader.find(0x04bu); const auto copyRsrc2 = copyResources == queue.shader.end() ? 0u : copyResources->second; - const auto streamConfig = (copyRsrc2 & 0x1000u) != 0u ? std::optional((copyRsrc2 >> 1u) & 0x1fu) : std::nullopt; - geometry.exports = ShaderRecompiler::ParseGeometryCopyProgram(programs.back().binary.code, geometry.maxVertices, geometry.vertexDwords, streamConfig); + product->copyStreamConfig = (copyRsrc2 & 0x1000u) != 0u ? std::optional((copyRsrc2 >> 1u) & 0x1fu) : std::nullopt; + geometry.exports = GeometryCopyExports(*product, programs); } else if (graphics.stages.legacyVertex) { append(0x48, 2, Stage::Vertex, 0x4b, 0x4c, Role::Main); } else { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp index 6ec8f295cd57..7e90882a3b48 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawLookup.cpp @@ -35,6 +35,7 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptr ExportTargetMerges(const State& state); ShaderRecompiler::RasterPrimitive RasterPrimitiveOf(const State& state); +bool RasterizesPointsOrLines(const State& state); bool PartialSampleMask(const State& state); bool UniformSampleMask(const State& state); VkSampleMask HostSampleMask(const State& state); @@ -384,7 +385,7 @@ struct DrawKeyRange { std::uint32_t first; std::uint32_t count; }; -inline constexpr std::array DrawKeyRegisters{{ +inline constexpr std::array DrawKeyRegisters{{ {RegisterBank::Context, 0x000, 1}, {RegisterBank::Context, 0x002, 2}, {RegisterBank::Context, 0x005, 1}, {RegisterBank::Context, 0x007, 7}, {RegisterBank::Context, 0x010, 6}, {RegisterBank::Context, 0x01a, 5}, {RegisterBank::Context, 0x080, 4}, {RegisterBank::Context, 0x08c, 4}, {RegisterBank::Context, 0x090, 2}, {RegisterBank::Context, 0x094, 0x20}, {RegisterBank::Context, 0x0b4, 2}, {RegisterBank::Context, 0x105, 4}, {RegisterBank::Context, 0x10b, 3}, {RegisterBank::Context, 0x10f, 0x60}, // SPI_PS_INPUT_CNTL_0..31, SPI_PS_INPUT_ENA/ADDR, SPI_PS_IN_CONTROL .. SPI_BARYC_CNTL, SPI_SHADER_POS/Z/COL_FORMAT, @@ -392,13 +393,13 @@ inline constexpr std::array DrawKeyRegisters{{ {RegisterBank::Context, 0x191, 32}, {RegisterBank::Context, 0x1b3, 2}, {RegisterBank::Context, 0x1b6, 3}, {RegisterBank::Context, 0x1c3, 3}, {RegisterBank::Context, 0x1e0, 8}, {RegisterBank::Context, 0x1ff, 1}, // DB_DEPTH_CONTROL .. PA_CL_VS_OUT_CNTL, PA_SC_MODE_CNTL_0/1, VGT_GS_MODE, VGT_GS_VERT_ITEMSIZE, // PA_SU_VTX_CNTL, the sample masks, PA_SC_CONSERVATIVE_RASTERIZATION_CNTL. - {RegisterBank::Context, 0x200, 8}, {RegisterBank::Context, 0x282, 1}, {RegisterBank::Context, 0x286, 2}, {RegisterBank::Context, 0x292, 2}, {RegisterBank::Context, 0x29b, 1}, {RegisterBank::Context, 0x2a8, 2}, {RegisterBank::Context, 0x2ab, 1}, {RegisterBank::Context, 0x2af, 1}, {RegisterBank::Context, 0x2ce, 1}, {RegisterBank::Context, 0x2d5, 2}, {RegisterBank::Context, 0x2db, 2}, {RegisterBank::Context, 0x2de, 6}, {RegisterBank::Context, 0x2f8, 2}, {RegisterBank::Context, 0x2fe, 16}, {RegisterBank::Context, 0x30e, 2}, {RegisterBank::Context, 0x313, 1}, + {RegisterBank::Context, 0x200, 8}, {RegisterBank::Context, 0x282, 1}, {RegisterBank::Context, 0x286, 2}, {RegisterBank::Context, 0x290, 1}, {RegisterBank::Context, 0x292, 2}, {RegisterBank::Context, 0x29b, 1}, {RegisterBank::Context, 0x2a8, 2}, {RegisterBank::Context, 0x2ab, 2}, {RegisterBank::Context, 0x2af, 1}, {RegisterBank::Context, 0x2ce, 1}, {RegisterBank::Context, 0x2d5, 6}, {RegisterBank::Context, 0x2db, 2}, {RegisterBank::Context, 0x2de, 6}, {RegisterBank::Context, 0x2e4, 2}, {RegisterBank::Context, 0x2f8, 2}, {RegisterBank::Context, 0x2fe, 16}, {RegisterBank::Context, 0x30e, 2}, {RegisterBank::Context, 0x313, 1}, // CB_COLOR0..7_BASE .. DCC_BASE (15 words a slot), CB_COLOR0..7_BASE_EXT, DCC_BASE_EXT, ATTRIB2, ATTRIB3. {RegisterBank::Context, 0x318, 0x78}, {RegisterBank::Context, 0x390, 8}, {RegisterBank::Context, 0x398, 0x10}, {RegisterBank::Context, 0x3a8, 0x18}, // The pixel program address, RSRC2 and user words; the geometry-back user pointer and program // address; the vertex/geometry-front RSRC1/RSRC2 and user words; the vertex program address; // the hull user pointer, program address, RSRC2 and user words; the local program address. - {RegisterBank::Shader, 0x008, 0x24}, {RegisterBank::Shader, 0x048, 0x14}, {RegisterBank::Shader, 0x082, 2}, {RegisterBank::Shader, 0x088, 2}, {RegisterBank::Shader, 0x08a, 0x22}, {RegisterBank::Shader, 0x0c8, 2}, {RegisterBank::Shader, 0x102, 2}, {RegisterBank::Shader, 0x108, 2}, {RegisterBank::Shader, 0x10b, 0x21}, {RegisterBank::Shader, 0x148, 0x14}, + {RegisterBank::Shader, 0x008, 0x24}, {RegisterBank::Shader, 0x048, 0x14}, {RegisterBank::Shader, 0x082, 2}, {RegisterBank::Shader, 0x088, 2}, {RegisterBank::Shader, 0x08a, 0x22}, {RegisterBank::Shader, 0x0c8, 0x24}, {RegisterBank::Shader, 0x102, 2}, {RegisterBank::Shader, 0x108, 2}, {RegisterBank::Shader, 0x10b, 0x21}, {RegisterBank::Shader, 0x148, 0x14}, // GE_PRIM_TYPE, GE_MULTI_PRIM_IB_RESET_EN, the geometry subgroup sizes. {RegisterBank::UserConfig, 0x242, 1}, {RegisterBank::UserConfig, 0x24b, 1}, {RegisterBank::UserConfig, 0x25b, 1}, }}; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp index 81c59c22c5fe..286915afc3ca 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp @@ -1935,7 +1935,7 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) { const auto raster = read(cx, 0x205); // Bits 5-10 give the front/back polygon type (2 = filled triangles), which POLY_MODE (bit 3) turns on // explicitly; KEEP_TOGETHER_ENABLE (bit 24) only affects primitive distribution across the chip. - const bool pointsOrLines = result.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || result.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || result.topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || (result.stages.mesh.has_value() && result.stages.mesh->outputPrimitiveSize <= 2u); + const bool pointsOrLines = RasterizesPointsOrLines(result); const auto lineOffset = (raster & 0x1800u) != 0 && !pointsOrLines ? 0x2000u : 0u; const auto rasterMode = raster & ~0x7u & ~0x7f8u & ~(1u << 24u) & ~0x1800u & ~lineOffset & ~(1u << 19u) & ~(1u << 16u); if (rasterMode != 0) throw std::runtime_error("AGC graphics: " + zeroMessage(0x205, raster, "depth bias or nonstandard rasterization")); @@ -2447,6 +2447,11 @@ std::array QuadSampleMasks(const State& state) { return masks; } +bool RasterizesPointsOrLines(const State& state) { + if (state.stages.legacyGeometry) return RasterPrimitiveOf(state) == ShaderRecompiler::RasterPrimitive::Line; + return state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || (state.stages.mesh.has_value() && state.stages.mesh->outputPrimitiveSize <= 2u); +} + ShaderRecompiler::RasterPrimitive RasterPrimitiveOf(const State& state) { if (state.rectList) return ShaderRecompiler::RasterPrimitive::Rectangle; if (state.stages.legacyGeometry) return state.stages.legacyGeometry->outputTopology == 1u ? ShaderRecompiler::RasterPrimitive::Line : ShaderRecompiler::RasterPrimitive::Triangle; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index 07ce17abd58c..fa3087ec9424 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -43,6 +43,20 @@ alignas(256) constexpr std::array GcnGeometry{ 0xe070403c, 0x08411000, 0xe070404c, 0x08410a00, 0xbf900022, 0xbf900012, 0xbf810000, }; +alignas(256) constexpr std::array GcnGeometryDone = [] { + auto code = GcnGeometry; + code[60] = 0xbf800000u; + code[61] = 0xbf900033u; + return code; +}(); + +alignas(256) constexpr std::array GcnGeometryBarrier = [] { + std::array code{}; + code[0] = 0xbf8a0000u; + for (std::size_t i = 0; i < GcnGeometry.size(); ++i) code[i + 1u] = GcnGeometry[i]; + return code; +}(); + alignas(256) constexpr std::array GcnCopy{ 0x34020082, 0xe0305000, 0x80400201, 0xe0305100, 0x80400301, 0xe0305200, 0x80400401, 0xb0040300, 0xe0305000, 0x04400501, 0xe0305400, 0x80400601, 0xbf8c0000, 0x7e0e0280, 0x7e1002f2, 0xf80008cf, @@ -78,6 +92,10 @@ alignas(256) constexpr std::array GcnCopySccClobbered{ 0x34000082, 0x900a9802, 0xb48a0000, 0x80058105, 0xbf840005, 0xe0305000, 0x80400200, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xbf810000, }; +alignas(256) constexpr std::array GcnCopyAliasedLoad{ + 0x34020082, 0xe0305000, 0x80400101, 0xbf8c0000, 0xf80008cf, 0x01010101, 0xbf810000, +}; + alignas(256) constexpr std::array GcnCopyComputed{ 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0x060604f2, 0xf80008cf, 0x02020302, 0xbf810000, }; @@ -133,6 +151,34 @@ ShaderRecompiler::RecompileResult Compile(const ShaderRecompiler::SpirvTarget& t return result; } +std::size_t CountOpcode(const ShaderRecompiler::RecompileResult& result, std::uint32_t opcode) { + const auto words = result.spirv.Words(); + std::size_t count = 0; + for (std::size_t i = 5; i < words.size();) { + const auto length = words[i] >> 16u; + if ((words[i] & 0xffffu) == opcode) ++count; + if (length == 0u) break; + i += length; + } + return count; +} + +void RequireGeometryMessages(const ShaderRecompiler::SpirvTarget& target) { + constexpr std::uint32_t OpEmitVertex = 218u; + constexpr std::uint32_t OpEndPrimitive = 219u; + constexpr std::uint32_t OpControlBarrier = 224u; + const auto geometry = Points(); + std::uint32_t cursor = 0; + const auto plain = Compile(target, ShaderStage::Geometry, GcnGeometry, GeometryUserData, cursor, geometry); + cursor = 0; + const auto done = Compile(target, ShaderStage::Geometry, GcnGeometryDone, GeometryUserData, cursor, geometry); + Require(CountOpcode(plain, OpEmitVertex) == 4u && CountOpcode(plain, OpEndPrimitive) == 1u, "the GCN geometry program did not emit four vertices and one cut"); + Require(CountOpcode(done, OpEmitVertex) == CountOpcode(plain, OpEmitVertex) && CountOpcode(done, OpEndPrimitive) == CountOpcode(plain, OpEndPrimitive), "MSG_GS_DONE with GS_OP_EMIT_CUT did not emit the final vertex and end the strip"); + cursor = 0; + const auto barrier = Compile(target, ShaderStage::Geometry, GcnGeometryBarrier, GeometryUserData, cursor, geometry); + Require(CountOpcode(barrier, OpControlBarrier) == 0u && CountOpcode(barrier, OpEmitVertex) == 4u, "s_barrier in a GCN geometry program emitted a workgroup control barrier"); +} + std::array PixelAt(float x, float y) { const auto column = static_cast((x + 1.0f) * 0.5f * Width); const auto row = static_cast((1.0f - y) * 0.5f * Height); @@ -218,6 +264,8 @@ void RequireCopyLayout() { Require(refused, "a copy program read at a slot stride other than VGT_GS_MAX_VERT_OUT times 64 bytes was accepted"); const auto streams = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyStreams, 4u, 5u, 2u); Require(streams.size() == 1u && streams[0].constants == 0u && streams[0].values == std::array{0u, 0u, 0u, 0u}, "the stream 0 block of a copy program that selects its stream from the stream-out configuration SGPR was not read"); + const auto aliased = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyAliasedLoad, 4u, 5u, std::nullopt); + Require(aliased.size() == 1u && aliased[0].constants == 0u && aliased[0].values == std::array{0u, 0u, 0u, 0u}, "a GSVS ring read that loads into its own address register was refused"); const auto skipped = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopySkip, 4u, 5u, std::nullopt); Require(skipped.size() == 1u && skipped[0].values == std::array{0u, 0u, 0u, 0u}, "a taken s_cbranch_scc0 did not skip the export it jumps over"); refused = false; @@ -271,7 +319,13 @@ AgcDriver::QueueState GeometryQueue() { void RequireStageDecode() { auto queue = GeometryQueue(); - const auto stages = AgcDriver::Graphics::DecodeShaderStages(queue); + std::vector log; + const auto stages = [&] { + const AgcDriver::Graphics::RegisterReadLogScope scope(&log); + return AgcDriver::Graphics::DecodeShaderStages(queue); + }(); + Require(!log.empty(), "the GCN geometry stage decode recorded no register reads"); + for (const auto read : log) Require(AgcDriver::Graphics::DrawKeyCovers(read), "DrawKeyRegisters lacks a register the GCN geometry decode reads: " + std::string(AgcDriver::Graphics::RegisterBankName(read.bank)) + " " + std::to_string(read.offset)); Require(stages.path == AgcDriver::Graphics::ShaderPath::Vertex && stages.legacyGeometry.has_value() && !stages.legacyVertex && !stages.mesh, "VGT_SHADER_STAGES_EN 0xb0 did not decode as GCN ES-GS-VS routing"); const auto& geometry = *stages.legacyGeometry; Require(geometry.inputVertices == 1u && geometry.outputTopology == 2u && geometry.maxVertices == 4u && geometry.instances == 1u && geometry.esgsItemDwords == 2u && geometry.vertexDwords == 5u, "the GCN geometry registers decoded to another configuration"); @@ -286,6 +340,13 @@ void RequireStageDecode() { } Require(false, "a GCN geometry draw was accepted with register 0x" + std::to_string(offset) + " = " + std::to_string(value)); }; + AgcDriver::Graphics::State points{}; + points.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; + Require(AgcDriver::Graphics::RasterizesPointsOrLines(points), "a plain point list draw was not rasterized as points"); + points.stages.legacyGeometry = Points(); + Require(!AgcDriver::Graphics::RasterizesPointsOrLines(points), "triangle strips a GCN geometry program makes from points were classified as points or lines, so a line polygon mode would draw them filled"); + points.stages.legacyGeometry->outputTopology = 1u; + Require(AgcDriver::Graphics::RasterizesPointsOrLines(points), "line strips from a GCN geometry program were not classified as lines"); refuses(0x2e5, 1u, "stream-out"); refuses(0x290, 0x00200033u, "VGT_GS_MODE"); refuses(0x2d8, 4u, "vertex streams 1-3"); @@ -331,6 +392,20 @@ void RequireProgramDecode() { Require(std::ranges::equal(program.userData, users[index]), name + " did not read its own stage's user data"); } Require(draw.state.stages.legacyGeometry->exports == Points().exports, "the copy program's exports were not read into the geometry configuration"); + Require(UserDataWords(draw.programs, draw.roles, 0x0ccu) == std::vector>{{0u, 0u}} && UserDataWords(draw.programs, draw.roles, 0x08du) == std::vector>{{1u, 1u}}, "a GCN program's first user SGPR register did not map to its first user data word"); + Require(GeometryCopyExports(draw, draw.programs) == Points().exports, "the copy exports of the decoded programs differ from the decode's"); + auto refreshed = draw.programs; + refreshed[2].binary.code = std::span(GcnCopyFolded); + Require(GeometryCopyExports(draw, refreshed) == ShaderRecompiler::ParseGeometryCopyProgram(GcnCopyFolded, 4u, 5u, std::nullopt), "a refreshed copy program's exports were not read from its new code"); + const auto key = GeometryConfigurationKey(draw.state.stages.legacyGeometry); + Require(key == GeometryConfigurationKey(Points()), "equal geometry configurations produced different draw keys"); + auto taller = Points(); + ++taller.maxVertices; + auto rerouted = Points(); + rerouted.exports[1].values[0] = 3u; + for (const auto& [other, name] : {std::pair{std::optional(taller), "VGT_GS_MAX_VERT_OUT"}, std::pair{std::optional(rerouted), "a copy export"}, std::pair{std::optional(), "no geometry configuration"}}) { + Require(GeometryConfigurationKey(other) != key, std::string("a geometry configuration differing in ") + name + " produced the same draw key"); + } Require(&PositionExportProgram(draw.programs, draw.roles, 1u) == &draw.programs[2], "the GS position export layout was not read from the copy program that exports the GS vertices"); Require(&PositionExportProgram(draw.programs, draw.roles, 0u) == &draw.programs[0], "the ES position export layout was not read from the ES program"); Require(&PositionExportProgram(draw.programs, draw.roles, 2u) == &draw.programs[2], "the copy program's position export layout was not read from itself"); @@ -355,6 +430,7 @@ int main() { return VulkanTestSkipped; } ShaderRecompiler::SetGcnGuestShaders(true); + RequireGeometryMessages(device->Target()); RequireQuads(*device); ShaderRecompiler::SetGcnGuestShaders(false); device.reset(); diff --git a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp index 612430366c88..e0b1b7238ffa 100644 --- a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp +++ b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp @@ -76,24 +76,33 @@ std::optional Evaluate(const IrValue* raw, std::uint32_t depth = 0u) { case IrOpcode::IAdd32: { const auto terms = pair(); if (!terms || (terms->first.vertex && terms->second.vertex)) return std::nullopt; - return Term{terms->first.vertex ? terms->first.vertex : terms->second.vertex, terms->first.scale + terms->second.scale, terms->first.constant + terms->second.constant}; + Term sum{terms->first.vertex ? terms->first.vertex : terms->second.vertex}; + if (__builtin_add_overflow(terms->first.scale, terms->second.scale, &sum.scale) || __builtin_add_overflow(terms->first.constant, terms->second.constant, &sum.constant)) return std::nullopt; + return sum; } case IrOpcode::ISub32: { const auto terms = pair(); if (!terms || terms->second.vertex) return std::nullopt; - return Term{terms->first.vertex, terms->first.scale, terms->first.constant - terms->second.constant}; + Term difference{terms->first.vertex, terms->first.scale}; + if (__builtin_sub_overflow(terms->first.constant, terms->second.constant, &difference.constant)) return std::nullopt; + return difference; } case IrOpcode::ShiftLeftLogical32: { const auto terms = pair(); if (!terms || terms->second.vertex || terms->second.constant < 0 || terms->second.constant > 31) return std::nullopt; - return Term{terms->first.vertex, terms->first.scale << terms->second.constant, terms->first.constant << terms->second.constant}; + const auto factor = std::int64_t{1} << terms->second.constant; + Term shifted{terms->first.vertex}; + if (__builtin_mul_overflow(terms->first.scale, factor, &shifted.scale) || __builtin_mul_overflow(terms->first.constant, factor, &shifted.constant)) return std::nullopt; + return shifted; } case IrOpcode::IMul32: { const auto terms = pair(); if (!terms || (terms->first.vertex && terms->second.vertex)) return std::nullopt; const auto& varying = terms->first.vertex ? terms->first : terms->second; const auto& factor = terms->first.vertex ? terms->second : terms->first; - return Term{varying.vertex, varying.scale * factor.constant, varying.constant * factor.constant}; + Term product{varying.vertex}; + if (__builtin_mul_overflow(varying.scale, factor.constant, &product.scale) || __builtin_mul_overflow(varying.constant, factor.constant, &product.constant)) return std::nullopt; + return product; } default: return std::nullopt; @@ -409,9 +418,10 @@ std::vector ParseGeometryCopyProgram(std::spansecond.vertexOffset) FailCopy("a GSVS ring read not addressed by the vertex index times 4", pc); + const bool vertexOffset = address != vectors.end() && address->second.vertexOffset; + Forget(vectors, scalars, instruction); + if (!instruction.offen || instruction.idxen || !vertexOffset) FailCopy("a GSVS ring read not addressed by the vertex index times 4", pc); const auto soffset = ScalarValue(instruction.source2, scalars); if (!soffset) FailCopy("a GSVS ring read whose scalar offset is not a constant", pc); const auto bytes = static_cast(*soffset) + instruction.memoryOffset; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp index 9c0b4dfc2d2f..a1ba45c70ab1 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvFlowEmitter.cpp @@ -1432,11 +1432,12 @@ void EmitVoid(SpirvValueEmitContext&) { void EmitBarrier(SpirvValueEmitContext& ctx, const IrValue& inst) { auto& state = ctx.state; - if (state.program.Resources().stage == IrShaderStage::Vertex) { + const auto stage = state.program.Resources().stage; + if (stage == IrShaderStage::Vertex || stage == IrShaderStage::Geometry) { if (PrecedesEveryMemoryAccess(state.program, inst)) return; for (const auto* block : state.program.BlockOrder()) { for (const auto* instruction : block->Instructions()) { - if (CommunicatesThroughMemory(instruction->Opcode())) ctx.Fail(inst, "s_barrier in a vertex program that accesses LDS or GDS or writes memory is not implemented"); + if (CommunicatesThroughMemory(instruction->Opcode())) ctx.Fail(inst, stage == IrShaderStage::Vertex ? "s_barrier in a vertex program that accesses LDS or GDS or writes memory is not implemented" : "s_barrier in a geometry program that accesses LDS or GDS or writes memory is not implemented"); } } return; diff --git a/core/shader/recompiler/Translation/src/ControlFlowInstructions.cpp b/core/shader/recompiler/Translation/src/ControlFlowInstructions.cpp index f65e7d7d9544..da571b15ffd8 100644 --- a/core/shader/recompiler/Translation/src/ControlFlowInstructions.cpp +++ b/core/shader/recompiler/Translation/src/ControlFlowInstructions.cpp @@ -262,10 +262,10 @@ void TranslationContext::sSendmsg(const RdnaInstruction& inst) { constexpr std::uint32_t GsDoneMessage = 3u; const auto simm = inst.rawWords[0] & 0xffffu; if (program.Resources().stage == IrShaderStage::Geometry && ((simm & 0xfu) == GsMessage || (simm & 0xfu) == GsDoneMessage)) { - if ((simm & 0xfu) == GsDoneMessage) return; - if (((simm >> 8u) & 3u) != 0u) throw std::runtime_error("a GCN geometry program emits to vertex stream " + std::to_string((simm >> 8u) & 3u) + ", and only stream 0 is rasterized without stream-out"); const auto operation = (simm >> 4u) & 3u; - if (operation != 0u) (void)ir.Emit(IrOpcode::EmitVertex, IrType::Void, {&ir.GetExec(), &ir.Constant(operation)}); + if (operation == 0u) return; + if (((simm >> 8u) & 3u) != 0u) throw std::runtime_error("a GCN geometry program emits to vertex stream " + std::to_string((simm >> 8u) & 3u) + ", and only stream 0 is rasterized without stream-out"); + (void)ir.Emit(IrOpcode::EmitVertex, IrType::Void, {&ir.GetExec(), &ir.Constant(operation)}); return; } (void)ir.Emit(IrOpcode::Sendmsg, IrType::Void, {}); From c614dad1c0d486bda601503a1bfc015350cf0150 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:02:31 -0500 Subject: [PATCH 19/34] fix(shader): bound computed on-chip tessellation LDS reads - A hull read of its on-chip output control points at a computed offset is now treated like a computed input read: the relative patch term is removed from the address, and a read that is not a whole number of control points is refused. - A computed on-chip LDS address whose dynamic term can be negative, or whose sign is unknown, is refused instead of being rebased below the output control points. - A pass-through hull on chip is refused when its control points need more per-vertex input or output components than the device allows. Co-Authored-By: Claude Opus 5.5 --- .../tests/execution/GcnTessellation.cpp | 48 +++++++++++++++++-- .../Optimization/src/TessellationLowering.cpp | 20 +++++++- 2 files changed, 61 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp index 13039b135dfa..3e19733b9cb1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp @@ -105,6 +105,33 @@ alignas(256) constexpr std::array GcnDomainOnChipOffsetInputs 0x101e1b0f, 0x7e200280, 0x7e2202f2, 0xf80008cf, 0x11100f0e, 0xf800020f, 0x11111111, 0xbf810000, }; +alignas(256) constexpr std::array GcnHullOnChipComputedOutputRead{ + 0xbefc03c1, 0xc2c60500, 0xd2900002, 0x02151101, 0xd2900003, 0x02210101, 0xbf8c007f, 0x34080484, + 0xd2860005, 0x04116103, 0xd8d80000, 0x06000005, 0xd8d80004, 0x07000005, 0x7e28020f, 0xd2860014, + 0x04502503, 0xd2860014, 0x04501b02, 0xbf8c007f, 0xd8340000, 0x00000614, 0xd8340004, 0x00000714, + 0x7d840480, 0x7e1a02f2, 0x00181a80, 0xd8340008, 0x00000c14, 0xbe86246a, 0x36100081, 0x7e100d08, + 0x081010f2, 0x34120684, 0xe0701000, 0x08000809, 0xe0701004, 0x08000809, 0xe0701008, 0x08000809, + 0xe070100c, 0x08000809, 0x261c0080, 0x341c1c84, 0x7e1e020f, 0xd286000f, 0x043c2503, 0x4a1e1d0f, + 0xd8d80008, 0x0b00000f, 0xbf8c007f, 0x7e140211, 0xd286000a, 0x04282103, 0xd8340000, 0x00000b0a, + 0xbf810000, +}; + +alignas(256) constexpr std::array GcnHullOnChipComputedOutputReadPatchData{ + 0xbefc03c1, 0xc2c60500, 0xd2900002, 0x02151101, 0xd2900003, 0x02210101, 0xbf8c007f, 0x34080484, + 0xd2860005, 0x04116103, 0xd8d80000, 0x06000005, 0xd8d80004, 0x07000005, 0x7e28020f, 0xd2860014, + 0x04502503, 0xd2860014, 0x04501b02, 0xbf8c007f, 0xd8340000, 0x00000614, 0xd8340004, 0x00000714, + 0x7d840480, 0x7e1a02f2, 0x00181a80, 0xd8340008, 0x00000c14, 0xbe86246a, 0x36100681, 0x7e100d08, + 0x081010f2, 0x34120684, 0xe0701000, 0x08000809, 0xe0701004, 0x08000809, 0xe0701008, 0x08000809, + 0xe070100c, 0x08000809, 0x261c0080, 0x341c1c84, 0x7e1e020f, 0xd286000f, 0x043c2503, 0x4a1e1d0f, + 0xd8d80008, 0x0b00000f, 0xbf8c007f, 0x7e140211, 0xd286000a, 0x04282103, 0xd8340000, 0x00000b0a, + 0xbf810000, +}; + +alignas(256) constexpr std::array GcnDomainOnChipBelowOutputs{ + 0xbefc03c1, 0xc2c20100, 0xbf8c007f, 0xd2860004, 0x02001502, 0x261c0680, 0x341c1c84, 0x4c081d04, + 0xd8d800c0, 0x05000004, 0xbf8c007f, 0xf80008cf, 0x05050505, 0xbf810000, +}; + using Constants = std::array; alignas(16) constexpr Constants PassthroughConstants{16u, 16u, 4u, 0u, 16u, 192u, 48u, 0u, 0u}; @@ -136,8 +163,9 @@ std::array HullUserData(const Constants& constants) { return {RingUserData[0], RingUserData[1], RingUserData[2], RingUserData[3], buffer[0], buffer[1], buffer[2], buffer[3]}; } -TessellationConfiguration Patches(bool onChip) { +TessellationConfiguration Patches(bool onChip, std::uint32_t primitiveGroupSize = 0u) { TessellationConfiguration configuration{3u, 3u, 1u, 0u, 2u, 4u}; + configuration.primitiveGroupSize = primitiveGroupSize; configuration.onChip = onChip; return configuration; } @@ -193,10 +221,10 @@ void ExpectConstantsRequired(const ShaderRecompiler::SpirvTarget& target, Shader Require(false, "an on-chip GCN tessellation program that addresses LDS through the tessellation constant buffer compiled without its constants"); } -void ExpectRefusal(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, const std::string& reason) { +void ExpectRefusal(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, const std::string& reason, std::span userData = {}, const std::optional& constants = std::nullopt) { std::uint32_t cursor = 0; try { - static_cast(Compile(target, stage, code, cursor, Patches(true))); + static_cast(Compile(target, stage, code, cursor, Patches(true), userData, constants)); } catch (const std::exception& error) { Require(std::string(error.what()).find(reason) != std::string::npos, "the refusal named another reason: " + std::string(error.what())); return; @@ -259,9 +287,9 @@ void Draw(AgcDriver::VulkanDevice& device, const Stages& stages, const Tessellat device.WaitIdle(); } -void RequirePatches(AgcDriver::VulkanDevice& device, std::span hull, std::span domain, bool onChip, const std::string& program, const std::optional& constants = std::nullopt) { +void RequirePatches(AgcDriver::VulkanDevice& device, std::span hull, std::span domain, bool onChip, const std::string& program, const std::optional& constants = std::nullopt, std::uint32_t primitiveGroupSize = 0u) { const auto target = device.Target(); - const auto configuration = Patches(onChip); + const auto configuration = Patches(onChip, primitiveGroupSize); const auto hullUsers = constants ? HullUserData(*constants) : std::array{}; const auto domainUsers = constants ? ConstantBuffer(*constants) : std::array{}; const auto hullData = constants ? std::span(hullUsers) : std::span(); @@ -354,10 +382,20 @@ int main() { RequirePatches(*device, GcnHullOnChipPassthrough, GcnDomainOnChipInputs, true, "GCN on-chip pass-through LS-HS-VS draw through LDS", PassthroughConstants); RequirePatches(*device, GcnHullOnChipOutputs, GcnDomainOnChipInputs, true, "GCN on-chip LS-HS-VS draw with hull output control points in LDS", OutputConstants); RequirePatches(*device, GcnHullOnChipOutputs, GcnDomainOnChipOffsetInputs, true, "GCN on-chip LS-HS-VS draw whose domain shader reaches the hull output control points through its LDS instruction offset", OutputConstants); + RequirePatches(*device, GcnHullOnChipComputedOutputRead, GcnDomainOnChipInputs, true, "GCN on-chip LS-HS-VS draw whose hull reads its patch's output control point 0 at a computed offset", OutputConstants); + RequirePatches(*device, GcnHullOnChipComputedOutputReadPatchData, GcnDomainOnChipInputs, true, "GCN on-chip LS-HS-VS draw, with GE_CNTL.PRIM_GRP_SIZE 4, whose hull takes its factors from its relative patch index and reads its patch's output control point 0 at a computed offset", OutputConstants, 4u); const auto hullUsers = HullUserData(PassthroughConstants); const auto domainUsers = ConstantBuffer(PassthroughConstants); ExpectConstantsRequired(target, ShaderStage::TessellationControl, GcnHullOnChipPassthrough, hullUsers, 4u); ExpectConstantsRequired(target, ShaderStage::TessellationEvaluation, GcnDomainOnChipInputs, domainUsers, 0u); + const auto outputDomainUsers = ConstantBuffer(OutputConstants); + ExpectRefusal(target, ShaderStage::TessellationEvaluation, GcnDomainOnChipBelowOutputs, "at a computed offset that can fall below the hull shader's on-chip output control points", outputDomainUsers, OutputConstants); + auto narrowOutputs = target; + narrowOutputs.tessellation->maxControlPerVertexOutputComponents = 2u; + ExpectRefusal(narrowOutputs, ShaderStage::TessellationControl, GcnHullOnChipPassthrough, "the pass-through hull shader's control points exceed the device limits (4 input and 4 output components per control point", hullUsers, PassthroughConstants); + auto narrowInputs = target; + narrowInputs.tessellation->maxControlPerVertexInputComponents = 2u; + ExpectRefusal(narrowInputs, ShaderStage::TessellationControl, GcnHullOnChipPassthrough, "the pass-through hull shader's control points exceed the device limits (4 input and 4 output components per control point", hullUsers, PassthroughConstants); ShaderRecompiler::SetGcnGuestShaders(false); device.reset(); std::puts("GCN tessellation tests passed"); diff --git a/core/shader/recompiler/Optimization/src/TessellationLowering.cpp b/core/shader/recompiler/Optimization/src/TessellationLowering.cpp index c93389e8b550..ef3b386a6220 100644 --- a/core/shader/recompiler/Optimization/src/TessellationLowering.cpp +++ b/core/shader/recompiler/Optimization/src/TessellationLowering.cpp @@ -874,6 +874,7 @@ class Lowering { if (stage == IrShaderStage::TessellationControl) lowerWaterfallTests(); collect(); derive(); + if (passthrough) requirePassthroughLimits(); orderControlOutputReads(); for (const auto& access : accesses) rewrite(access); if (passthrough) copyInputControlPoints(); @@ -1182,6 +1183,7 @@ class Lowering { if (!access.write) { if (controlStride == 0u) Fail("the hull shader reads off-chip memory but writes no control point there, so the control point stride is unknown", access.pc); if ((address.vertex != 0 && address.vertex != controlStride) || address.relative != outputs * controlStride || address.constant < 0 || end + address.vertex * (outputs - 1) > outputs * controlStride) Fail("the hull shader reads off-chip memory outside its patch's control points", access.pc); + if (address.dynamic && (address.dynamicScale == 0 || address.dynamicScale % controlStride != 0)) Fail("the hull shader reads its output control points at a computed offset that is not a whole number of control points", access.pc); break; } if (address.vertex == 0 && !soleControlPoint(access)) { @@ -1235,7 +1237,8 @@ class Lowering { if (user->Opcode() != IrOpcode::GetTessellationAttribute || user->Argument(1)->Resolve() != value->Resolve()) return false; const bool control = IsImmediate(user->Argument(0), static_cast(TessellationAttribute::ControlInput)); const bool evaluation = IsImmediate(user->Argument(0), static_cast(TessellationAttribute::EvaluationInput)); - if (!control && !evaluation) return false; + const bool output = stage == IrShaderStage::TessellationControl && IsImmediate(user->Argument(0), static_cast(TessellationAttribute::ControlOutput)); + if (!control && !evaluation && !output) return false; const auto address = evaluator.Evaluate(value, user->Argument(2), true); const auto stride = control ? static_cast(tessellation.inputControlPoints) * localStride : static_cast(tessellation.outputControlPoints) * controlStride; return address && address->dynamic && address->relative == stride; @@ -1536,6 +1539,17 @@ class Lowering { } } + void requirePassthroughLimits() const { + if (limits == nullptr) Fail("the target has no tessellation limits for a pass-through hull shader on chip", 0u); + const auto input = 4u * ((localStride + 15u) / 16u); + const auto output = 4u * ((controlStride + 15u) / 16u); + if (input > limits->maxControlPerVertexInputComponents || output > limits->maxControlPerVertexOutputComponents) { + char text[256]; + std::snprintf(text, sizeof(text), "the pass-through hull shader's control points exceed the device limits (%u input and %u output components per control point, %u and %u allowed)", input, output, limits->maxControlPerVertexInputComponents, limits->maxControlPerVertexOutputComponents); + Fail(text, 0u); + } + } + void requireMergedLimits() const { if (limits == nullptr) Fail("the target has no tessellation limits for a merged hull program", 0u); const auto vectors = [](std::uint32_t bytes) { return (bytes + 15u) / 16u; }; @@ -1640,6 +1654,7 @@ class Lowering { if (evaluator.Lowest(access.address) < base) Fail("a hull shader reads LDS across its input and output control points on chip", access.pc); access.kind = TessellationAttribute::ControlOutput; } + if (access.address.dynamic && (access.address.dynamicRoot == nullptr || access.address.dynamicScale < 0)) Fail(stage == IrShaderStage::TessellationControl ? "a hull shader addresses LDS on chip at a computed offset that can fall below its on-chip output control points" : "a domain shader reads LDS on chip at a computed offset that can fall below the hull shader's on-chip output control points", access.pc); if (evaluator.Lowest(access.address) < base) Fail(stage == IrShaderStage::TessellationControl ? "a hull shader writes LDS below its on-chip output control points" : "a domain shader reads LDS below the hull shader's on-chip output control points", access.pc); if (base == 0) return; access.address.constant -= base; @@ -1739,7 +1754,8 @@ class Lowering { for (IrValue* inst : block->Instructions()) { if (inst->Opcode() != IrOpcode::GetTessellationAttribute) continue; const bool control = IsImmediate(inst->Argument(0), static_cast(TessellationAttribute::ControlInput)); - if (!control && !IsImmediate(inst->Argument(0), static_cast(TessellationAttribute::EvaluationInput))) continue; + const bool output = stage == IrShaderStage::TessellationControl && IsImmediate(inst->Argument(0), static_cast(TessellationAttribute::ControlOutput)); + if (!control && !output && !IsImmediate(inst->Argument(0), static_cast(TessellationAttribute::EvaluationInput))) continue; const auto address = evaluator.Evaluate(inst->Argument(1), inst->Argument(2), true); if (!address || !address->dynamic || address->relative == 0) continue; IrValue& patch = program.CreateValue(IrOpcode::IMul32, IrType::U32); From a1503285b91df69330a1c9ce4415ee97798bd8e7 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:40:32 -0500 Subject: [PATCH 20/34] test(shader): replay version 64 tessellated requests with emulated barycentrics A version 64 tessellated request whose last byte is the emulated barycentrics flag must read with barycentrics set and the on-chip flag clear, and a version 65 request must keep both. Co-Authored-By: Claude Opus 5.5 --- .../tests/RequestSerializerTests.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index 36844b8e7a85..f539b332717c 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -244,6 +244,29 @@ std::vector Version63Bytes(std::vector bytes) { return bytes; } +void VerifyTessellationOnChipWithBarycentrics() { + const ShaderRecompiler::RequestSerializer serializer; + for (const bool onChip : {false, true}) { + ShaderRecompiler::RecompileRequest request{}; + request.graphics.emplace(); + request.graphics->tessellation = ShaderRecompiler::TessellationConfiguration{3u, 3u, 1u, 0u, 2u}; + request.graphics->tessellation->onChip = onChip; + request.graphics->emulateBarycentrics = true; + const auto encoded = serializer.Serialize(request); + const auto replay = serializer.Deserialize(encoded); + Require(replay.request.graphics && replay.request.graphics->emulateBarycentrics && replay.request.graphics->tessellation && replay.request.graphics->tessellation->onChip == onChip); + Require(serializer.Serialize(replay.request) == encoded); + const auto current = DecodeBase64(encoded); + const auto older = Version64Bytes(current); + Require(older[4] == 64u && older.size() < current.size() && older.back() == 1u); + const auto replay64 = serializer.Deserialize(EncodeBase64(older)); + Require(replay64.request.graphics && replay64.request.graphics->emulateBarycentrics && replay64.request.graphics->tessellation && !replay64.request.graphics->tessellation->onChip); + ShaderRecompiler::RecompileRequest plain = request; + plain.graphics->tessellation->onChip = false; + Require(serializer.Serialize(replay64.request) == serializer.Serialize(plain)); + } +} + std::string SerializeVersion56(const ShaderRecompiler::RecompileRequest& request) { auto bytes = Version63Bytes(DecodeBase64(ShaderRecompiler::RequestSerializer{}.Serialize(request))); Require(bytes.size() > 14u && bytes[4] == 63u); @@ -1323,6 +1346,7 @@ void VerifySplitState() { int main() { VerifyTessellationOnChip(); + VerifyTessellationOnChipWithBarycentrics(); VerifySplitState(); VerifySingleSampleVersion63(); VerifyTargetOptions(); From 715ebdfed6897a1409884044450183632af5bb0d Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:52:00 -0500 Subject: [PATCH 21/34] test(shader): replay version 65 tessellated requests with emulated barycentrics A version 65 tessellated request that ends with the emulated barycentrics flag reads with that flag set, its on-chip flag kept and no tessellation constants. Co-Authored-By: Claude Opus 5.5 --- core/shader/recompiler/tests/RequestSerializerTests.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/shader/recompiler/tests/RequestSerializerTests.cpp b/core/shader/recompiler/tests/RequestSerializerTests.cpp index 0d96bbf7d4bf..c6cd3282993a 100644 --- a/core/shader/recompiler/tests/RequestSerializerTests.cpp +++ b/core/shader/recompiler/tests/RequestSerializerTests.cpp @@ -293,6 +293,10 @@ void VerifyTessellationOnChipWithBarycentrics() { Require(replay.request.graphics && replay.request.graphics->emulateBarycentrics && replay.request.graphics->tessellation && replay.request.graphics->tessellation->onChip == onChip); Require(serializer.Serialize(replay.request) == encoded); const auto current = DecodeBase64(encoded); + const auto version65 = Version65Bytes(current); + Require(version65[4] == 65u && version65.size() + 1u == current.size() && version65.back() == 1u && version65[version65.size() - 2u] == (onChip ? 1u : 0u)); + const auto replay65 = serializer.Deserialize(EncodeBase64(version65)); + Require(replay65.request.graphics && replay65.request.graphics->emulateBarycentrics && replay65.request.graphics->tessellation && replay65.request.graphics->tessellation->onChip == onChip && !replay65.request.graphics->tessellationConstants); const auto older = Version64Bytes(current); Require(older[4] == 64u && older.size() < current.size() && older.back() == 1u); const auto replay64 = serializer.Deserialize(EncodeBase64(older)); From 6bbf38cc2b0dcf0d757105cfd6020e14fe8c2016 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:53:26 -0500 Subject: [PATCH 22/34] fix(agc): collapse a zero-width viewport only for GCN geometry triangle output A zero-width viewport is taken as drawing nothing only when the draw rasterizes triangles. A GCN geometry program that turns triangles into line strips or points now reaches the unsupported viewport transform refusal instead of having every fragment scissored away. Co-Authored-By: Claude Opus 5.5 --- core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp | 1 + core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp | 8 +++++++- .../prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp | 9 +++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp index e26c9fe5a39a..4935fe87b5d9 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp @@ -282,6 +282,7 @@ bool DepthStencilTests(const State& state); std::vector ExportTargetMerges(const State& state); ShaderRecompiler::RasterPrimitive RasterPrimitiveOf(const State& state); bool RasterizesPointsOrLines(const State& state); +bool CollapsedViewportDrawsNothing(const State& state); bool PartialSampleMask(const State& state); bool UniformSampleMask(const State& state); VkSampleMask HostSampleMask(const State& state); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp index 286915afc3ca..c42dd5158ac8 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/State.cpp @@ -2047,7 +2047,7 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) { std::fprintf(stderr, "[gpu] layer/viewport index vertex exports are ignored (PA_CL_VS_OUT_CNTL=0x%08x)\n", read(cx, 0x207)); } } - const bool areaFree = result.stages.path == ShaderPath::Vertex && (result.rectList || result.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || result.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN || result.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP); + const bool areaFree = CollapsedViewportDrawsNothing(result); bool collapsed = false; if (viewportControl == 0u && !viewportProgrammed(cx)) { result.viewport = VkViewport{0.0f, 0.0f, static_cast(result.renderExtent.width), static_cast(result.renderExtent.height), result.negativeOneToOne ? -1.0f : 0.0f, 1.0f}; @@ -2447,6 +2447,12 @@ std::array QuadSampleMasks(const State& state) { return masks; } +bool CollapsedViewportDrawsNothing(const State& state) { + if (state.stages.path != ShaderPath::Vertex) return false; + if (state.stages.legacyGeometry && state.stages.legacyGeometry->outputTopology != 2u) return false; + return state.rectList || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; +} + bool RasterizesPointsOrLines(const State& state) { if (state.stages.legacyGeometry) return RasterPrimitiveOf(state) == ShaderRecompiler::RasterPrimitive::Line; return state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || (state.stages.mesh.has_value() && state.stages.mesh->outputPrimitiveSize <= 2u); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index fa3087ec9424..c7450ee4be8e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -347,6 +347,15 @@ void RequireStageDecode() { Require(!AgcDriver::Graphics::RasterizesPointsOrLines(points), "triangle strips a GCN geometry program makes from points were classified as points or lines, so a line polygon mode would draw them filled"); points.stages.legacyGeometry->outputTopology = 1u; Require(AgcDriver::Graphics::RasterizesPointsOrLines(points), "line strips from a GCN geometry program were not classified as lines"); + AgcDriver::Graphics::State triangles{}; + triangles.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + Require(AgcDriver::Graphics::CollapsedViewportDrawsNothing(triangles), "a zero-width viewport no longer collapses a plain triangle list draw"); + triangles.stages.legacyGeometry = Points(); + Require(AgcDriver::Graphics::CollapsedViewportDrawsNothing(triangles), "a zero-width viewport no longer collapses triangle strips from a GCN geometry program"); + triangles.stages.legacyGeometry->outputTopology = 1u; + Require(!AgcDriver::Graphics::CollapsedViewportDrawsNothing(triangles), "a zero-width viewport was taken as drawing nothing for line strips a GCN geometry program makes from triangles, which still cover pixels"); + triangles.stages.legacyGeometry->outputTopology = 0u; + Require(!AgcDriver::Graphics::CollapsedViewportDrawsNothing(triangles), "a zero-width viewport was taken as drawing nothing for points a GCN geometry program makes from triangles"); refuses(0x2e5, 1u, "stream-out"); refuses(0x290, 0x00200033u, "VGT_GS_MODE"); refuses(0x2d8, 4u, "vertex streams 1-3"); From 42e81a08835c74566da606b19a511884b08d15bd Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:55:19 -0500 Subject: [PATCH 23/34] fix(shader): refuse a merged hull program that keeps its outputs on chip A merged hull program's LDS writes are taken as merged records before the on-chip checks run, so a merged hull with OC_LDS_EN clear now fails by name instead. A register-key test also checks that every GCN local stage user data word (0x14c-0x15b) is part of the draw key. Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/tests/RegisterKey.cpp | 9 +++++++++ .../tests/TessellationLowering.cpp | 16 ++++++++++++++++ .../Optimization/src/TessellationLowering.cpp | 1 + 3 files changed, 26 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/RegisterKey.cpp b/core/libs/prx/libSceAgcDriver/tests/RegisterKey.cpp index 430cad5fa4bc..72f709012d51 100644 --- a/core/libs/prx/libSceAgcDriver/tests/RegisterKey.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/RegisterKey.cpp @@ -68,6 +68,15 @@ void testFingerprints() { check(RegisterStateKey(queue, false, true, nullptr, &parts) != beforeRuntimeKey, "runtime-register mutation did not change the key"); check(parts.userDataRegisters != beforeRuntimeMutation.userDataRegisters && parts.auxiliaryRegisters == beforeRuntimeMutation.auxiliaryRegisters && parts.stableRegisters == beforeRuntimeMutation.stableRegisters, "user-data register change was not isolated"); queue = QueueState{}; + queue.shader[0x14b] = 2u << 1u; + for (std::uint32_t offset = 0x14cu; offset < 0x15cu; ++offset) { + const auto beforeLocalKey = RegisterStateKey(queue, false, true, nullptr, &parts); + const auto beforeLocal = parts; + queue.shader[offset] = offset; + check(RegisterStateKey(queue, false, true, nullptr, &parts) != beforeLocalKey, "a GCN local-stage user data word change did not change the draw register key"); + check(parts.stableRegisters != beforeLocal.stableRegisters, "a GCN local-stage user data word change was not attributed to the stable registers"); + } + queue = QueueState{}; auto reference = baselineRegisterStateKey(queue); auto tracked = RegisterStateKey(queue); const auto compare = [&] { diff --git a/core/libs/prx/libSceAgcDriver/tests/TessellationLowering.cpp b/core/libs/prx/libSceAgcDriver/tests/TessellationLowering.cpp index 2ec08d4fdb34..5833d2bc69f5 100644 --- a/core/libs/prx/libSceAgcDriver/tests/TessellationLowering.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/TessellationLowering.cpp @@ -1190,6 +1190,22 @@ int main() { return true; }); + passed &= run("a merged hull program that keeps its outputs on chip is refused before its LDS writes are taken as merged records", [] { + Hull hull; + auto& record = hull.builder.IMul(hull.relativePatch(), hull.builder.Constant(16u)); + auto& own = hull.builder.IAdd(record, hull.builder.IMul(hull.invocation(), hull.builder.Constant(16u))); + static_cast(hull.builder.Emit(IrOpcode::WriteSharedU32, IrType::Void, {&own, &hull.builder.Constant(7u), &hull.builder.ConstantBool(true)}, MemoryFlags{0u, RingWritePc})); + static_cast(hull.read(hull.builder.IAdd(hull.builder.IMul(hull.relativePatch(), hull.builder.Constant(16u)), hull.builder.Constant(4u)))); + const ShaderTessellationInputInfo merged{.inputControlPoints = 1u, .outputControlPoints = 1u, .patchesPerGroup = 1u, .mergedHull = true, .onChip = true}; + const TessellationTargetLimits limits{32u, 128u, 128u, 120u, 4096u, 128u, 128u}; + try { + TessellationLowering{}.Lower(hull.program, merged, &limits); + } catch (const std::exception& error) { + return std::string(error.what()).find("merged hull program cannot keep its outputs on chip") != std::string::npos; + } + return false; + }); + passed &= run("quad factors at an address that adds the invocation are refused when the hull program has several control points", [] { Hull hull; hull.writeFactor(hull.builder.IAdd(hull.builder.IMul(hull.relativePatch(), hull.builder.Constant(24u)), hull.builder.IMul(hull.invocation(), hull.builder.Constant(4u)))); diff --git a/core/shader/recompiler/Optimization/src/TessellationLowering.cpp b/core/shader/recompiler/Optimization/src/TessellationLowering.cpp index 5dafb093192d..85c880caf48e 100644 --- a/core/shader/recompiler/Optimization/src/TessellationLowering.cpp +++ b/core/shader/recompiler/Optimization/src/TessellationLowering.cpp @@ -863,6 +863,7 @@ class Lowering { evaluator(stage == IrShaderStage::TessellationControl ? tessellation.outputControlPoints : capture ? 1u : 0u, stage == IrShaderStage::Local ? LocalVertexIndexCount : static_cast(tessellation.patchesPerGroup), capture), localStride(program.Metadata().tessellationLocalStride) {} void Run() { + if (merged && tessellation.onChip) Fail("a merged hull program cannot keep its outputs on chip (SPI_SHADER_PGM_RSRC2_HS.OC_LDS_EN=0)", 0u); if (merged) { if (tessellation.inputControlPoints > tessellation.outputControlPoints) Fail("a merged hull program with more input than output control points runs its local part on lanes the hull stage does not have", 0u); requireUniformBarriers(); From 8c5d5183d273604c3c35ce56a4e508b3ff501ce0 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:10:02 -0500 Subject: [PATCH 24/34] fix(agc): map indirect-draw user data registers through hidden user words UserDataWords placed a user data register at 8 - firstUserSgpr words into a program's user data. A GCN program has no hidden words and its first user SGPR is 0, so its first register mapped to word 8 and an indirect draw's base vertex, start instance or draw index was patched in the wrong word or not at all. The word is now the program's hidden word count plus the register's offset, as DrawRelocate already does. Co-Authored-By: Claude Opus 5.5 --- .../libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp | 2 +- .../libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp | 2 +- .../prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp | 2 ++ 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 30197a03de13..07132cf7e1e1 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -892,7 +892,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { if (location == 0x280u) return std::nullopt; for (std::size_t i = 0; i < programs.size(); ++i) { if (roles[i] == Role::Fragment || roles[i] == Role::GeometryBack || location < programs[i].userDataBase) continue; - const auto word = location - programs[i].userDataBase + (8u - programs[i].firstUserSgpr); + const auto word = location - programs[i].userDataBase + programs[i].hiddenUserWords; if (word < programs[i].userData.size()) return std::make_pair(i, static_cast(word)); } return std::nullopt; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp index 22ffa0aa62ee..b92d421ff346 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp @@ -98,7 +98,7 @@ std::vector> UserDataWords(const std::vector if (location == 0x280u) return words; for (std::size_t i = 0; i < programs.size(); ++i) { if (roles[i] == Role::Fragment || roles[i] == Role::GeometryBack || location < programs[i].userDataBase) continue; - const auto word = location - programs[i].userDataBase + (8u - programs[i].firstUserSgpr); + const auto word = location - programs[i].userDataBase + programs[i].hiddenUserWords; if (word < programs[i].userData.size()) words.emplace_back(i, static_cast(word)); } return words; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp index 262affde6453..ebbba5a2188f 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp @@ -265,6 +265,8 @@ void RequireProgramDecode() { Require(std::ranges::equal(program.userData, users[index]), name + " did not read its own stage's user data"); } Require(!draw.state.stages.tessellation->mergedHull, "a GCN hull program decoded as a merged hull"); + using Words = std::vector>; + Require(UserDataWords(draw.programs, draw.roles, 0x14cu) == Words{{0u, 0u}} && UserDataWords(draw.programs, draw.roles, 0x10du) == Words{{1u, 1u}} && UserDataWords(draw.programs, draw.roles, 0x04eu) == Words{{2u, 2u}}, "a GCN program's user data register did not map to its own user data word, so an indirect draw would patch another word"); } } From ddbed321b8046d5c83d77f592b423b49e973526e Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:10:49 -0500 Subject: [PATCH 25/34] fix(shader): refuse an on-chip pass-through hull that reads LDS after writing it With its output control points at LDS offset 0, a pass-through hull's LDS reads are served from its input control points. A read that can follow one of its own LDS writes would return the input value instead of the written one, so it is now refused by name. Reads before every write still draw. Co-Authored-By: Claude Opus 5.5 --- .../tests/execution/GcnTessellation.cpp | 2 ++ .../Optimization/src/TessellationLowering.cpp | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp index 3e19733b9cb1..08a82f168f3e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnTessellation.cpp @@ -390,6 +390,8 @@ int main() { ExpectConstantsRequired(target, ShaderStage::TessellationEvaluation, GcnDomainOnChipInputs, domainUsers, 0u); const auto outputDomainUsers = ConstantBuffer(OutputConstants); ExpectRefusal(target, ShaderStage::TessellationEvaluation, GcnDomainOnChipBelowOutputs, "at a computed offset that can fall below the hull shader's on-chip output control points", outputDomainUsers, OutputConstants); + ExpectRefusal(target, ShaderStage::TessellationControl, GcnHullOnChipComputedOutputRead, "a pass-through hull shader on chip reads LDS after it may have written it there", hullUsers, PassthroughConstants); + RequirePatches(*device, GcnHullOnChipOutputs, GcnDomainOnChipInputs, true, "GCN on-chip pass-through LS-HS-VS draw whose hull reads its input control points before it writes them", PassthroughConstants); auto narrowOutputs = target; narrowOutputs.tessellation->maxControlPerVertexOutputComponents = 2u; ExpectRefusal(narrowOutputs, ShaderStage::TessellationControl, GcnHullOnChipPassthrough, "the pass-through hull shader's control points exceed the device limits (4 input and 4 output components per control point", hullUsers, PassthroughConstants); diff --git a/core/shader/recompiler/Optimization/src/TessellationLowering.cpp b/core/shader/recompiler/Optimization/src/TessellationLowering.cpp index 8144e86ecc23..ab081d80b8b5 100644 --- a/core/shader/recompiler/Optimization/src/TessellationLowering.cpp +++ b/core/shader/recompiler/Optimization/src/TessellationLowering.cpp @@ -876,6 +876,7 @@ class Lowering { collect(); derive(); if (passthrough) requirePassthroughLimits(); + if (passthrough) requirePassthroughReadsBeforeWrites(); orderControlOutputReads(); for (const auto& access : accesses) rewrite(access); if (passthrough) copyInputControlPoints(); @@ -1540,6 +1541,23 @@ class Lowering { } } + void requirePassthroughReadsBeforeWrites() const { + const auto edges = takenEdges(); + for (const auto& write : accesses) { + if (!write.write || (write.kind != TessellationAttribute::ControlOutput && write.kind != TessellationAttribute::PatchOutput)) continue; + const auto after = reachedFrom(edges, edges.at(write.block), nullptr); + for (const auto& read : accesses) { + if (read.write || read.kind != TessellationAttribute::ControlInput) continue; + bool follows = after.contains(read.block); + if (read.block == write.block) { + const auto& instructions = write.block->Instructions(); + follows = follows || std::find(std::find(instructions.begin(), instructions.end(), write.inst), instructions.end(), read.inst) != instructions.end(); + } + if (follows) Fail("a pass-through hull shader on chip reads LDS after it may have written it there, and its reads are served from the input control points", read.pc); + } + } + } + void requirePassthroughLimits() const { if (limits == nullptr) Fail("the target has no tessellation limits for a pass-through hull shader on chip", 0u); const auto input = 4u * ((localStride + 15u) / 16u); From e80c70c01b83ecb1df1afb385ca127f8f4536636 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:12:02 -0500 Subject: [PATCH 26/34] docs(debt): record the on-chip tessellation refusals and the copy-less hull gap Co-Authored-By: Claude Opus 5.5 --- docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md b/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md index 2de1b17f0d02..0b38ec7d0911 100644 --- a/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md +++ b/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md @@ -2,7 +2,7 @@ ## add Functional -- [PS4 (GCN) on-chip tessellation](../../../core/shader/recompiler/Optimization/src/TessellationLowering.cpp) (shader recompiler, PS4) - not measured on a console. The tessellation constant buffer (shadPS4 `TessellationDataConstantBuffer`) is read from guest memory for every on-chip draw and compiled into its hull and domain stages, so those draws are kept in no draw cache or recipe. With `OC_LDS_EN` clear, hull LDS writes and domain LDS reads at or above `hs_output_base` go through the off-chip ring lowering at that offset less `hs_output_base`. A hull with `hs_output_base` 0 is taken as pass-through and copies `ls_stride` bytes of its input control point to its output; one with another output stride or control point count throws, as does an on-chip LDS address that reads another constant buffer or none. LS, HS and VS-stage domain routing (0x45, 0x145) uses the off-chip ring lowering. +- [PS4 (GCN) on-chip tessellation](../../../core/shader/recompiler/Optimization/src/TessellationLowering.cpp) (shader recompiler, PS4) - not measured on a console. The tessellation constant buffer (shadPS4 `TessellationDataConstantBuffer`) is read from guest memory for every on-chip draw and compiled into its hull and domain stages, so those draws are kept in no draw cache or recipe. With `OC_LDS_EN` clear, hull LDS writes and domain LDS reads at or above `hs_output_base` go through the off-chip ring lowering at that offset less `hs_output_base`. A hull with `hs_output_base` 0 is taken as pass-through and copies `ls_stride` bytes of its input control point to its output; one with another output stride or control point count throws, as does an on-chip LDS address that reads another constant buffer or none. LS, HS and VS-stage domain routing (0x45, 0x145) uses the off-chip ring lowering. A pass-through hull that reads LDS after it may have written it there, an on-chip LDS address whose run-time term can be negative, and a pass-through control point that needs more per-vertex components than the device allows also throw. A hull with no LDS access reads no constant buffer, so it is not known to be pass-through and copies nothing to its outputs: a domain shader that then reads its control points from LDS at `hs_output_base` 0 reads unwritten hull outputs, and this is not detected. # libSceAgcDriver From 66a4b647e7988a2571648717df32b32c7b22d700 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:52:09 -0500 Subject: [PATCH 27/34] fix(agc): decode vertex stages with each program's hidden user words The vertex-stage decoders took 8 - firstUserSgpr as the hidden word count, which only matches the merged layout; a GCN program, with its first user SGPR at 0 and no hidden words, had its buffer and attribute table SGPRs shifted by 8. All four decode sites now use the stored hidden word count. The draw key also covers all 32 local-stage user data words that a 32-word RSRC2 count can read (0x14c-0x16b). Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp | 6 +++--- .../Execution/src/Driver/Shaders/ShaderRegistry.cpp | 2 +- core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp | 2 +- core/libs/prx/libSceAgcDriver/tests/RegisterKey.cpp | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp index 07132cf7e1e1..c184e0833348 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/Draw.cpp @@ -639,7 +639,7 @@ DrawVerdict Driver::draw(QueueState& queue, std::span packe const auto decodeVertexInfo = [&](std::size_t i) { const auto& program = programs[i]; if (program.binary.stage == Stage::Fragment || roles[i] == Role::GeometryBack) return; - vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, decodeReads[i], 8u - program.firstUserSgpr); + vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, decodeReads[i], program.hiddenUserWords); if (vertexInfos[i]) { vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, readRegister(queue.context, 0x207), program.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode; @@ -901,7 +901,7 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) { const auto& program = programs[i]; if (program.binary.stage == Stage::Fragment || roles[i] == Role::GeometryBack) return; decodeReads[i].clear(); - vertexInfos[i] = Graphics::DecodeVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, &decodeReads[i], false, 8u - program.firstUserSgpr); + vertexInfos[i] = Graphics::DecodeVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, &decodeReads[i], false, program.hiddenUserWords); if (vertexInfos[i]) { vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, tail.reg207, program.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode; @@ -1521,7 +1521,7 @@ void Driver::restartFinishedDraw(DrawTail& tail) { tail.vertexInfos[i].reset(); const auto& program = programs[i]; if (program.binary.stage == Stage::Fragment || roles[i] == Role::GeometryBack) continue; - tail.vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, tail.decodeReads[i], 8u - program.firstUserSgpr); + tail.vertexInfos[i] = DecodeOrderedVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, tail.decodeReads[i], program.hiddenUserWords); if (!tail.vertexInfos[i]) continue; tail.vertexInfos[i]->paClVsOutCntl = PositionExportLayout(program.snapshot.get(), program.codeOffset, program.binary.code, tail.reg207, program.tailContinuation.get()) | graphics.layerExports | graphics.viewportExports; tail.vertexInfos[i]->depthRemapMode = graphics.depthRemap.mode; diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp index 0f4cbee42bf5..6c3e305d798b 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp @@ -2693,7 +2693,7 @@ std::vector PrepareGraphicsStages(const DrawDecode& decod } std::optional vertex; try { - if (!fragment) vertex = Graphics::DecodeVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, nullptr, true, 8u - program.firstUserSgpr); + if (!fragment) vertex = Graphics::DecodeVertexStageInfo(program.binary.header, program.binary.headerAddress, program.userData, nullptr, true, program.hiddenUserWords); } catch (const std::exception& error) { if (!deferUnprepared) throw; DeferPipelineStage(transaction.Edit(*program.snapshot), *program.snapshot, error.what()); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp index d2ddde5b2ca6..e7530b332622 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/State.hpp @@ -396,7 +396,7 @@ inline constexpr std::array DrawKeyRegisters{{ // The pixel program address, RSRC2 and user words; the geometry-back user pointer and program // address; the vertex/geometry-front RSRC1/RSRC2 and user words; the vertex program address; // the hull user pointer, program address, RSRC2 and user words; the local program address. - {RegisterBank::Shader, 0x008, 0x24}, {RegisterBank::Shader, 0x048, 0x14}, {RegisterBank::Shader, 0x082, 2}, {RegisterBank::Shader, 0x088, 2}, {RegisterBank::Shader, 0x08a, 0x22}, {RegisterBank::Shader, 0x0c8, 2}, {RegisterBank::Shader, 0x102, 2}, {RegisterBank::Shader, 0x108, 2}, {RegisterBank::Shader, 0x10b, 0x21}, {RegisterBank::Shader, 0x148, 0x14}, + {RegisterBank::Shader, 0x008, 0x24}, {RegisterBank::Shader, 0x048, 0x14}, {RegisterBank::Shader, 0x082, 2}, {RegisterBank::Shader, 0x088, 2}, {RegisterBank::Shader, 0x08a, 0x22}, {RegisterBank::Shader, 0x0c8, 2}, {RegisterBank::Shader, 0x102, 2}, {RegisterBank::Shader, 0x108, 2}, {RegisterBank::Shader, 0x10b, 0x21}, {RegisterBank::Shader, 0x148, 0x24}, // GE_PRIM_TYPE, GE_MULTI_PRIM_IB_RESET_EN, the geometry subgroup sizes. {RegisterBank::UserConfig, 0x242, 1}, {RegisterBank::UserConfig, 0x24b, 1}, {RegisterBank::UserConfig, 0x25b, 1}, }}; diff --git a/core/libs/prx/libSceAgcDriver/tests/RegisterKey.cpp b/core/libs/prx/libSceAgcDriver/tests/RegisterKey.cpp index 72f709012d51..d9b5625d9ea0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/RegisterKey.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/RegisterKey.cpp @@ -68,8 +68,8 @@ void testFingerprints() { check(RegisterStateKey(queue, false, true, nullptr, &parts) != beforeRuntimeKey, "runtime-register mutation did not change the key"); check(parts.userDataRegisters != beforeRuntimeMutation.userDataRegisters && parts.auxiliaryRegisters == beforeRuntimeMutation.auxiliaryRegisters && parts.stableRegisters == beforeRuntimeMutation.stableRegisters, "user-data register change was not isolated"); queue = QueueState{}; - queue.shader[0x14b] = 2u << 1u; - for (std::uint32_t offset = 0x14cu; offset < 0x15cu; ++offset) { + queue.shader[0x14b] = 0x1fu << 1u | 1u << 27u; + for (std::uint32_t offset = 0x14cu; offset < 0x16cu; ++offset) { const auto beforeLocalKey = RegisterStateKey(queue, false, true, nullptr, &parts); const auto beforeLocal = parts; queue.shader[offset] = offset; From 58c5304937a3e2ffaa16c830d031ecc2695b76e9 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:55:52 -0500 Subject: [PATCH 28/34] docs(debt): shorten the on-chip tessellation entry and note the copy-less hull gap Co-Authored-By: Claude Opus 5.5 --- docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md b/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md index 0b38ec7d0911..0f5175b7e0a2 100644 --- a/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md +++ b/docs/dev/debt/changes/claude-gcn-ls-hs-vs-tessellation.md @@ -2,7 +2,7 @@ ## add Functional -- [PS4 (GCN) on-chip tessellation](../../../core/shader/recompiler/Optimization/src/TessellationLowering.cpp) (shader recompiler, PS4) - not measured on a console. The tessellation constant buffer (shadPS4 `TessellationDataConstantBuffer`) is read from guest memory for every on-chip draw and compiled into its hull and domain stages, so those draws are kept in no draw cache or recipe. With `OC_LDS_EN` clear, hull LDS writes and domain LDS reads at or above `hs_output_base` go through the off-chip ring lowering at that offset less `hs_output_base`. A hull with `hs_output_base` 0 is taken as pass-through and copies `ls_stride` bytes of its input control point to its output; one with another output stride or control point count throws, as does an on-chip LDS address that reads another constant buffer or none. LS, HS and VS-stage domain routing (0x45, 0x145) uses the off-chip ring lowering. A pass-through hull that reads LDS after it may have written it there, an on-chip LDS address whose run-time term can be negative, and a pass-through control point that needs more per-vertex components than the device allows also throw. A hull with no LDS access reads no constant buffer, so it is not known to be pass-through and copies nothing to its outputs: a domain shader that then reads its control points from LDS at `hs_output_base` 0 reads unwritten hull outputs, and this is not detected. +- [PS4 (GCN) on-chip tessellation](../../../core/shader/recompiler/Optimization/src/TessellationLowering.cpp) (shader recompiler, PS4) - not measured on a console. On-chip draws compile the title's tessellation constant buffer into their hull and domain stages and skip the draw caches. With `OC_LDS_EN` clear, hull LDS writes and domain LDS reads at or above `hs_output_base` go through the off-chip ring lowering at that offset less `hs_output_base`. A hull with `hs_output_base` 0 is taken as pass-through and copies `ls_stride` bytes of its input control point to its output; one with another output stride or control point count throws, as does an on-chip LDS address that reads another constant buffer or none. Routing 0x45 and 0x145 uses the off-chip ring lowering. Not detected: a hull with no LDS access copies nothing, so a domain shader reading control points at `hs_output_base` 0 reads unwritten outputs. # libSceAgcDriver From 8dd935bb29f991add1863b6303624f6b4838d8b8 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:56:52 -0500 Subject: [PATCH 29/34] fix(agc): capture the pinned tessellation constants with the draw's memory The on-chip tessellation constants were read with GuestMemory::Read, so the words a hull or domain stage was compiled from were not among the captured regions the draw checks again before it commits. Read them through the draw's ShaderMemory instead, so a change to those words restarts the draw and a recorded GPU write to them is waited for like any other captured read. Co-Authored-By: Claude Opus 5.5 --- .../Execution/include/ShaderMemory.hpp | 1 + .../Execution/src/Driver/Draw/DrawCapture.cpp | 14 +++++++------- .../prx/libSceAgcDriver/tests/ShaderMemory.cpp | 16 ++++++++++++++++ 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp index 9864a554f80e..c14f9a8f80b3 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/ShaderMemory.hpp @@ -78,6 +78,7 @@ class ShaderMemory { // included, the initial regions excluded: one stage's own reads on the draw path's shared // ShaderMemory (Regions() stays the union). The spans point into the pages, as Regions()'s do. [[nodiscard]] std::vector TakeRecentRegions(); + [[nodiscard]] bool ReadWords(std::uint64_t address, std::span values) { return readWords(this, address, values.data(), values.size()); } // The driver's source handle memo outcomes, for the [capture] line (APS5_PROFILE_DRAW). static void CountHandleMemo(bool hit); struct SupplyCounts { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp index 77c153b314ea..736ee11efd0c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawCapture.cpp @@ -25,16 +25,16 @@ namespace AgcDriver::DriverDetail { namespace { -std::array ReadTessellationConstants(std::span userData, std::uint32_t word) { +std::array ReadTessellationConstants(ShaderMemory& shaderMemory, std::span userData, std::uint32_t word) { require(word + 4u <= userData.size(), "the tessellation constant buffer's V# lies past the stage's user data"); const auto base = static_cast(userData[word]) | (static_cast(userData[word + 1u] & 0xffffu) << 32u); const auto stride = (userData[word + 1u] >> 16u) & 0x3fffu; const auto size = stride == 0u ? static_cast(userData[word + 2u]) : static_cast(stride) * userData[word + 2u]; std::array constants{}; - for (std::uint32_t index = 0; index < constants.size(); ++index) { - if (4u * index + 4u > size) break; - GuestMemory::Read(base + 4u * index, std::as_writable_bytes(std::span(&constants[index], 1u)), 4u); - } + const auto count = static_cast(std::min(constants.size(), size / 4u)); + if (count == 0u) return constants; + require(base % 4u == 0u, "the tessellation constant buffer starts at an address that is not a whole dword"); + require(shaderMemory.ReadWords(base, std::span(constants).first(count)), "the tessellation constant buffer could not be read"); return constants; } @@ -214,12 +214,12 @@ std::shared_ptr Driver::materializeDraw ShaderRecompiler::GraphicsCompileContext{program.firstUserSgpr, linked, Graphics::StageMeshConfiguration(graphics.stages, program.binary.stage), graphics.stages.tessellation, {drawParameters.indexAddress, drawParameters.indexCount, drawParameters.indexSize, drawParameters.instanceCount}, program.binary.stage == Stage::Mesh ? meshBarycentrics : std::nullopt, emulateBarycentrics && program.binary.stage == Stage::Fragment} }; if (request.graphics->tessellation && request.graphics->tessellation->onChip && (program.binary.stage == Stage::TessellationControl || program.binary.stage == Stage::TessellationEvaluation)) { - if (const auto word = TessellationConstantWord(*program.snapshot, program.codeOffset)) request.graphics->tessellationConstants = ReadTessellationConstants(program.userData, *word); + if (const auto word = TessellationConstantWord(*program.snapshot, program.codeOffset)) request.graphics->tessellationConstants = ReadTessellationConstants(shaderMemory, program.userData, *word); } const auto pinTessellationConstants = [&](const ShaderRecompiler::TessellationConstantsRequired& required) { if (request.graphics->tessellationConstants) throw required; RecordTessellationConstantWord(*program.snapshot, program.codeOffset, required.UserDataWord()); - request.graphics->tessellationConstants = ReadTessellationConstants(program.userData, required.UserDataWord()); + request.graphics->tessellationConstants = ReadTessellationConstants(shaderMemory, program.userData, required.UserDataWord()); }; const auto waitedBefore = traceCapSync() || profile ? Graphics::Recorder::ThreadWaitedMs() : 0.0; auto invocation = [&] { diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index d87d0b2fcbe0..a6a5237b1896 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -13737,6 +13737,21 @@ void verifyTableKeep() { } } +void verifyReadWordsRegions() { + alignas(4096) static std::array words{}; + for (std::size_t index = 0; index < words.size(); ++index) words[index] = static_cast(0x9e3779b9u * (index + 1u)); + AgcDriver::ShaderMemory memory({}); + std::array values{}; + const auto first = words.data() + 1022; + require(memory.ReadWords(reinterpret_cast(first), values), "ReadWords failed on readable guest words"); + require(std::equal(values.begin(), values.end(), first), "ReadWords returned other words than guest memory holds"); + const auto recent = memory.TakeRecentRegions(); + require(TableCovered(recent, first, sizeof(values)), "words read with ReadWords are missing from the recent regions"); + require(!TableCovered(recent, words.data(), sizeof(std::uint32_t)) && !TableCovered(recent, first + values.size(), sizeof(std::uint32_t)), "the recent regions list words ReadWords did not read"); + require(TableCovered(memory.Regions(), first, sizeof(values)), "words read with ReadWords are missing from the capture's regions"); + require(memory.TakeRecentRegions().empty(), "ReadWords left recent regions after they were taken"); +} + int main(int argc, char** argv) { try { #ifdef _WIN32 @@ -14341,6 +14356,7 @@ int main(int argc, char** argv) { require(Recompile(request, *nullRootCapture)->poisonedSrtReads >= nullRootCapture->snapshot.nullRootReads, "a capture through a null user-data pointer is cacheable"); verifyAllocationChurnSnapshot(); verifySnapshotAllocationMoves(); + verifyReadWordsRegions(); std::cout << "Shader memory capture, strict validation and deterministic replay passed\n"; return 0; } catch (const std::exception& error) { From bbafa86a1097624ca51eec211b1cad3e850da4b3 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:41:38 -0500 Subject: [PATCH 30/34] fix(geometry): refuse copy-program memory accesses other than GSVS reads ParseGeometryCopyProgram dropped any buffer, flat, LDS or image access other than the GSVS ring read, so a copy program store (for example a stream-out write) parsed without error and never ran. It now throws. Co-Authored-By: Claude Opus 5.5 --- .../prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp | 6 +++++- .../shader/recompiler/Optimization/src/GeometryLowering.cpp | 1 + docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index c7450ee4be8e..39f7262c0e59 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -96,6 +96,10 @@ alignas(256) constexpr std::array GcnCopyAliasedLoad{ 0x34020082, 0xe0305000, 0x80400101, 0xbf8c0000, 0xf80008cf, 0x01010101, 0xbf810000, }; +alignas(256) constexpr std::array GcnCopyStore{ + 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xe0705000, 0x80400201, 0xbf810000, +}; + alignas(256) constexpr std::array GcnCopyComputed{ 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0x060604f2, 0xf80008cf, 0x02020302, 0xbf810000, }; @@ -282,7 +286,7 @@ void RequireCopyLayout() { refused = std::string(error.what()).find("a copy program branch on a condition not known at draw time") != std::string::npos; } Require(refused, "a copy program branch on the stream ID was followed without the stream-out configuration SGPR"); - for (const auto& [code, reason] : {std::pair{std::span(GcnCopyBranch), "control flow other than a scalar condition in a copy program"}, std::pair{std::span(GcnCopyExec), "a copy program that writes EXEC"}, std::pair{std::span(GcnCopyMovedIndex), "not addressed by the vertex index times 4"}}) { + for (const auto& [code, reason] : {std::pair{std::span(GcnCopyBranch), "control flow other than a scalar condition in a copy program"}, std::pair{std::span(GcnCopyExec), "a copy program that writes EXEC"}, std::pair{std::span(GcnCopyMovedIndex), "not addressed by the vertex index times 4"}, std::pair{std::span(GcnCopyStore), "a memory access other than a GSVS ring read in a copy program"}}) { refused = false; try { static_cast(ShaderRecompiler::ParseGeometryCopyProgram(code, 4u, 5u, std::nullopt)); diff --git a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp index e0b1b7238ffa..acff6ae46fcf 100644 --- a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp +++ b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp @@ -455,6 +455,7 @@ std::vector ParseGeometryCopyProgram(std::span Date: Fri, 27 Nov 2026 22:08:03 -0500 Subject: [PATCH 31/34] test(geometry): catch duplicated quads and twisted strips in the GCN draw The pixel check drew opaque quads and sampled their centres, so a primitive drawn twice or a strip emitted in the wrong vertex order still passed. The draw now adds each quad at a quarter of its colour over the clear colour and samples five points per quad. Co-Authored-By: Claude Opus 5.5 --- .../tests/execution/GcnGeometry.cpp | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index 39f7262c0e59..489b3bd30183 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include namespace { @@ -230,15 +231,24 @@ void RequireQuads(AgcDriver::VulkanDevice& device) { state.scissor = {{0, 0}, {Width, Height}}; state.cullMode = VK_CULL_MODE_NONE; state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; + state.blend.blendEnable = VK_TRUE; + state.blend.srcColorBlendFactor = VK_BLEND_FACTOR_CONSTANT_COLOR; + state.blend.dstColorBlendFactor = VK_BLEND_FACTOR_ONE; + state.blend.colorBlendOp = VK_BLEND_OP_ADD; + state.blend.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; + state.blend.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + state.blend.alphaBlendOp = VK_BLEND_OP_ADD; state.blend.colorWriteMask = 15; state.blends = {state.blend}; - state.blendConstants = {}; + state.blendConstants = {0.25f, 0.25f, 0.25f, 0.25f}; device.Draw(state, {reinterpret_cast(Indices.data()), static_cast(Indices.size()), 2, 1, 0, true, 0, 0}, shaders); device.WaitIdle(); - const auto first = PixelAt(-0.5f, 0.0f); - Require(first == std::array{255u, 0u, 0u, 255u}, "the first point's quad is " + PixelText(first) + ", expected (255, 0, 0, 255)"); - const auto second = PixelAt(0.5f, 0.0f); - Require(second[0] >= 127u && second[0] <= 128u && second[1] == 0u && second[2] == 0u && second[3] == 255u, "the second point's quad is " + PixelText(second) + ", expected half red"); + for (const auto [centre, red, name] : {std::tuple{-0.5f, 80u, "first"}, std::tuple{0.5f, 48u, "second"}}) { + for (const auto [dx, dy] : {std::pair{0.0f, 0.0f}, std::pair{-0.15f, 0.0f}, std::pair{0.15f, 0.0f}, std::pair{0.0f, -0.15f}, std::pair{0.0f, 0.15f}}) { + const auto pixel = PixelAt(centre + dx, dy); + Require(pixel[0] + 1u >= red && pixel[0] <= red + 1u && pixel[1] == Background[1] && pixel[2] == Background[2] && pixel[3] == 255u, std::string("the ") + name + " point's quad at (" + std::to_string(centre + dx) + ", " + std::to_string(dy) + ") is " + PixelText(pixel) + ", expected red " + std::to_string(red) + " from one quarter-weight quad over the clear colour: a missing or duplicated primitive, or a strip in the wrong vertex order"); + } + } for (const auto [x, y] : {std::pair{0.0f, 0.0f}, std::pair{-0.5f, 0.4f}, std::pair{0.5f, -0.4f}, std::pair{-0.9f, 0.0f}}) { const auto outside = PixelAt(x, y); Require(outside == Background, "a pixel outside both quads at (" + std::to_string(x) + ", " + std::to_string(y) + ") is " + PixelText(outside)); From 1e7436042b4dda8ee1c19143cf09642bc8d9ead9 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:19:20 -0500 Subject: [PATCH 32/34] fix(geometry): bound address evaluation and refuse unproven GSVS copy reads Evaluate walked both operands of every node before checking either, so a shared chain such as a[n+1] = a[n] - a[n] cost 2^n calls and could stall compilation. It now remembers each solved term and stops at the first operand it cannot solve. The copy-program parser read every buffer_load_dword as a GSVS ring read. It now throws on a read into LDS, and on reads through two descriptors or after the descriptor SGPRs are rewritten. Co-Authored-By: Claude Opus 5.5 --- .../tests/GeometryLowering.cpp | 88 +++++++++++++++++ .../cmake/agc_geometry_lowering_tests.cmake | 14 +++ .../tests/execution/GcnGeometry.cpp | 14 ++- .../Optimization/src/GeometryLowering.cpp | 98 +++++++++++-------- .../debt/changes/claude-gcn-es-gs-copy-vs.md | 2 + 5 files changed, 176 insertions(+), 40 deletions(-) create mode 100644 core/libs/prx/libSceAgcDriver/tests/GeometryLowering.cpp create mode 100644 core/libs/prx/libSceAgcDriver/tests/cmake/agc_geometry_lowering_tests.cmake diff --git a/core/libs/prx/libSceAgcDriver/tests/GeometryLowering.cpp b/core/libs/prx/libSceAgcDriver/tests/GeometryLowering.cpp new file mode 100644 index 000000000000..ec30a1e517cb --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/GeometryLowering.cpp @@ -0,0 +1,88 @@ +#include "IntermediateRepresentation/IrBuilder.hpp" +#include "IntermediateRepresentation/IrProgram.hpp" +#include "Optimization/GeometryLowering.hpp" +#include "Optimization/ShaderStageInputInfo.hpp" +#include +#include +#include +#include +#include + +using namespace ShaderRecompiler; + +namespace { + +constexpr std::uint32_t RingMemory = 0u; +constexpr std::uint32_t OutputMemory = 1u; +constexpr std::uint32_t SharedSubtractions = 31u; + +void Require(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +struct Geometry { + IrProgram program; + IrBuilder builder{program}; + + Geometry() { + program.Resources().stage = IrShaderStage::Geometry; + program.Resources().memoryInfo.push_back(MemoryInfo{.kind = ResourceKind::Buffer, .offen = true}); + program.Resources().memoryInfo.push_back(MemoryInfo{.kind = ResourceKind::Buffer}); + auto& block = program.CreateBlock(); + program.BlockOrder().push_back(&block); + BlockInfo info; + info.id = block.Id(); + program.Metadata().blockInfo.push_back(info); + program.SetEntryBlock(block); + builder.SetInsertionPoint(block); + } + + IrValue& resource() { + return builder.Emit(IrOpcode::GetBufferResource, IrType::BufferResource, {&builder.Constant(0u), &builder.Constant(0u), &builder.Constant(0u), &builder.Constant(0u)}); + } +}; + +ShaderGeometryInputInfo Points() { + ShaderGeometryInputInfo geometry; + geometry.active = true; + geometry.inputVertices = 1u; + geometry.outputTopology = 2u; + geometry.maxVertices = 4u; + geometry.esgsItemDwords = 2u; + geometry.vertexDwords = 5u; + return geometry; +} + +void RequireSharedAddressTermsEvaluatedOnce() { + Geometry shader; + auto& builder = shader.builder; + auto& vertex = builder.Emit(IrOpcode::TessellationBase, IrType::U32, {&builder.Constant(static_cast(TessellationBaseKind::GeometryVertex))}); + IrValue* zero = &builder.Constant(8u); + for (std::uint32_t i = 0; i < SharedSubtractions; ++i) zero = &builder.Emit(IrOpcode::ISub32, IrType::U32, {zero, zero}); + auto& scaled = builder.Emit(IrOpcode::IMul32, IrType::U32, {&vertex, &builder.Constant(4u)}); + auto& offset = builder.Emit(IrOpcode::IAdd32, IrType::U32, {&scaled, zero}); + auto& loaded = builder.Emit(IrOpcode::LoadBufferU32, IrType::U32, {&shader.resource(), &builder.Constant(0u), &offset, &builder.Constant(256u), &builder.ConstantBool(true)}, MemoryFlags{RingMemory, 0x40u}); + static_cast(builder.Emit(IrOpcode::StoreBufferU32, IrType::Void, {&shader.resource(), &builder.Constant(0u), &builder.Constant(0u), &builder.Constant(0u), &loaded, &builder.ConstantBool(true)}, MemoryFlags{OutputMemory, 0x48u})); + GeometryLowering{}.Lower(shader.program, Points()); + const IrValue* read = nullptr; + for (IrBlock* block : shader.program.BlockOrder()) { + for (IrValue* inst : block->Instructions()) { + if (inst->Opcode() == IrOpcode::GetTessellationAttribute) read = inst; + Require(inst->Opcode() != IrOpcode::LoadBufferU32, "the ESGS ring read was left as a buffer load"); + } + } + Require(read != nullptr && read->Argument(0)->Resolve()->ImmediateU32() == static_cast(TessellationAttribute::GeometryInput) && read->Argument(1)->Resolve()->ImmediateU32() == 4u, "an ESGS ring read at the ES vertex offset times 4 plus 31 shared subtractions of 8 from itself, scalar offset 256, was not lowered to dword 1 of input vertex 0"); +} + +} + +int main() { + try { + RequireSharedAddressTermsEvaluatedOnce(); + std::puts("geometry lowering tests passed"); + return 0; + } catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_geometry_lowering_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_geometry_lowering_tests.cmake new file mode 100644 index 000000000000..6cf0186c289c --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_geometry_lowering_tests.cmake @@ -0,0 +1,14 @@ +add_test_executable(agc_geometry_lowering_tests EXCLUDE_FROM_ALL tests/GeometryLowering.cpp) +target_link_libraries(agc_geometry_lowering_tests PRIVATE shader_recompiler_agc_driver libc) +set_target_properties(agc_geometry_lowering_tests PROPERTIES CXX_EXTENSIONS OFF) +configure_windows_unwind(agc_geometry_lowering_tests) + +if(BUILD_TESTING) + set_target_properties(agc_geometry_lowering_tests PROPERTIES EXCLUDE_FROM_ALL OFF) + add_test(NAME agc_geometry_lowering COMMAND agc_geometry_lowering_tests) + set_tests_properties(agc_geometry_lowering PROPERTIES TIMEOUT 10) + if(WIN32) + set_tests_properties(agc_geometry_lowering PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index 489b3bd30183..c7a43573fa64 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -101,6 +101,18 @@ alignas(256) constexpr std::array GcnCopyStore{ 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xe0705000, 0x80400201, 0xbf810000, }; +alignas(256) constexpr std::array GcnCopyLds{ + 0x34020082, 0xe0315000, 0x80400301, 0xe0305000, 0x80400201, 0xbf8c0000, 0xf80008cf, 0x02020202, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnCopyTwoDescriptors{ + 0x34020082, 0xe0305000, 0x80400201, 0xe0305000, 0x80410301, 0xbf8c0000, 0xf80008cf, 0x02020302, 0xbf810000, +}; + +alignas(256) constexpr std::array GcnCopyDescriptorReloaded{ + 0x34020082, 0xe0305000, 0x80400201, 0xbe800380, 0xe0305000, 0x80400301, 0xbf8c0000, 0xf80008cf, 0x02020302, 0xbf810000, +}; + alignas(256) constexpr std::array GcnCopyComputed{ 0x34020082, 0xe0305000, 0x80400201, 0xbf8c0000, 0x060604f2, 0xf80008cf, 0x02020302, 0xbf810000, }; @@ -296,7 +308,7 @@ void RequireCopyLayout() { refused = std::string(error.what()).find("a copy program branch on a condition not known at draw time") != std::string::npos; } Require(refused, "a copy program branch on the stream ID was followed without the stream-out configuration SGPR"); - for (const auto& [code, reason] : {std::pair{std::span(GcnCopyBranch), "control flow other than a scalar condition in a copy program"}, std::pair{std::span(GcnCopyExec), "a copy program that writes EXEC"}, std::pair{std::span(GcnCopyMovedIndex), "not addressed by the vertex index times 4"}, std::pair{std::span(GcnCopyStore), "a memory access other than a GSVS ring read in a copy program"}}) { + for (const auto& [code, reason] : {std::pair{std::span(GcnCopyBranch), "control flow other than a scalar condition in a copy program"}, std::pair{std::span(GcnCopyExec), "a copy program that writes EXEC"}, std::pair{std::span(GcnCopyMovedIndex), "not addressed by the vertex index times 4"}, std::pair{std::span(GcnCopyStore), "a memory access other than a GSVS ring read in a copy program"}, std::pair{std::span(GcnCopyLds), "a GSVS ring read into LDS"}, std::pair{std::span(GcnCopyTwoDescriptors), "GSVS ring reads through more than one buffer descriptor"}, std::pair{std::span(GcnCopyDescriptorReloaded), "GSVS ring reads through more than one buffer descriptor"}}) { refused = false; try { static_cast(ShaderRecompiler::ParseGeometryCopyProgram(code, 4u, 5u, std::nullopt)); diff --git a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp index acff6ae46fcf..9612af610ed6 100644 --- a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp +++ b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace ShaderRecompiler { @@ -60,53 +61,64 @@ struct Term { std::int64_t constant = 0; }; -std::optional Evaluate(const IrValue* raw, std::uint32_t depth = 0u) { +std::optional Evaluate(const IrValue* raw, std::unordered_map& known, std::uint32_t depth) { if (depth > 32u) return std::nullopt; const IrValue* value = raw->Resolve(); if (value->HasImmediate()) return Term{std::nullopt, 0, static_cast(value->ImmediateU32())}; if (const auto vertex = GeometryVertexOf(value)) return Term{vertex, 1, 0}; + if (const auto found = known.find(value); found != known.end()) return found->second; const auto pair = [&]() -> std::optional> { if (value->ArgumentCount() < 2u) return std::nullopt; - const auto left = Evaluate(value->Argument(0), depth + 1u); - const auto right = Evaluate(value->Argument(1), depth + 1u); - if (!left || !right) return std::nullopt; + const auto left = Evaluate(value->Argument(0), known, depth + 1u); + if (!left) return std::nullopt; + const auto right = Evaluate(value->Argument(1), known, depth + 1u); + if (!right) return std::nullopt; return std::pair{*left, *right}; }; - switch (value->Opcode()) { - case IrOpcode::IAdd32: { - const auto terms = pair(); - if (!terms || (terms->first.vertex && terms->second.vertex)) return std::nullopt; - Term sum{terms->first.vertex ? terms->first.vertex : terms->second.vertex}; - if (__builtin_add_overflow(terms->first.scale, terms->second.scale, &sum.scale) || __builtin_add_overflow(terms->first.constant, terms->second.constant, &sum.constant)) return std::nullopt; - return sum; - } - case IrOpcode::ISub32: { - const auto terms = pair(); - if (!terms || terms->second.vertex) return std::nullopt; - Term difference{terms->first.vertex, terms->first.scale}; - if (__builtin_sub_overflow(terms->first.constant, terms->second.constant, &difference.constant)) return std::nullopt; - return difference; - } - case IrOpcode::ShiftLeftLogical32: { - const auto terms = pair(); - if (!terms || terms->second.vertex || terms->second.constant < 0 || terms->second.constant > 31) return std::nullopt; - const auto factor = std::int64_t{1} << terms->second.constant; - Term shifted{terms->first.vertex}; - if (__builtin_mul_overflow(terms->first.scale, factor, &shifted.scale) || __builtin_mul_overflow(terms->first.constant, factor, &shifted.constant)) return std::nullopt; - return shifted; - } - case IrOpcode::IMul32: { - const auto terms = pair(); - if (!terms || (terms->first.vertex && terms->second.vertex)) return std::nullopt; - const auto& varying = terms->first.vertex ? terms->first : terms->second; - const auto& factor = terms->first.vertex ? terms->second : terms->first; - Term product{varying.vertex}; - if (__builtin_mul_overflow(varying.scale, factor.constant, &product.scale) || __builtin_mul_overflow(varying.constant, factor.constant, &product.constant)) return std::nullopt; - return product; - } - default: - return std::nullopt; - } + const auto term = [&]() -> std::optional { + switch (value->Opcode()) { + case IrOpcode::IAdd32: { + const auto terms = pair(); + if (!terms || (terms->first.vertex && terms->second.vertex)) return std::nullopt; + Term sum{terms->first.vertex ? terms->first.vertex : terms->second.vertex}; + if (__builtin_add_overflow(terms->first.scale, terms->second.scale, &sum.scale) || __builtin_add_overflow(terms->first.constant, terms->second.constant, &sum.constant)) return std::nullopt; + return sum; + } + case IrOpcode::ISub32: { + const auto terms = pair(); + if (!terms || terms->second.vertex) return std::nullopt; + Term difference{terms->first.vertex, terms->first.scale}; + if (__builtin_sub_overflow(terms->first.constant, terms->second.constant, &difference.constant)) return std::nullopt; + return difference; + } + case IrOpcode::ShiftLeftLogical32: { + const auto terms = pair(); + if (!terms || terms->second.vertex || terms->second.constant < 0 || terms->second.constant > 31) return std::nullopt; + const auto factor = std::int64_t{1} << terms->second.constant; + Term shifted{terms->first.vertex}; + if (__builtin_mul_overflow(terms->first.scale, factor, &shifted.scale) || __builtin_mul_overflow(terms->first.constant, factor, &shifted.constant)) return std::nullopt; + return shifted; + } + case IrOpcode::IMul32: { + const auto terms = pair(); + if (!terms || (terms->first.vertex && terms->second.vertex)) return std::nullopt; + const auto& varying = terms->first.vertex ? terms->first : terms->second; + const auto& factor = terms->first.vertex ? terms->second : terms->first; + Term product{varying.vertex}; + if (__builtin_mul_overflow(varying.scale, factor.constant, &product.scale) || __builtin_mul_overflow(varying.constant, factor.constant, &product.constant)) return std::nullopt; + return product; + } + default: + return std::nullopt; + } + }(); + if (term) known.emplace(value, *term); + return term; +} + +std::optional Evaluate(const IrValue* raw) { + std::unordered_map known; + return Evaluate(raw, known, 0u); } ExportTargetKind CopyTargetKind(std::uint32_t target, std::uint32_t& index) { @@ -368,6 +380,8 @@ std::vector ParseGeometryCopyProgram(std::span scc; std::optional skipTo; + std::optional ringDescriptor; + bool ringDescriptorWritten = false; std::vector exports; const auto slotBytes = maxVertices * GsVsVertexBytes; for (const auto& instruction : program.instructions) { @@ -393,6 +407,8 @@ std::vector ParseGeometryCopyProgram(std::spankind == RdnaOperandKind::ExecLo || destination->kind == RdnaOperandKind::ExecHi) FailCopy("a copy program that writes EXEC", pc); + const auto count = std::max(instruction.dataDwordCount, 1u) + (instruction.is64Bit ? 1u : 0u); + if (ringDescriptor && destination->kind == RdnaOperandKind::ScalarRegister && destination->reg < *ringDescriptor + 4u && *ringDescriptor < destination->reg + count) ringDescriptorWritten = true; } const bool indexLive = vertexIndex; for (const auto* destination : {&instruction.destination, &instruction.destination2}) { @@ -418,6 +434,10 @@ std::vector ParseGeometryCopyProgram(std::spansecond.vertexOffset; Forget(vectors, scalars, instruction); diff --git a/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md b/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md index ff06fd2ea9ba..7c5c3af10ee8 100644 --- a/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md +++ b/docs/dev/debt/changes/claude-gcn-es-gs-copy-vs.md @@ -4,6 +4,8 @@ - [PS4 (GCN) geometry shaders](../../../core/shader/recompiler/Optimization/src/GeometryLowering.cpp) (shader recompiler, PS4) - not measured on a console. These throw: a copy VS export that is neither a GSVS ring dword nor a constant, copy VS EXEC writes, backward branches, and branches other than on an SCC known at draw time, copy VS GSVS reads not spaced `VGT_GS_MAX_VERT_OUT` times 64 bytes apart, other copy VS memory accesses, ESGS reads of a non-constant input vertex or of more than one dword, ESGS stores at a per-lane address, LDS in the GS, emits to streams 1-3, and GSVS stores at a constant address past `VGT_GS_VERT_ITEMSIZE` times `VGT_GS_MAX_VERT_OUT` dwords. The copy VS's stream-out configuration SGPR (after its user SGPRs when `SPI_SHADER_PGM_RSRC2_VS.SO_EN` is set) is read as 0: stream 0 and no stream-out, the only modeled case. A GSVS store at a computed address past that goes to a spare dword no output reads; on the console it lands in a neighbouring primitive's item. +- [PS4 (GCN) geometry copy VS buffer descriptor](../../../core/shader/recompiler/Optimization/src/GeometryLowering.cpp) (shader recompiler, PS4) - not measured on a console. The copy VS is parsed, not run, and every `buffer_load_dword` it makes is read as a GSVS ring read. The parser does not check that the descriptor is the GSVS ring's: the guest ring table layout is not modeled, and shadPS4's `ParseCopyShader` does not check it either. These throw: reads through two descriptors, a read after the descriptor SGPRs are rewritten, and a read into LDS. A copy VS whose only loads use one other buffer is still read as a GSVS copy. + # libSceAgcDriver ## add Functional From 84c6ee2d4bdcb72d6ef782045218b396779117f3 Mon Sep 17 00:00:00 2001 From: B-Howell <116104752+B-Howell@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:53:19 -0500 Subject: [PATCH 33/34] fix(geometry): compute GSVS ring sizes in 64 bits and refuse ones that wrap GeometryRingDwords checks that VGT_GS_VERT_ITEMSIZE slots of VGT_GS_MAX_VERT_OUT vertices at 64 bytes each fit in 32-bit ring addresses before the copy-program parser, the geometry lowering or the SPIR-V ring array uses them, so a wrapped slot stride can no longer map a copy read to the wrong GSVS dword. Co-Authored-By: Claude Opus 5.5 --- .../tests/GeometryLowering.cpp | 60 +++++++++++++++++++ .../include/Optimization/GeometryLowering.hpp | 3 + .../Optimization/src/GeometryLowering.cpp | 15 ++++- .../SpirvBackend/src/SpirvModuleEmitter.cpp | 5 +- 4 files changed, 78 insertions(+), 5 deletions(-) diff --git a/core/libs/prx/libSceAgcDriver/tests/GeometryLowering.cpp b/core/libs/prx/libSceAgcDriver/tests/GeometryLowering.cpp index ec30a1e517cb..6e5da412bcdb 100644 --- a/core/libs/prx/libSceAgcDriver/tests/GeometryLowering.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/GeometryLowering.cpp @@ -2,11 +2,14 @@ #include "IntermediateRepresentation/IrProgram.hpp" #include "Optimization/GeometryLowering.hpp" #include "Optimization/ShaderStageInputInfo.hpp" +#include "Recompiler.hpp" +#include #include #include #include #include #include +#include using namespace ShaderRecompiler; @@ -15,6 +18,11 @@ namespace { constexpr std::uint32_t RingMemory = 0u; constexpr std::uint32_t OutputMemory = 1u; constexpr std::uint32_t SharedSubtractions = 31u; +constexpr std::uint32_t MaxGeometryVertices = 1024u; +constexpr std::uint32_t MaxVertexDwords = 0x7fffu; +constexpr std::uint32_t WrappingGeometryVertices = 0x4000001u; +constexpr std::array CopySlotOne{0x34020082u, 0xe0305040u, 0x80400201u, 0xbf8c0000u, 0xf80008cfu, 0x02020202u, 0xbf810000u}; +constexpr std::array CopySlotZero{0x34020082u, 0xe0305000u, 0x80400201u, 0xbf8c0000u, 0xf80008cfu, 0x02020202u, 0xbf810000u}; void Require(bool condition, const std::string& message) { if (!condition) throw std::runtime_error(message); @@ -74,11 +82,63 @@ void RequireSharedAddressTermsEvaluatedOnce() { Require(read != nullptr && read->Argument(0)->Resolve()->ImmediateU32() == static_cast(TessellationAttribute::GeometryInput) && read->Argument(1)->Resolve()->ImmediateU32() == 4u, "an ESGS ring read at the ES vertex offset times 4 plus 31 shared subtractions of 8 from itself, scalar offset 256, was not lowered to dword 1 of input vertex 0"); } +template +bool RefusedWith(Function&& function, const std::string& reason) { + try { + function(); + } catch (const std::exception& error) { + return std::string(error.what()).find(reason) != std::string::npos; + } + return false; +} + +ShaderGeometryInputInfo LargestRing() { + auto geometry = Points(); + geometry.maxVertices = MaxGeometryVertices; + geometry.vertexDwords = MaxVertexDwords; + return geometry; +} + +std::vector LowerGsVsStore(const ShaderGeometryInputInfo& geometry, std::uint32_t bytes) { + Geometry shader; + auto& builder = shader.builder; + auto& base = builder.Emit(IrOpcode::TessellationBase, IrType::U32, {&builder.Constant(static_cast(TessellationBaseKind::GsVsOffset))}); + static_cast(builder.Emit(IrOpcode::StoreBufferU32, IrType::Void, {&shader.resource(), &builder.Constant(0u), &builder.Constant(bytes), &base, &builder.Constant(7u), &builder.ConstantBool(true)}, MemoryFlags{RingMemory, 0x50u})); + GeometryLowering{}.Lower(shader.program, geometry); + std::vector addresses; + for (IrBlock* block : shader.program.BlockOrder()) { + for (IrValue* inst : block->Instructions()) { + if (inst->Opcode() == IrOpcode::SetTessellationAttribute && inst->Argument(0)->Resolve()->ImmediateU32() == static_cast(TessellationAttribute::GeometryRing)) addresses.push_back(inst->Argument(1)->Resolve()->ImmediateU32()); + } + } + return addresses; +} + +void RequireLargestRingAddressed() { + const auto lastByte = (MaxGeometryVertices * MaxVertexDwords - 1u) * 4u; + Require(LowerGsVsStore(LargestRing(), lastByte) == std::vector{lastByte}, "a GSVS ring store at the last dword of a 1024-vertex, 32767-dword ring was not lowered to that dword"); + Require(RefusedWith([&] { static_cast(LowerGsVsStore(LargestRing(), lastByte + 4u)); }, "a GSVS ring store outside VGT_GS_VERT_ITEMSIZE times VGT_GS_MAX_VERT_OUT dwords"), "a GSVS ring store one dword past a 1024-vertex, 32767-dword ring was accepted"); + const auto exports = ParseGeometryCopyProgram(CopySlotZero, MaxGeometryVertices, MaxVertexDwords, std::nullopt); + Require(exports.size() == 1u && exports[0].values == std::array{0u, 0u, 0u, 0u}, "a copy program read of slot 0 of a 1024-vertex, 32767-dword ring was not parsed"); + Require(RefusedWith([&] { static_cast(ParseGeometryCopyProgram(CopySlotOne, MaxGeometryVertices, MaxVertexDwords, std::nullopt)); }, "which is not one of the 32767 vertex dwords of 65536 bytes each"), "a copy program read at 64 bytes was accepted for a ring whose slots are 65536 bytes"); +} + +void RequireWrappingRingRefused() { + const std::string reason = "do not fit in 32-bit ring addresses"; + Require(RefusedWith([] { static_cast(ParseGeometryCopyProgram(CopySlotOne, WrappingGeometryVertices, 5u, std::nullopt)); }, reason), "a copy program was parsed for a VGT_GS_MAX_VERT_OUT whose 64-byte slot stride wraps 32 bits"); + auto geometry = Points(); + geometry.maxVertices = WrappingGeometryVertices; + Require(RefusedWith([&] { static_cast(LowerGsVsStore(geometry, 0u)); }, reason), "a geometry program was lowered for a VGT_GS_MAX_VERT_OUT whose ring size wraps 32 bits"); + Require(RefusedWith([] { static_cast(GeometryRingDwords(0xffffffffu, 0xffffffffu)); }, reason), "a geometry ring of 2^32-1 vertices of 2^32-1 dwords was accepted"); +} + } int main() { try { RequireSharedAddressTermsEvaluatedOnce(); + RequireLargestRingAddressed(); + RequireWrappingRingRefused(); std::puts("geometry lowering tests passed"); return 0; } catch (const std::exception& error) { diff --git a/core/shader/recompiler/Optimization/include/Optimization/GeometryLowering.hpp b/core/shader/recompiler/Optimization/include/Optimization/GeometryLowering.hpp index 66990c923583..bca695d10188 100644 --- a/core/shader/recompiler/Optimization/include/Optimization/GeometryLowering.hpp +++ b/core/shader/recompiler/Optimization/include/Optimization/GeometryLowering.hpp @@ -3,6 +3,7 @@ #include "IntermediateRepresentation/IrProgram.hpp" #include "Optimization/ShaderStageInputInfo.hpp" +#include namespace ShaderRecompiler { @@ -11,6 +12,8 @@ class GeometryLowering { void Lower(IrProgram& program, const ShaderGeometryInputInfo& geometry) const; }; +[[nodiscard]] std::uint32_t GeometryRingDwords(std::uint32_t maxVertices, std::uint32_t vertexDwords); + } #endif diff --git a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp index 9612af610ed6..5f797e1531fb 100644 --- a/core/shader/recompiler/Optimization/src/GeometryLowering.cpp +++ b/core/shader/recompiler/Optimization/src/GeometryLowering.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -136,7 +137,7 @@ ExportTargetKind CopyTargetKind(std::uint32_t target, std::uint32_t& index) { class Lowering { public: - Lowering(IrProgram& program, const ShaderGeometryInputInfo& geometry) : program(program), geometry(geometry), stage(program.Resources().stage) {} + Lowering(IrProgram& program, const ShaderGeometryInputInfo& geometry) : program(program), geometry(geometry), stage(program.Resources().stage), ringDwords(GeometryRingDwords(geometry.maxVertices, geometry.vertexDwords)) {} void Run() { if (stage != IrShaderStage::Vertex && stage != IrShaderStage::Geometry) Fail("a geometry configuration reached a stage other than the export or geometry program", 0u); @@ -225,7 +226,7 @@ class Lowering { if (offset) { const auto value = offset->constant + bytes; if (value < 0 || (value & 3) != 0) Fail("an unaligned GSVS ring store", flags.pc); - if (value / 4 >= static_cast(geometry.vertexDwords) * geometry.maxVertices) Fail("a GSVS ring store outside VGT_GS_VERT_ITEMSIZE times VGT_GS_MAX_VERT_OUT dwords", flags.pc); + if (value / 4 >= ringDwords) Fail("a GSVS ring store outside VGT_GS_VERT_ITEMSIZE times VGT_GS_MAX_VERT_OUT dwords", flags.pc); address = &constant(static_cast(value)); } else { address = bytes == 0u ? inst.Argument(2) : &insert(block, inst, IrOpcode::IAdd32, IrType::U32, {inst.Argument(2), &constant(bytes)}); @@ -286,6 +287,7 @@ class Lowering { IrProgram& program; const ShaderGeometryInputInfo& geometry; IrShaderStage stage; + std::uint32_t ringDwords; }; struct CopySource { @@ -367,12 +369,19 @@ void Forget(std::map& vectors, std::map(maxVertices) * GsVsVertexBytes; + if (slotBytes > std::numeric_limits::max() / vertexDwords) throw std::runtime_error("geometry ring: " + std::to_string(vertexDwords) + " vertex dwords of " + std::to_string(maxVertices) + " vertices at " + std::to_string(GsVsVertexBytes) + " bytes each do not fit in 32-bit ring addresses"); + return maxVertices * vertexDwords; +} + void GeometryLowering::Lower(IrProgram& program, const ShaderGeometryInputInfo& geometry) const { Lowering(program, geometry).Run(); } std::vector ParseGeometryCopyProgram(std::span code, std::uint32_t maxVertices, std::uint32_t vertexDwords, std::optional streamConfigSgpr) { - if (maxVertices == 0u || vertexDwords == 0u) throw std::runtime_error("geometry copy program: VGT_GS_MAX_VERT_OUT and VGT_GS_VERT_ITEMSIZE must be nonzero"); + static_cast(GeometryRingDwords(maxVertices, vertexDwords)); const auto program = RdnaInstructionDecoder{}.Decode(code); std::map vectors; std::map scalars; diff --git a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp index 280320a279f6..b028cb250ab7 100644 --- a/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp +++ b/core/shader/recompiler/SpirvBackend/src/SpirvModuleEmitter.cpp @@ -5,6 +5,7 @@ #include "SpirvBackend/SpirvFlowEmitter.hpp" #include "SpirvBackend/SpirvBda.hpp" #include "SpirvBackend/SpirvMemory/SpirvFormatConvert.hpp" +#include "Optimization/GeometryLowering.hpp" #include #include #include @@ -1153,7 +1154,7 @@ std::uint32_t TessellationOuterFactors(const SpirvEmitterState& state) { std::uint32_t GeometryRingElement(SpirvEmitterState& state, std::uint32_t variable, std::uint32_t index) { const auto& geometry = state.inputInfo.vertex->geometry; const auto clamped = state.module.AllocateId(); - state.module.AddFunction(spv::OpExtInst, TypeU32(state), clamped, GlslStd450(state), GLSLstd450UMin, index, ConstantU32(state, geometry.vertexDwords * geometry.maxVertices)); + state.module.AddFunction(spv::OpExtInst, TypeU32(state), clamped, GlslStd450(state), GLSLstd450UMin, index, ConstantU32(state, GeometryRingDwords(geometry.maxVertices, geometry.vertexDwords))); const auto pointer = state.module.AllocateId(); state.module.AddFunction(spv::OpAccessChain, TypePointer(state, spv::StorageClassPrivate, TypeU32(state)), pointer, variable, clamped); return pointer; @@ -1300,7 +1301,7 @@ void DefineTessellationInterfaces(SpirvEmitterState& state) { const auto emitted = static_cast(TessellationAttribute::GeometryEmitted); if (state.tessVariables.at(ring) == 0u) { const auto& geometry = state.inputInfo.vertex->geometry; - const auto ringType = array(TypeU32(state), geometry.vertexDwords * geometry.maxVertices + 1u); + const auto ringType = array(TypeU32(state), GeometryRingDwords(geometry.maxVertices, geometry.vertexDwords) + 1u); const auto variable = state.module.DefineInitializedGlobalVariable(TypePointer(state, spv::StorageClassPrivate, ringType), spv::StorageClassPrivate, state.module.Constant(spv::OpConstantNull, ringType)); if (state.spirvVersion >= 0x00010400u) state.interfaceVariables.push_back(variable); state.tessVariables.at(ring) = variable; From f224ad5bcdb0fa5f4df998f1de9b7ecff23da818 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 22:49:27 +0200 Subject: [PATCH 34/34] fix(agc): accept the PS4 copy VS render target index as a geometry gl_Layer Co-Authored-By: Claude Opus 5.5 --- .../Graphics/src/ShaderValidation.cpp | 1 + .../tests/execution/GcnGeometry.cpp | 48 ++++++++++++++++--- .../changes/fix-agc-ps4-geometry-layer.md | 5 ++ 3 files changed, 47 insertions(+), 7 deletions(-) create mode 100644 docs/dev/debt/changes/fix-agc-ps4-geometry-layer.md diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp index feaee9b40aac..6509c3e1ccd0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp @@ -120,6 +120,7 @@ struct Module { if (stage == Stage::Geometry && !(!input && (value == spv::BuiltInClipDistance || value == spv::BuiltInCullDistance) && copiedGeometry)) { const auto signature = Signature(type); if (copiedGeometry && input && (value == spv::BuiltInPrimitiveId || value == spv::BuiltInInvocationId) && (signature == "i32" || signature == "u32")) return; + if (copiedGeometry && !input && value == spv::BuiltInLayer && layerOutput && (signature == "u32" || signature == "i32")) return; Require(value == spv::BuiltInPosition && signature == "f32x4" && (input || !position) && !(copiedGeometry && input), "unsupported geometry built-in"); if (!input) position = true; return; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp index c7a43573fa64..6a5042c49b9d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/GcnGeometry.cpp @@ -1,9 +1,11 @@ #include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp" #include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp" #include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp" #include "Recompiler.hpp" #include "RdnaDecoder/RdnaInstructionDecoder.hpp" #include "VulkanTestDevice.hpp" +#include #include #include #include @@ -64,6 +66,14 @@ alignas(256) constexpr std::array GcnCopy{ 0x05040302, 0xf800020f, 0x08070706, 0xbf810000, }; +alignas(256) constexpr std::array GcnCopyLayer{ + 0x34020082, 0xe0305000, 0x80400201, 0xe0305100, 0x80400301, 0xe0305200, 0x80400401, 0xb0040300, + 0xe0305000, 0x04400501, 0xe0305400, 0x80400601, 0xbf8c0000, 0x7e0e0280, 0x7e1002f2, 0xf80000cf, + 0x05040302, 0xf80008d4, 0x00070000, 0xf800020f, 0x08070706, 0xbf810000, +}; + +constexpr std::uint32_t LayerExports = (1u << 18u) | (1u << 21u); + alignas(256) constexpr std::array GcnCopyFolded{ 0x34020082, 0xb0040200, 0xb7840100, 0x8f058881, 0x92068a81, 0xe0305000, 0x04400201, 0xe0305000, 0x05400301, 0xe0305000, 0x06400401, 0xbf8c0000, 0xf80008cf, 0x02040302, 0xbf810000, @@ -126,7 +136,7 @@ alignas(256) constexpr std::array Indices{0u, 1u}; constexpr std::array RingUserData{0x1000u, 0u, 0u, 0u}; constexpr std::array GeometryUserData{0x1000u, 0u, 0u, 0u, 0x2000u, 0u, 0u, 0u}; -GeometryConfiguration Points() { +GeometryConfiguration Points(std::span copy = GcnCopy) { GeometryConfiguration geometry; geometry.inputVertices = 1u; geometry.outputTopology = 2u; @@ -134,11 +144,11 @@ GeometryConfiguration Points() { geometry.instances = 1u; geometry.esgsItemDwords = 2u; geometry.vertexDwords = 5u; - geometry.exports = ShaderRecompiler::ParseGeometryCopyProgram(GcnCopy, geometry.maxVertices, geometry.vertexDwords, std::nullopt); + geometry.exports = ShaderRecompiler::ParseGeometryCopyProgram(copy, geometry.maxVertices, geometry.vertexDwords, std::nullopt); return geometry; } -ShaderRecompiler::RecompileResult Compile(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, std::span userData, std::uint32_t& pushCursor, const GeometryConfiguration& geometry) { +ShaderRecompiler::RecompileResult Compile(const ShaderRecompiler::SpirvTarget& target, ShaderStage stage, std::span code, std::span userData, std::uint32_t& pushCursor, const GeometryConfiguration& geometry, std::uint32_t exports = 0u) { const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; std::optional pixel; std::optional vertex; @@ -152,6 +162,7 @@ ShaderRecompiler::RecompileResult Compile(const ShaderRecompiler::SpirvTarget& t pixel = info; } else { vertex = ShaderRecompiler::ShaderVertexStageInfo{}; + vertex->paClVsOutCntl = exports; graphics = ShaderRecompiler::GraphicsCompileContext{0u, {}, std::nullopt, std::nullopt, {reinterpret_cast(Indices.data()), static_cast(Indices.size()), 2, 1}, std::nullopt, false, std::nullopt, geometry}; } const auto layout = stage == ShaderStage::Fragment ? PixelPushLayout(pushCursor, target) : ShaderRecompiler::BindingLayout{0, 0, pushCursor, AgcDriver::Graphics::PipelinePushSlotBytes - pushCursor}; @@ -209,13 +220,27 @@ std::string PixelText(const std::array& pixel) { return text; } -void RequireQuads(AgcDriver::VulkanDevice& device) { +std::size_t LayerStores(const ShaderRecompiler::RecompileResult& result) { + const auto words = result.spirv.Words(); + std::uint32_t layer = 0u; + for (std::size_t i = 5; i < words.size() && (words[i] >> 16u) != 0u; i += words[i] >> 16u) { + if ((words[i] & 0xffffu) == spv::OpDecorate && (words[i] >> 16u) == 4u && words[i + 2] == spv::DecorationBuiltIn && words[i + 3] == spv::BuiltInLayer) layer = words[i + 1]; + } + std::size_t stores = 0; + for (std::size_t i = 5; layer != 0u && i < words.size() && (words[i] >> 16u) != 0u; i += words[i] >> 16u) { + if ((words[i] & 0xffffu) == spv::OpStore && words[i + 1] == layer) ++stores; + } + return stores; +} + +void RequireQuads(AgcDriver::VulkanDevice& device, std::span copy = GcnCopy, std::uint32_t exports = 0u) { const auto target = device.Target(); - const auto geometry = Points(); + const auto geometry = Points(copy); std::uint32_t cursor = 0; - auto exporter = Compile(target, ShaderStage::Vertex, GcnExport, RingUserData, cursor, geometry); - auto program = Compile(target, ShaderStage::Geometry, GcnGeometry, GeometryUserData, cursor, geometry); + auto exporter = Compile(target, ShaderStage::Vertex, GcnExport, RingUserData, cursor, geometry, exports); + auto program = Compile(target, ShaderStage::Geometry, GcnGeometry, GeometryUserData, cursor, geometry, exports); auto fragment = Compile(target, ShaderStage::Fragment, PixelCode, {}, cursor, geometry); + Require(LayerStores(program) == (exports == 0u ? 0u : 4u), "the GCN geometry program stored gl_Layer " + std::to_string(LayerStores(program)) + " times, expected once before each of its four emitted vertices when the copy VS exports the render target index and never otherwise"); for (std::size_t i = 0; i < Pixels.size(); i += 4) { for (std::size_t c = 0; c < 4; ++c) Pixels[i + c] = std::byte{Background[c]}; } @@ -233,6 +258,7 @@ void RequireQuads(AgcDriver::VulkanDevice& device) { AgcDriver::Graphics::State state{}; state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0xb0u, 64, 64, std::nullopt, std::nullopt, 1.0f, 64.0f}; state.stages.legacyGeometry = geometry; + state.paClVsOutCntl = exports; state.color = {reinterpret_cast(Pixels.data()), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, Pixels.size(), 0xe4u}; state.colors = {state.color}; state.hasColorTarget = true; @@ -253,6 +279,11 @@ void RequireQuads(AgcDriver::VulkanDevice& device) { state.blend.colorWriteMask = 15; state.blends = {state.blend}; state.blendConstants = {0.25f, 0.25f, 0.25f, 0.25f}; + VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES}; + subgroup.subgroupSize = target.subgroupSize; + subgroup.supportedStages = device.SubgroupStages(); + subgroup.supportedOperations = VK_SUBGROUP_FEATURE_BASIC_BIT | VK_SUBGROUP_FEATURE_VOTE_BIT | VK_SUBGROUP_FEATURE_ARITHMETIC_BIT | VK_SUBGROUP_FEATURE_BALLOT_BIT | VK_SUBGROUP_FEATURE_SHUFFLE_BIT | VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT | VK_SUBGROUP_FEATURE_QUAD_BIT; + static_cast(AgcDriver::Graphics::ValidateShaders(shaders, state, subgroup, false, true, false, true, false, false, true, true, exports != 0u, true, true, true, false, true, false)); device.Draw(state, {reinterpret_cast(Indices.data()), static_cast(Indices.size()), 2, 1, 0, true, 0, 0}, shaders); device.WaitIdle(); for (const auto [centre, red, name] : {std::tuple{-0.5f, 80u, "first"}, std::tuple{0.5f, 48u, "second"}}) { @@ -467,6 +498,9 @@ int main() { ShaderRecompiler::SetGcnGuestShaders(true); RequireGeometryMessages(device->Target()); RequireQuads(*device); + const auto capabilities = device->Target().supportedCapabilities; + if (std::ranges::find(capabilities, static_cast(spv::CapabilityShaderViewportIndexLayerEXT)) != capabilities.end()) RequireQuads(*device, GcnCopyLayer, LayerExports); + else std::puts("GCN geometry: render target index export skipped, the device has no VK_EXT_shader_viewport_index_layer"); ShaderRecompiler::SetGcnGuestShaders(false); device.reset(); std::puts("GCN geometry tests passed"); diff --git a/docs/dev/debt/changes/fix-agc-ps4-geometry-layer.md b/docs/dev/debt/changes/fix-agc-ps4-geometry-layer.md new file mode 100644 index 000000000000..0b9645023cde --- /dev/null +++ b/docs/dev/debt/changes/fix-agc-ps4-geometry-layer.md @@ -0,0 +1,5 @@ +# libSceAgcDriver + +## add Functional + +- [PS4 (GCN) geometry render target index](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderValidation.cpp) (libSceAgcDriver, PS4) - not measured on a console. With `PA_CL_VS_OUT_CNTL` USE_VTX_RENDER_TARGET_INDX and the misc vector enabled, the copy VS's render target index becomes the geometry stage's `gl_Layer`, written before each emitted vertex, when the device has `VK_EXT_shader_viewport_index_layer`. A primitive whose vertices carry different indices takes the layer of the vertex Vulkan selects; which vertex GCN takes is not measured. The copy VS's viewport index (`USE_VTX_VIEWPORT_INDX`) still throws as an unsupported geometry built-in.