fix(recompiler): split image reads whose T# or S# is a Phi of SRT reads

A sampler (or texture) chosen by scalar control flow reaches the image
operation as a Phi of two ReadConst values. The SRT walker only accepts
invariant Phis, so GetHandle threw "GetSamplerResource dword 0 is not a
valid runtime value" and the draw was skipped (G-buffer and HDR draws
in PPSA21564).

Before tracking, a read-only image operation (sample, gather, LOD query,
size query, load) whose descriptor dwords are Phis of one block is
copied once per distinct incoming descriptor. Each copy gets its own
memory entry and descriptor handles whose dwords are the edge's values,
recomputed before the operation (SRT reads, user data, the shader base
and pure uniform arithmetic over them only). The results are selected
by a Bool Phi of the edge that entered the Phi block. The copies run
where the original did, so implicit derivatives are unchanged, and the
host binds every edge's descriptor. Any other shape (a nested Phi, a
dynamic read on an edge, a store or atomic) is left alone and still
throws.
This commit is contained in:
Dean Galvin
2026-10-03 10:02:51 +13:00
parent 7d40a57d18
commit ad72175a67
2 changed files with 375 additions and 0 deletions
@@ -374,6 +374,108 @@ void verifyBindlessTable() {
}
void verifyDescriptorPhis() {
using namespace ShaderRecompiler;
constexpr std::uint32_t Format8888UNorm = 56;
constexpr std::uint32_t Type2D = 9;
struct alignas(256) Texture { std::array<std::uint8_t, 256> bytes{}; };
static Texture textures[2];
const auto imageDescriptor = [&](const Texture& texture) {
const auto base = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(texture.bytes.data()));
return std::array<std::uint32_t, 8>{static_cast<std::uint32_t>(base >> 8u), static_cast<std::uint32_t>((base >> 40u) & 0xffu) | (Format8888UNorm << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (Type2D << 28u), 0u, 0u, 0u, 0u};
};
const std::array<std::uint32_t, 4> pointWrap{0u, 0u, 0u, 0u};
const std::array<std::uint32_t, 4> linearMirror{0x49u, 0u, 0x00500000u, 0u};
std::array<std::uint32_t, 4> output{};
const auto outputAddress = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(output.data()));
std::array<std::uint32_t, 32> srt{};
const auto first = imageDescriptor(textures[0]);
const auto second = imageDescriptor(textures[1]);
std::copy(first.begin(), first.end(), srt.begin());
std::copy(pointWrap.begin(), pointWrap.end(), srt.begin() + 8);
std::copy(linearMirror.begin(), linearMirror.end(), srt.begin() + 12);
const std::array<std::uint32_t, 4> outputV{static_cast<std::uint32_t>(outputAddress), static_cast<std::uint32_t>((outputAddress >> 32u) & 0xffffu), 16u, 0xfacu};
std::copy(outputV.begin(), outputV.end(), srt.begin() + 16);
srt[20] = 1u;
std::copy(second.begin(), second.end(), srt.begin() + 24);
const auto srtAddress = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(srt.data()));
const std::array<std::uint32_t, 2> userData{static_cast<std::uint32_t>(srtAddress), static_cast<std::uint32_t>(srtAddress >> 32u)};
const std::array<std::uint32_t, 1> capabilities{29u};
const auto makeRequest = [&](const std::vector<std::uint32_t>& code, std::uint32_t waveSize = 32u) {
RecompileRequest request{};
request.shader = {ShaderStage::Compute, 0x21000u, code, 0, {}};
request.context.waveSize = waveSize;
request.context.userDataBaseRegister = 0;
request.context.userData = userData;
request.context.compute = ShaderComputeStageInfo{{waveSize, 1u, 1u}, 0u, {false, false, false}, false, 1u};
request.target.vulkanVersion = 0x00401000u;
request.target.spirvVersion = 0x00010300u;
request.target.subgroupSize = 32;
request.target.supportedCapabilities = capabilities;
request.target.fragmentShaderBarycentricEnabled = false;
request.layout.pushConstantSizeBytes = 128;
return request;
};
const auto countOps = [](const std::vector<std::uint32_t>& words, std::uint32_t opcode) {
std::size_t count = 0;
for (std::size_t cursor = 5; cursor < words.size();) {
const auto length = words[cursor] >> 16u;
require(length != 0 && length <= words.size() - cursor, "descriptor Phi: truncated SPIR-V instruction");
count += (words[cursor] & 0xffffu) == opcode ? 1u : 0u;
cursor += length;
}
return count;
};
constexpr std::uint32_t OpImageSampleExplicitLod = 88;
const std::vector<std::uint32_t> samplerCode{0xf40c0200u, 0xfa000000u, 0xf4000400u, 0xfa000050u, 0xbf8cc07fu, 0xbf068010u, 0xbf850003u, 0xf4080500u, 0xfa000020u, 0xbf820002u, 0xf4080500u, 0xfa000030u, 0xf4080600u, 0xfa000040u, 0xbf8cc07fu, 0xf09c0f08u, 0x00a20000u, 0xbf8c3f70u, 0xe0700000u, 0x80060000u, 0xbf810000u};
const std::vector<std::uint32_t> imageCode{0xf4000400u, 0xfa000050u, 0xf4080500u, 0xfa000020u, 0xbf8cc07fu, 0xbf068010u, 0xbf850003u, 0xf40c0200u, 0xfa000000u, 0xbf820002u, 0xf40c0200u, 0xfa000060u, 0xf4080600u, 0xfa000040u, 0xbf8cc07fu, 0xf09c0f08u, 0x00a20000u, 0xbf8c3f70u, 0xe0700000u, 0x80060000u, 0xbf810000u};
const std::vector<std::uint32_t> dynamicCode{0xf40c0200u, 0xfa000000u, 0xf4000400u, 0xfa000050u, 0xbf8cc07fu, 0xbf068010u, 0xbf850003u, 0xf4080500u, 0xfa000020u, 0xbf820002u, 0xf4080500u, 0x20000000u, 0xf4080600u, 0xfa000040u, 0xbf8cc07fu, 0xf09c0f08u, 0x00a20000u, 0xbf8c3f70u, 0xe0700000u, 0x80060000u, 0xbf810000u};
const auto compile = [&](const std::vector<std::uint32_t>& code, std::size_t images, std::size_t samplers) {
auto request = makeRequest(code);
const auto plan = GetResourcePlan(request);
require(plan->info.images.size() == images && plan->info.samplers.size() == samplers && plan->info.sampledPairs.size() == 2u, "descriptor Phi: the edges were not given one resource each");
AgcDriver::ShaderMemory memory({});
const auto capture = memory.Capture(request);
request.context.memory = memory.Regions();
const auto compiled = Recompile(request, *capture);
require(countOps(compiled->spirv, OpImageSampleExplicitLod) == 2u, "descriptor Phi: the SPIR-V does not sample once per edge");
#if ANYPS5_ENABLE_SPIRV_TOOLS
static_cast<void>(ValidateAndOptimizeSpirv(compiled->spirv, request.target.vulkanVersion, request.target.spirvVersion));
#endif
return capture;
};
const auto samplerCapture = compile(samplerCode, 1u, 2u);
const auto& samplers = samplerCapture->snapshot.samplers;
require(samplers.size() == 2u, "descriptor Phi: the snapshot does not hold both S#s");
const auto holds = [&](const std::array<std::uint32_t, 4>& words) {
return std::ranges::any_of(samplers, [&](const DescriptorValue& value) {
return value.dwordCount == 4u && std::equal(words.begin(), words.end(), value.dwords.begin());
});
};
require(holds(pointWrap) && holds(linearMirror), "descriptor Phi: the snapshot S#s are not the two edges' S#s");
const auto imageCapture = compile(imageCode, 2u, 1u);
const auto& images = imageCapture->snapshot.images;
require(images.size() == 2u, "descriptor Phi: the snapshot does not hold both T#s");
const auto holdsImage = [&](const std::array<std::uint32_t, 8>& words) {
return std::ranges::any_of(images, [&](const DescriptorValue& value) {
return std::equal(words.begin(), words.end(), value.dwords.begin());
});
};
require(holdsImage(first) && holdsImage(second), "descriptor Phi: the snapshot T#s are not the two edges' T#s");
auto twoLane = makeRequest(samplerCode, 64u);
AgcDriver::ShaderMemory twoLaneMemory({});
const auto twoLaneCapture = twoLaneMemory.Capture(twoLane);
twoLane.context.memory = twoLaneMemory.Regions();
require(countOps(Recompile(twoLane, *twoLaneCapture)->spirv, OpImageSampleExplicitLod) == 4u, "descriptor Phi: the two-lane SPIR-V does not sample once per edge and half");
auto dynamic = makeRequest(dynamicCode);
expectFailure([&] { static_cast<void>(GetResourcePlan(dynamic)); }, "GetSamplerResource dword 0 is not a valid runtime value", "descriptor Phi: an edge without an SRT slot was accepted");
}
void verifyProgramCounterRelativeData() {
using namespace ShaderRecompiler;
static const std::array<std::uint32_t, 15> code{
@@ -605,6 +707,7 @@ int main() {
verifyRegisterSources();
verifyPureFlatSlots();
verifyBindlessTable();
verifyDescriptorPhis();
verifyProgramCounterRelativeData();
verifyMeshConfiguration();
verifyPixelInputs();
@@ -2,11 +2,13 @@
#include "Optimization/SrtWalker.hpp"
#include "Optimization/ResourceMaterializer.hpp"
#include "IntermediateRepresentation/IrBuilder.hpp"
#include "Optimization/SrtWalker/SrtInstructionPredicates.hpp"
#include <algorithm>
#include <array>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <span>
#include <string>
@@ -106,6 +108,7 @@ public:
if (!m_program.Resources().srtPlanComplete) {
fail("SRT plan is not ready");
}
SplitDescriptorPhis();
PlanIndirectImages();
for (auto& block : m_program.Blocks()) {
for (IrValue* inst : block->Instructions()) {
@@ -470,6 +473,269 @@ private:
});
}
static constexpr std::uint32_t phiSearchDepth = 8u;
static bool SplittableImageRead(const IrValue& inst) {
switch (inst.Opcode()) {
case IrOpcode::ImageSampleRaw:
case IrOpcode::ImageGatherRaw:
case IrOpcode::ImageQueryLod:
case IrOpcode::ImageQueryDimensions:
case IrOpcode::ImageRead: return inst.Type() == IrType::U32x4;
default: return false;
}
}
void CollectDescriptorPhis(IrValue* value, std::vector<IrValue*>& phis, std::uint32_t depth) const {
value = value->Resolve();
if (value->HasImmediate()) {
return;
}
if (value->IsPhi()) {
if (ResolveInvariantPhi(m_program.Resources(), value) == nullptr && std::ranges::find(phis, value) == phis.end()) {
phis.push_back(value);
}
return;
}
if (depth == 0u || !Detail::IsRuntimeUniformOp(value->Opcode())) {
return;
}
for (std::size_t index = 0; index < value->ArgumentCount(); index++) {
CollectDescriptorPhis(value->Argument(index), phis, depth - 1u);
}
}
static IrValue* PhiIncoming(const IrValue& phi, const IrBlock* predecessor) {
for (std::size_t index = 0; index < phi.ArgumentCount(); index++) {
if (phi.PhiBlock(index) == predecessor) {
return phi.Argument(index);
}
}
return nullptr;
}
IrValue* EmitBefore(IrValue& position, IrOpcode op, IrType type, std::span<IrValue* const> arguments, std::uint64_t flags = 0) {
IrValue& value = m_program.CreateValue(op, type, flags);
for (IrValue* argument : arguments) {
value.AddArgument(argument);
}
position.Parent()->InsertInstructionBefore(&position, &value);
return &value;
}
IrValue* EmitCopy(const IrValue& original, std::span<IrValue* const> arguments, IrValue& position) {
return EmitBefore(position, original.Opcode(), original.Type(), arguments, original.Flags<std::uint64_t>());
}
IrValue* Rematerialize(IrValue* value, IrValue& position, bool emit, std::uint32_t depth) {
value = value->Resolve();
if (value->HasImmediate()) {
return value;
}
if (value->IsPhi()) {
IrValue* invariant = ResolveInvariantPhi(m_program.Resources(), value);
return invariant == nullptr || invariant->IsPhi() ? nullptr : Rematerialize(invariant, position, emit, depth);
}
if (depth == 0u) {
return nullptr;
}
const auto op = value->Opcode();
const bool register_ = op == IrOpcode::GetUserData;
const bool argumentless = (op == IrOpcode::GetShaderBase || op == IrOpcode::GetSrtResource) && value->ArgumentCount() == 0u;
const bool srtRead = op == IrOpcode::ReadConst && value->ArgumentCount() == 2u && value->Argument(0)->Resolve()->Opcode() == IrOpcode::GetSrtResource && value->Argument(1)->Resolve()->HasImmediate();
if (!register_ && !argumentless && !srtRead && !Detail::IsRuntimeUniformOp(op)) {
return nullptr;
}
std::vector<IrValue*> arguments;
for (std::size_t index = 0; index < value->ArgumentCount(); index++) {
IrValue* argument = register_ ? value->Argument(index) : Rematerialize(value->Argument(index), position, emit, depth - 1u);
if (argument == nullptr) {
return nullptr;
}
arguments.push_back(argument);
}
return emit ? EmitCopy(*value, arguments, position) : value;
}
IrValue* SubstituteEdge(IrValue* value, const IrBlock* predecessor, IrValue& position, bool emit, std::uint32_t depth) {
value = value->Resolve();
std::vector<IrValue*> phis;
CollectDescriptorPhis(value, phis, depth);
if (phis.empty()) {
return value;
}
if (value->IsPhi()) {
IrValue* incoming = PhiIncoming(*value, predecessor);
return incoming == nullptr ? nullptr : Rematerialize(incoming, position, emit, phiSearchDepth);
}
std::vector<IrValue*> arguments;
for (std::size_t index = 0; index < value->ArgumentCount(); index++) {
IrValue* argument = SubstituteEdge(value->Argument(index), predecessor, position, emit, depth - 1u);
if (argument == nullptr) {
return nullptr;
}
arguments.push_back(argument);
}
return emit ? EmitCopy(*value, arguments, position) : value;
}
IrValue& EdgeSelector(IrBlock& block, const std::vector<bool>& edges) {
for (const auto& selector : m_edgeSelectors) {
if (selector.block == &block && selector.edges == edges) {
return *selector.value;
}
}
IrValue& phi = m_program.CreateValue(IrOpcode::Phi, IrType::Bool);
const auto& predecessors = block.Predecessors();
for (std::size_t index = 0; index < predecessors.size(); index++) {
phi.AddPhiOperand(predecessors[index], &m_builder.ConstantBool(edges[index]));
}
block.InsertInstructionBefore(nullptr, &phi);
m_edgeSelectors.push_back({&block, edges, &phi});
return phi;
}
void SplitDescriptorPhi(IrValue& inst) {
const auto info = ImageOpcodeInfoOf(inst.Opcode());
const std::uint32_t handleCount = info.needsSampler ? 2u : 1u;
if (inst.ArgumentCount() < handleCount) {
return;
}
std::array<IrValue*, 2> handles {};
std::array<bool, 2> split {};
std::vector<IrValue*> phis;
for (std::uint32_t slot = 0; slot < handleCount; slot++) {
IrValue* handle = inst.Argument(slot)->Resolve();
const auto expected = slot == 0u ? IrOpcode::GetImageResource : IrOpcode::GetSamplerResource;
if (handle->Opcode() != expected || handle->ArgumentCount() != (slot == 0u ? 8u : 4u)) {
return;
}
handles[slot] = handle;
std::vector<IrValue*> handlePhis;
for (std::size_t dword = 0; dword < handle->ArgumentCount(); dword++) {
CollectDescriptorPhis(handle->Argument(dword), handlePhis, phiSearchDepth);
}
split[slot] = !handlePhis.empty();
for (IrValue* phi : handlePhis) {
if (std::ranges::find(phis, phi) == phis.end()) {
phis.push_back(phi);
}
}
}
if (phis.empty()) {
return;
}
IrBlock* block = phis.front()->Parent();
if (block == nullptr || inst.Parent() == nullptr) {
return;
}
const auto& predecessors = block->Predecessors();
if (predecessors.size() < 2u) {
return;
}
for (const IrValue* phi : phis) {
if (phi->Parent() != block || phi->PhiBlockCount() != predecessors.size()) {
return;
}
for (const IrBlock* predecessor : predecessors) {
if (PhiIncoming(*phi, predecessor) == nullptr) {
return;
}
}
}
std::vector<std::uint32_t> edgeArm(predecessors.size());
std::vector<const IrBlock*> arms;
for (std::size_t edge = 0; edge < predecessors.size(); edge++) {
std::uint32_t arm = 0;
for (; arm < arms.size(); arm++) {
const bool same = std::ranges::all_of(phis, [&](const IrValue* phi) {
return EquivalentValue(m_program.Resources(), PhiIncoming(*phi, predecessors[edge]), PhiIncoming(*phi, arms[arm]));
});
if (same) {
break;
}
}
if (arm == arms.size()) {
arms.push_back(predecessors[edge]);
}
edgeArm[edge] = arm;
}
for (const IrBlock* arm : arms) {
for (std::uint32_t slot = 0; slot < handleCount; slot++) {
for (std::size_t dword = 0; split[slot] && dword < handles[slot]->ArgumentCount(); dword++) {
if (SubstituteEdge(handles[slot]->Argument(dword), arm, inst, false, phiSearchDepth) == nullptr) {
return;
}
}
}
}
std::vector<IrValue*> copies;
const auto flags = inst.Flags<MemoryFlags>();
const auto memory = m_program.Resources().memoryInfo.at(flags.index);
for (std::uint32_t arm = 0; arm < arms.size(); arm++) {
std::vector<IrValue*> arguments(inst.Arguments().begin(), inst.Arguments().end());
for (std::uint32_t slot = 0; slot < handleCount; slot++) {
if (!split[slot]) {
continue;
}
std::vector<IrValue*> dwords;
for (std::size_t dword = 0; dword < handles[slot]->ArgumentCount(); dword++) {
dwords.push_back(SubstituteEdge(handles[slot]->Argument(dword), arms[arm], inst, true, phiSearchDepth));
}
arguments[slot] = EmitCopy(*handles[slot], dwords, inst);
}
auto copyFlags = flags;
if (arm != 0u) {
copyFlags.index = static_cast<std::uint32_t>(m_program.Resources().memoryInfo.size());
m_program.Resources().memoryInfo.push_back(memory);
}
std::uint64_t rawFlags = 0;
std::memcpy(&rawFlags, &copyFlags, sizeof(copyFlags));
copies.push_back(EmitBefore(inst, inst.Opcode(), inst.Type(), arguments, rawFlags));
}
IrValue* result = copies.back();
if (copies.size() > 1u) {
std::array<IrValue*, 4> components {};
for (std::uint32_t component = 0; component < components.size(); component++) {
const auto extract = [&](IrValue* vector) {
const std::array<IrValue*, 2> arguments {vector, &m_builder.Constant(component)};
return EmitBefore(inst, IrOpcode::CompositeExtractU32x4, IrType::U32, arguments);
};
IrValue* selected = extract(copies.back());
for (std::uint32_t arm = static_cast<std::uint32_t>(copies.size()) - 1u; arm-- > 0u;) {
std::vector<bool> edges(edgeArm.size());
for (std::size_t edge = 0; edge < edgeArm.size(); edge++) {
edges[edge] = edgeArm[edge] == arm;
}
const std::array<IrValue*, 3> arguments {&EdgeSelector(*block, edges), extract(copies[arm]), selected};
selected = EmitBefore(inst, IrOpcode::SelectU32, IrType::U32, arguments);
}
components[component] = selected;
}
result = EmitBefore(inst, IrOpcode::CompositeConstructU32x4, IrType::U32x4, components);
}
inst.ReplaceAllUsesWith(result);
inst.Invalidate();
inst.Parent()->RemoveInstruction(&inst);
}
void SplitDescriptorPhis() {
std::vector<IrValue*> candidates;
for (auto& block : m_program.Blocks()) {
for (IrValue* inst : block->Instructions()) {
if (SplittableImageRead(*inst)) {
candidates.push_back(inst);
}
}
}
for (IrValue* inst : candidates) {
SplitDescriptorPhi(*inst);
}
}
void PlanIndirectImages() {
// Kill switch: APS5_NO_BINDLESS_IMAGES=1 leaves table-loaded T#s unplanned (GetHandle then
// rejects them as before).
@@ -822,6 +1088,12 @@ private:
// APS5_TRACE_BDA: address accesses seen by Collect (the first bdaTraceLimit are printed).
unsigned m_bdaTraces = 0;
std::vector<IndirectImagePlan> m_indirectImages;
struct EdgeSelectorEntry {
IrBlock* block = nullptr;
std::vector<bool> edges;
IrValue* value = nullptr;
};
std::vector<EdgeSelectorEntry> m_edgeSelectors;
};
}