From 1282ad9988ea14543897bcfbcbb84e2076d409e2 Mon Sep 17 00:00:00 2001 From: mjnhbg3 <2287071+mjnhbg3@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:16:47 -0500 Subject: [PATCH 1/2] fix(kyty): align scalar load operands independently --- .../backend/spirv/spirvEmitterMemory.cpp | 28 ++--- .../recompiler/ir/passes/RayQueryResults.cpp | 15 ++- .../recompiler/ir/passes/RayQuerySource.cpp | 30 ++++- .../ir/passes/RayQueryTraversal.cpp | 8 +- .../ir/passes/ResourceMaterialization.cpp | 8 +- .../recompiler/ir/passes/ResourceTracking.cpp | 60 +++++----- .../ir/passes/ShaderInfoCollection.cpp | 2 +- .../shader/recompiler/ir/passes/SrtWalker.cpp | 22 +--- .../shader/recompiler/ir/passes/TableMode.cpp | 2 +- .../KytyShim/tests/UniformScalarLoads.cpp | 109 ++++++++++++++++-- .../KytyShim/tests/UniformScalarReplay.cpp | 53 ++++++--- .../fix-kyty-sbuffer-offset-alignment.md | 2 +- 12 files changed, 228 insertions(+), 111 deletions(-) diff --git a/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp b/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp index ce5555e8849..f708295928f 100644 --- a/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp +++ b/core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp @@ -1101,11 +1101,11 @@ uint32_t LoadIndirectScalarBuffer(ValueEmitContext& ctx, const IR::Inst& inst) { Unary(state, spv::OpUConvert, TypeU64(state), EmitUMax32(state, stride, ConstantU32(state, 1))), Unary(state, spv::OpUConvert, TypeU64(state), ctx.Arg(handle, 2))); - const auto offset = Binary(state, spv::OpBitwiseAnd, TypeU64(state), - Binary(state, spv::OpIAdd, TypeU64(state), - Unary(state, spv::OpUConvert, TypeU64(state), ctx.Arg(inst, 1)), - ConstantU64(state, ctx.Memory(inst).offset)), - ConstantU64(state, ~uint64_t {3})); + const auto offset = Binary(state, spv::OpIAdd, TypeU64(state), + Unary(state, spv::OpUConvert, TypeU64(state), + Binary(state, spv::OpBitwiseAnd, TypeU32(state), + ctx.Arg(inst, 1), ConstantU32(state, ~3u))), + ConstantU64(state, ctx.Memory(inst).offset & ~3u)); const auto end = Binary(state, spv::OpIAdd, TypeU64(state), offset, ConstantU64(state, sizeof(uint32_t))); const auto scalar_address = [&]() { @@ -2617,25 +2617,15 @@ void EmitReadConstBuffer(ValueEmitContext& ctx, const IR::Inst& inst) { mem.kind = IR::ResourceKind::ScalarBuffer; const auto offset = inst.Arg(1).Resolve(); const auto static_index = offset.IsImmediate() - ? static_cast((uint64_t {offset.U32()} + mem.offset) >> 2u) + ? (offset.U32() >> 2u) + (mem.offset >> 2u) : 0u; auto index = offset.IsImmediate() ? ConstantU32(state, static_index) : Binary(state, spv::OpShiftRightLogical, TypeU32(state), ctx.Arg(inst, 1), ConstantU32(state, 2)); - if (!offset.IsImmediate() && mem.offset != 0u) { - if ((mem.offset & 3u) != 0u) { - const auto low = Binary(state, spv::OpBitwiseAnd, TypeU32(state), ctx.Arg(inst, 1), - ConstantU32(state, 3)); - const auto carry = Binary(state, spv::OpIAdd, TypeU32(state), low, - ConstantU32(state, mem.offset)); - index = Binary(state, spv::OpIAdd, TypeU32(state), index, - Binary(state, spv::OpShiftRightLogical, TypeU32(state), carry, - ConstantU32(state, 2))); - } else { - index = Binary(state, spv::OpIAdd, TypeU32(state), index, - ConstantU32(state, mem.offset >> 2u)); - } + if (!offset.IsImmediate() && mem.offset >= 4u) { + index = Binary(state, spv::OpIAdd, TypeU32(state), index, + ConstantU32(state, mem.offset >> 2u)); } const auto storage_load = [&]() { const auto access = PrepareMemoryResourceAccess(state, mem); diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryResults.cpp b/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryResults.cpp index f223ff73b8c..1843004eefb 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryResults.cpp +++ b/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryResults.cpp @@ -880,8 +880,10 @@ class Machine { const auto* buffer = inst.Arg(0).Resolve().TryInstruction(); if (buffer == nullptr) return "a constant buffer read without resource"; for (uint32_t lane = 0; lane < m_wave; ++lane) { - const auto base = (a(0, lane, 0) & 0xffffffffu) | ((a(0, lane, 1) & 0xffffu) << 32u); - const auto address = base + u32(a(1, lane)) + memory.offset; + const auto raw_base = (a(0, lane, 0) & 0xffffffffu) | ((a(0, lane, 1) & 0xffffu) << 32u); + const auto base = memory.kind == ResourceKind::IndirectBuffer ? raw_base & ~uint64_t {3} : raw_base; + const auto address = base + (u32(a(1, lane)) & ~3u) + + (memory.offset & ~3u); At(out, lane) = Memory(address); if (m_tracking && m_walk) { if (lane == 0) m_taint[out].reset(); @@ -967,9 +969,14 @@ class Machine { continue; } const auto& memory = m_program.memory_info[inst.Flags().index]; + const bool scalar = memory.kind == ResourceKind::ScalarAddress; + const auto low = u32(a(1, lane)); + const auto base_low = memory.address_is_full ? low : u32(a(0, lane, 0)); + const auto base_high = memory.address_is_full ? u32(a(2, lane)) : u32(a(0, lane, 1)); + const auto base = uint64_t {scalar ? base_low & ~3u : base_low} | (uint64_t {base_high} << 32u); + const auto dynamic = memory.address_is_full ? 0u : scalar ? low & ~3u : low; const auto offset = static_cast(static_cast(static_cast(memory.offset))); - const auto address = memory.address_is_full ? ((a(1, lane) & 0xffffffffu) | (a(2, lane) & 0xffffffffu) << 32u) + offset - : ((a(0, lane, 0) & 0xffffffffu) | (a(0, lane, 1) << 32u)) + (a(1, lane) & 0xffffffffu) + offset; + const auto address = base + dynamic + (scalar ? offset & ~uint64_t {3} : offset); auto value = static_cast(Memory(address)); value >>= (address & 3u) * 8u; if (op == Op::LoadAddressU16) value &= 0xffffu; diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/RayQuerySource.cpp b/core/kyty/graphics/shader/recompiler/ir/passes/RayQuerySource.cpp index fb7b4530fe5..ba174011cac 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/RayQuerySource.cpp +++ b/core/kyty/graphics/shader/recompiler/ir/passes/RayQuerySource.cpp @@ -335,6 +335,24 @@ class Evaluator { return value; } + uint32_t AlignDword(uint32_t value) { + auto form = m_store.F(value); + if (std::ranges::all_of(form.terms, [](const auto& term) { return (term.second & 3u) == 0u; })) { + form.constant &= ~uint64_t {3}; + return m_store.Make(std::move(form)); + } + return m_store.Op(32, {static_cast(ValueOpcode::BitwiseAnd32), value, Literal | 0xfffffffcu}); + } + + uint32_t AlignAddress(uint32_t value) { + auto form = m_store.F(value); + if (std::ranges::all_of(form.terms, [](const auto& term) { return (term.second & 3u) == 0u; })) { + form.constant &= ~uint64_t {3}; + return m_store.Make(std::move(form)); + } + return m_store.Join(AlignDword(m_store.Lo(value)), m_store.Hi(value)); + } + Choices Word(Value value) { value = value.Resolve(); if (value.IsImmediate()) { @@ -530,15 +548,22 @@ class Evaluator { Choices Address(const Inst& load) { const auto& memory = m_program.memory_info[load.Flags().index]; auto offset = static_cast(static_cast(static_cast(memory.offset))); + const bool scalar = memory.kind == ResourceKind::ScalarAddress; + if (scalar) offset &= ~uint64_t {3}; Choices bases; auto& ev = load.NumArgs() > 3 ? Given(load.Arg(3)) : *this; if (memory.address_is_full) { bases = ev.Pair(load.Arg(1), load.Arg(2)); + if (scalar) { + for (auto& base: bases) base = AlignAddress(base); + } } else { const auto* handle = ProducerOf(load.Arg(0), ValueOpcode::GetAddressResource); if (handle == nullptr) return {}; for (const auto base: ev.Pair(handle->Arg(0), handle->Arg(1))) { - for (const auto index: ev.Word(load.Arg(1))) bases.push_back(m_store.Add(base, m_store.Widen(index))); + for (const auto index: ev.Word(load.Arg(1))) + bases.push_back(m_store.Add(scalar ? AlignAddress(base) : base, + m_store.Widen(scalar ? AlignDword(index) : index))); } } Choices result; @@ -555,7 +580,8 @@ class Evaluator { for (const auto base: Pair(buffer->Arg(0), buffer->Arg(1))) { const auto start = m_store.Op(64, {Base48, base}); for (const auto index: Word(read.Arg(1))) { - result.push_back(m_store.Add(m_store.Add(start, m_store.Widen(index)), m_store.Constant(64, memory.offset))); + result.push_back(m_store.Add(m_store.Add(start, m_store.Widen(AlignDword(index))), + m_store.Constant(64, memory.offset & ~3u))); } } Cap(result); diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.cpp b/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.cpp index b62684e7553..9597fac4d3e 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.cpp +++ b/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.cpp @@ -3348,11 +3348,11 @@ bool DeriveLaneAlpha(const Program& program, const PacketWalk& w, const BlasWalk if (m2_load == nullptr || !std::ranges::all_of(textures->first, descriptor_defined)) return false; const auto material_element = [&](const Inst* load) -> std::optional> { if (!a.scalar) return ElementOfThree(load->Arg(1)); - auto at = MemoryOf(program, *load).offset; + auto at = MemoryOf(program, *load).offset & ~3u; auto index = Canonical(load->Arg(1)); const auto plus = Operands(index, Op::IAdd32, [](Value side) { return Immediate(side).has_value(); }); if (plus) { - at += *Immediate(plus->first); + at += *Immediate(plus->first) & ~3u; index = Canonical(plus->second); } const auto* lsl = Producer(index, Op::ShiftLeftLogical32); @@ -3993,9 +3993,9 @@ std::optional WaveResultKind(const Program& program, const L (base->GetOpcode() == ValueOpcode::CompositeConstructU64 && resource->Arg(0).Resolve() == base->Arg(0).Resolve())); if (!blas || !InLoop(program, value->Parent(), s.wave_header, s.wave_latch)) return std::nullopt; - auto at = MemoryOf(program, *value).offset; + auto at = MemoryOf(program, *value).offset & ~3u; if (const auto* add = Producer(value->Arg(1), ValueOpcode::IAdd32); add != nullptr) - at += Immediate(add->Arg(0)).value_or(Immediate(add->Arg(1)).value_or(0u)); + at += Immediate(add->Arg(0)).value_or(Immediate(add->Arg(1)).value_or(0u)) & ~3u; at &= 7u; return at == 0u ? std::optional(RayQueryResultKind::Node) : at == 4u ? std::optional(RayQueryResultKind::Word) diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp b/core/kyty/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp index eedc50cf3a3..8287d33b401 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp +++ b/core/kyty/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cpp @@ -662,7 +662,7 @@ bool MaterializeIndirectDescriptor(const ResourcePlan& p (base & AddressMask & ~uint64_t {3}) + (offset & ~uint64_t {3}), bytes)); }; const auto scalar_buffer_offset = [&](uint64_t offset) { - return (offset + indirect.table_immediate) & ~uint64_t {3}; + return (offset & ~uint64_t {3}) + (indirect.table_immediate & ~3u); }; const auto normalization_failed = [&](uint64_t offset, uint32_t key, uint64_t step, std::string_view key_kind) { @@ -1108,10 +1108,12 @@ bool MaterializeIndirectDescriptor(const ResourcePlan& p if (!EvaluateIndirectCount(program, indirect, runtime, key_count)) return false; if (!indirect.selector_first.IsEmpty() && !WalkedValue(program, indirect.selector_first, first_key)) return false; + const auto first_offset = indirect.indexed + ? uint64_t {indirect.table_offset} + indirect.table_immediate + : scalar_buffer_offset(indirect.table_offset); if (indirect.table_stride == 0u || key_count > MaxIndirectDescriptorProbes || (indirect.selector_first.IsEmpty() && key_count != 0u && - uint64_t {indirect.table_offset} + indirect.table_immediate + - uint64_t {key_count - 1u} * indirect.table_stride + descriptor_bytes > + first_offset + uint64_t {key_count - 1u} * indirect.table_stride + descriptor_bytes > UINT32_MAX + 1ull)) { return false; } diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp b/core/kyty/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp index 43e42ab32ba..e906151d542 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp +++ b/core/kyty/graphics/shader/recompiler/ir/passes/ResourceTracking.cpp @@ -608,9 +608,8 @@ class Tracker { offset = emit(ValueOpcode::ISub32, {dynamic, Value(indirect.table_offset)}); valid = emit(ValueOpcode::ULessThanEqual32, {Value(indirect.table_offset), dynamic}); } else { - const auto sum = emit(ValueOpcode::IAdd32, {read.Arg(1), Value(memory.offset)}); - offset = emit(ValueOpcode::BitwiseAnd32, {sum, Value(~3u)}); - valid = emit(ValueOpcode::ULessThanEqual32, {read.Arg(1), sum}); + offset = emit(ValueOpcode::IAdd32, {dynamic, Value(memory.offset & ~3u)}); + valid = emit(ValueOpcode::ULessThanEqual32, {dynamic, offset}); } } key = emit(ValueOpcode::SelectU32, {valid, offset, Value(UINT32_MAX)}); @@ -2705,8 +2704,8 @@ class Tracker { if (memory == nullptr || memory->offset > INT32_MAX || !MemoryIndexBelongsTo(memory_index, *read)) return false; const bool affine = MatchTableOffset(read->Arg(1), index, offset, stride) && - ((offset | stride | memory->offset) & 3u) == 0u && - uint64_t {offset} + memory->offset <= UINT32_MAX; + (stride & 3u) == 0u && + uint64_t {offset & ~3u} + (memory->offset & ~3u) <= UINT32_MAX; if (affine) { workgroup_axis = WorkgroupAxis(index, &first); const auto* bound = BoundedLoop(index, read->Parent()); @@ -2766,14 +2765,10 @@ class Tracker { } if (require_bound && count.IsEmpty() && workgroup_axis == UINT32_MAX && !rows) return false; if (!MakeRuntimeTableSource(*read, material_source)) return false; - if (memory->kind == ResourceKind::ScalarBuffer && - uint64_t {offset} + memory->offset > UINT32_MAX) return false; + if (uint64_t {offset & ~3u} + (memory->offset & ~3u) > UINT32_MAX) return false; selector.source = InternSource(material_source); selector.stride = stride; - selector.offset = memory->kind == ResourceKind::ScalarBuffer - ? static_cast((uint64_t {offset} + memory->offset) & - (byte_bias.IsEmpty() ? ~uint64_t {3} : UINT32_MAX)) - : offset + (memory->offset & ~3u); + selector.offset = (offset & ~3u) + (memory->offset & ~3u); indirect.selector = std::move(selector); indirect.selector_byte_bias = byte_bias; indirect.key_count = count; @@ -3217,8 +3212,8 @@ class Tracker { Value table_guard; const uint32_t alignment_mask = allow_fixed ? ~3u : UINT32_MAX; const auto physical_offset = [&](uint32_t offset, uint32_t immediate, ResourceKind kind) { - return allow_fixed && kind == ResourceKind::ScalarBuffer - ? (uint64_t {offset} + immediate) & ~uint64_t {3} + return kind == ResourceKind::ScalarBuffer || kind == ResourceKind::ScalarAddress + ? uint64_t {offset & ~3u} + (immediate & ~3u) : uint64_t {offset & alignment_mask} + (immediate & alignment_mask); }; for (uint32_t dword = 0; dword < plan.read_dwords; ++dword) { @@ -3373,8 +3368,8 @@ class Tracker { !EquivalentValue(m_program, low->Arg(1), high->Arg(1)) || !AvailableBefore(*low, *pointer) || !AvailableBefore(*high, *pointer) || !MatchTableOffset(low->Arg(1), key, indirect.table_offset, indirect.table_stride) || - ((uint64_t {indirect.table_offset} + low_memory->offset) & ~uint64_t {3}) + 4u != - ((uint64_t {indirect.table_offset} + high_memory->offset) & ~uint64_t {3}) || + uint64_t {indirect.table_offset & ~3u} + (low_memory->offset & ~3u) + 4u != + uint64_t {indirect.table_offset & ~3u} + (high_memory->offset & ~3u) || indirect.table_stride < 8u || (indirect.table_stride & 3u) != 0u || !SetExactTableMaximum(key, indirect) || (key.TryInstruction() != nullptr && !AvailableBefore(*key.Instruction(), handle)) || @@ -3581,16 +3576,16 @@ class Tracker { if (memory == nullptr || memory->kind != ResourceKind::ScalarAddress || !ImmediateU32(read->Arg(1), immediate) || memory->offset > INT32_MAX) return false; const auto* current = read->Arg(0).Resolve().TryInstruction(); - const auto offset = immediate + memory->offset; - if (current == nullptr || current->GetOpcode() != ValueOpcode::GetAddressResource || + const auto offset = uint64_t {immediate & ~3u} + (memory->offset & ~3u); + if (offset > UINT32_MAX || current == nullptr || current->GetOpcode() != ValueOpcode::GetAddressResource || current->NumArgs() < 2u || - (dword == 0u ? (offset & 3u) != 0u - : !EquivalentValue(m_program, Value(const_cast(pointer)), - Value(const_cast(current))) || - offset != record_offset + dword * 4u)) return false; + (dword != 0u && + (!EquivalentValue(m_program, Value(const_cast(pointer)), + Value(const_cast(current))) || + offset != uint64_t {record_offset} + dword * 4u))) return false; if (dword == 0u) { pointer = current; - record_offset = offset; + record_offset = static_cast(offset); } record_reads[dword] = read; } @@ -3614,8 +3609,8 @@ class Tracker { !EquivalentValue(m_program, low->Arg(0), high->Arg(0)) || !EquivalentValue(m_program, low->Arg(1), high->Arg(1)) || !MatchTableOffset(low->Arg(1), row_key, indirect.table_offset, indirect.table_stride) || - ((uint64_t {indirect.table_offset} + low_memory->offset) & ~uint64_t {3}) + 4u != - ((uint64_t {indirect.table_offset} + high_memory->offset) & ~uint64_t {3}) || + uint64_t {indirect.table_offset & ~3u} + (low_memory->offset & ~3u) + 4u != + uint64_t {indirect.table_offset & ~3u} + (high_memory->offset & ~3u) || row_key.IsEmpty() || indirect.table_stride < 8u || (indirect.table_stride & 3u) != 0u || !MakeRuntimeTableSource(*low, table_source) || table_source.dword_count != 4u) return false; indirect.table_immediate = low_memory->offset; @@ -3629,12 +3624,12 @@ class Tracker { functions = body.aliases; } } - if (uint64_t {element_offset} + element_immediate > UINT32_MAX) return false; + if (uint64_t {element_offset & ~3u} + (element_immediate & ~3u) > UINT32_MAX) return false; indirect.pointer_table = DescriptorSource::IndirectDescriptor::PointerTable { .offset = record_offset, .buffer = true, .element_stride = element_stride, - .element_offset = (element_offset + element_immediate) & ~3u, + .element_offset = (element_offset & ~3u) + (element_immediate & ~3u), .function = function, .functions = std::move(functions)}; DescriptorSource source; @@ -3782,6 +3777,7 @@ class Tracker { plan.retain_reads = true; } else if (table_source.dword_count == 2u) { if (table_mask != UINT32_MAX) return false; + indirect.table_offset &= ~3u; auto guarded_count = UnsignedBoundOnEntry(key, handle.Parent()); if (guarded_count.IsEmpty()) guarded_count = UnsignedResourceBound(key, handle); if (guarded_count.IsEmpty()) guarded_count = UnsignedBoundOnEntry(key, handle.Parent(), true); @@ -3852,7 +3848,6 @@ class Tracker { else if (!ProgramLoopCount(key, indirect)) return false; } - if ((table_offset & 3u) != 0u) return false; } else { const auto* address = !plan.table_indexed && plan.reads[0] != nullptr ? plan.reads[0]->Arg(1).Resolve().TryInstruction() : nullptr; @@ -3860,7 +3855,9 @@ class Tracker { uint32_t key_memory_index = 0; const auto* key_memory = key_read != nullptr ? ScalarReadMemory(*key_read, key_memory_index) : nullptr; - const auto table_base = uint64_t {table_offset} + table_immediate; + const auto table_base = plan.table_indexed + ? uint64_t {table_offset} + table_immediate + : uint64_t {table_offset & ~3u} + (table_immediate & ~3u); const bool table_array = !sampler && indirect.workgroup_axis == UINT32_MAX && table_stride == 32u && (key_memory == nullptr || key_memory->offset <= INT32_MAX) && @@ -4560,11 +4557,12 @@ class Tracker { (table != nullptr && !EquivalentValue(m_program, Value(const_cast(table)), Value(const_cast(current)))) || - !MatchTableOffset(read->Arg(1), current_key, offset, stride) || stride != 16u || - memory->offset > UINT32_MAX - offset) { + !MatchTableOffset(read->Arg(1), current_key, offset, stride) || stride != 16u) { return false; } - offset += memory->offset; + const auto aligned = uint64_t {offset & ~3u} + (memory->offset & ~3u); + if (aligned > UINT32_MAX) return false; + offset = static_cast(aligned); if (dword == 0u) { key = current_key; table_offset = offset; diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp b/core/kyty/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp index f80e0b0ce93..6f8b2316ee2 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp +++ b/core/kyty/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp @@ -324,7 +324,7 @@ void Visit(Program& program, ShaderStageInputInfo input_info, InputUsage& inputs ? inst.Arg(1).Resolve() : Value {}; const bool constant = offset.IsImmediate() && offset.GetType() == Type::U32 && - (static_cast(offset.U32() & ~3u) + memory.offset + sizeof(uint32_t) <= + (static_cast(offset.U32() & ~3u) + (memory.offset & ~3u) + sizeof(uint32_t) <= UniformBufferBytes - UniformBufferBaseSlack); if (!constant) { inputs.not_constant[memory.resource] = true; diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/SrtWalker.cpp b/core/kyty/graphics/shader/recompiler/ir/passes/SrtWalker.cpp index 3d5397db77b..0751f98c7cb 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/SrtWalker.cpp +++ b/core/kyty/graphics/shader/recompiler/ir/passes/SrtWalker.cpp @@ -1309,17 +1309,13 @@ void WalkerCompiler::EmitRead(const Node& node, uint32_t index) { } if (!args.empty()) { for (const auto& arg: args) Branch(arg, m_ret); - const auto raw_immediate = - static_cast(static_cast(m_plan.memory_info[inst.Flags().index].offset)); - const auto scalar_buffer = op == ValueOpcode::ReadConstBuffer && (raw_immediate & 3) != 0; - const auto immediate = raw_immediate & ~int64_t {3}; - const auto constant = scalar_buffer - ? (int64_t {static_cast(args[2].value)} + raw_immediate) & ~int64_t {3} - : int64_t {static_cast(args[2].value) & ~3u} + immediate; + const auto immediate = + static_cast(static_cast(m_plan.memory_info[inst.Flags().index].offset)) & + ~int64_t {3}; + const auto constant = int64_t {static_cast(args[2].value) & ~3u} + immediate; const bool folded = args[2].kind == Kind::Constant && constant + 4 <= INT32_MAX; const auto offset = folded ? Xbyak::RegExp(static_cast(constant)) - : scalar_buffer ? Xbyak::RegExp(c.r9) - : c.r9 + static_cast(immediate); + : c.r9 + static_cast(immediate); if (args[0].kind == Kind::UserData && args[1].kind == Kind::UserData) { c.mov(c.rax, c.qword[At(m_bases.at({args[0].value, args[1].value}))]); } else { @@ -1327,13 +1323,7 @@ void WalkerCompiler::EmitRead(const Node& node, uint32_t index) { } if (!folded) { Load(c.r9, args[2]); - if (scalar_buffer) { - c.mov(c.r9d, c.r9d); - c.add(c.r9, static_cast(raw_immediate)); - c.and_(c.r9, ~3u); - } else { - c.and_(c.r9d, ~3u); - } + c.and_(c.r9d, ~3u); } c.lea(c.r10, c.ptr[c.rax + offset]); if (op == ValueOpcode::LoadAddressU32) { diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/TableMode.cpp b/core/kyty/graphics/shader/recompiler/ir/passes/TableMode.cpp index c60b597610e..95055fa5252 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/TableMode.cpp +++ b/core/kyty/graphics/shader/recompiler/ir/passes/TableMode.cpp @@ -74,7 +74,7 @@ bool EnterTableMode(Program& program, std::string& reason) { return refuse("an SRT slot that is no scalar buffer load"); const auto low = TableOperand(handle->Arg(0), slot), high = TableOperand(handle->Arg(1), slot), records = TableOperand(handle->Arg(2), slot); - const auto bytes = (uint64_t {static_cast(memory.offset)} + offset.U32()) & ~uint64_t {3}; + const auto bytes = uint64_t {memory.offset & ~3u} + (offset.U32() & ~3u); if (!low || !high || !records || bytes > INT32_MAX) return refuse("an SRT slot address table mode cannot evaluate"); plan.slots.push_back({*low, *high, TablePlan::Operand {}, static_cast(bytes), *records, true}); diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/UniformScalarLoads.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/UniformScalarLoads.cpp index 731d504f11f..07d1d2154ec 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/UniformScalarLoads.cpp +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/UniformScalarLoads.cpp @@ -268,6 +268,88 @@ void TableRead(bool robust) { name + "the uniform view is declared in the Uniform storage class"); } +void RecordTableAlignedOffsets() { + std::fill(g_guest.begin(), g_guest.end(), 0u); + const uint64_t pointer_table = SrtAddress + 0x400u; + const std::array records {ConstantAddress + 0x400u, ConstantAddress + 0x500u}; + const std::array elements {SrtAddress + 0x800u, SrtAddress + 0x900u}; + const std::array images {MakeTexture(TextureA, Format8888), MakeTexture(TextureB, Format8888)}; + std::array keys {}; + for (size_t row = 0; row < records.size(); ++row) { + Poke(pointer_table + row * 16u, static_cast(records[row])); + Poke(pointer_table + row * 16u + 4u, static_cast(records[row] >> 32u)); + const auto sharp = MakeSharp(elements[row], 32u, Format32UInt, SwizzleXyzw, 3u); + keys[row] = sharp[0]; + for (size_t word = 0; word < sharp.size(); ++word) Poke(records[row] + word * 4u, sharp[word]); + for (size_t word = 0; word < images[row].size(); ++word) + Poke(elements[row] + word * 4u, images[row][word]); + } + std::array user_data {}; + const auto pointer_sharp = MakeSharp(pointer_table, 32u, Format32UInt, SwizzleXyzw, 3u); + std::copy(pointer_sharp.begin(), pointer_sharp.end(), user_data.begin()); + user_data[12] = 1u; + const std::vector code { + 0x7e040f00u, 0x7e180502u, 0x8f0d840cu, 0xf4240100u, 0x1a000000u, WaitAll, 0xb00e0003u, + 0xf4080202u, 0x1c000001u, WaitAll, 0xf42c0404u, 0xfa000000u, WaitAll, + 0x7e040280u, 0x7e060280u, 0xf0001108u, 0x00040402u, WaitAll, + 0xf800180fu, 0x04040404u, EndProgram, + }; + ShaderPixelInputInfo pixel {}; + pixel.ps_pos_x = true; + pixel.target_output_mode[0] = 1; + Recompiler::CompileOptions options; + options.stage = ShaderType::Pixel; + options.input_info.pixel = &pixel; + options.user_data = std::vector(16, 0u); + const auto source = Recompiler::PrepareShaderSource(code, options); + auto translated = Recompiler::TranslateProgram(source.decoded, options); + const auto plan = IR::ExtractResourcePlan(translated.program); + const IR::DescriptorSource::IndirectDescriptor* indirect = nullptr; + for (const auto& descriptor: plan.descriptor_sources) { + if (!descriptor.indirect_descriptor || !descriptor.indirect_descriptor->pointer_table || + !descriptor.indirect_descriptor->pointer_table->buffer) continue; + indirect = &*descriptor.indirect_descriptor; + break; + } + Check(indirect != nullptr, "the image is planned through a scalar record table"); + if (indirect == nullptr) return; + Check(indirect->pointer_table->offset == 0u && indirect->pointer_table->element_offset == 0u && + indirect->table_stride == 16u, + "a register offset of three and encoded offset of one select the first aligned record word"); + const IR::SrtRuntime runtime {.user_data = user_data, .read_specialization_memory = ReadMemory}; + IR::ResourceSnapshot snapshot; + IR::ResourceSpecialization specialization; + const bool materialized = IR::MaterializeResources(plan, runtime, snapshot, specialization); + Check(materialized, "both scalar record table rows materialize"); + if (!materialized) return; + for (const auto& image: images) { + const bool found = std::any_of(snapshot.images.begin(), snapshot.images.end(), + [&](const IR::DescriptorValue& descriptor) { + return descriptor.dword_count == image.size() && + std::equal(image.begin(), image.end(), descriptor.dwords.begin()); + }); + Check(found, "the scalar record table contains each image descriptor"); + } + Check(!specialization.images.empty(), "the scalar record table has an image specialization"); + if (specialization.images.empty()) return; + const size_t mapping_offset = specialization.images[0].indirect_mapping_offset; + const bool mapped = mapping_offset <= snapshot.flattened_srt.size() && + snapshot.flattened_srt.size() - mapping_offset >= 5u && + snapshot.flattened_srt[mapping_offset] == 2u; + Check(mapped, "the scalar record table has two distinct rows"); + if (mapped) { + for (const auto key: keys) { + const bool found = snapshot.flattened_srt[mapping_offset + 1u] == key || + snapshot.flattened_srt[mapping_offset + 3u] == key; + Check(found, "the scalar record table maps each record V# key"); + } + } + const auto compiled = Recompiler::CompileProgram(std::move(translated), options, specialization, 0); + std::string messages; + Check(!compiled.spirv.empty() && ValidateSpirv(compiled.spirv, messages), + "pixel shader with a scalar record table: " + messages); +} + void IndirectTypedLoad() { const std::vector code { 0xd760000cu, 0x00000500u, 0x870c810cu, 0x8f0c840cu, 0xf4280304u, 0x18000000u, WaitAll, @@ -299,15 +381,16 @@ const IR::Inst* ReadLaneSource(IR::Value value) { } } -enum class RecordIndex { UserData, FirstLane, Waterfall, CombinedOffsets, OverlappingOffsets }; +enum class RecordIndex { UserData, IndependentAlignment, FirstLane, Waterfall, CombinedOffsets, OverlappingOffsets }; void RuntimeOffsetDescriptors(RecordIndex index) { + const bool independent_alignment = index == RecordIndex::IndependentAlignment; const bool overlap = index == RecordIndex::OverlappingOffsets; const bool combined = index == RecordIndex::CombinedOffsets || overlap; const bool waterfall = index == RecordIndex::Waterfall || combined; - const bool wave_record = index != RecordIndex::UserData; - const uint32_t sampler_field = combined ? (overlap ? 1u : 5u) : waterfall ? 128u : 8u; - const uint32_t image_field = combined ? (overlap ? 4u : 1u) : waterfall ? 64u : 0u; + const bool wave_record = index != RecordIndex::UserData && !independent_alignment; + const uint32_t sampler_field = independent_alignment ? 3u : combined ? (overlap ? 1u : 5u) : waterfall ? 128u : 8u; + const uint32_t image_field = independent_alignment ? 7u : combined ? (overlap ? 2u : 1u) : waterfall ? 64u : 0u; std::vector code; uint32_t loop_start = 0; if (waterfall) { @@ -325,8 +408,10 @@ void RuntimeOffsetDescriptors(RecordIndex index) { constexpr uint32_t ReadFirstLaneS12 = 0x7e180502u; code = {ConvertPositionX, ReadFirstLaneS12}; } + code.push_back(waterfall ? 0x98eb0d0cu : 0x936bb00cu); + if (independent_alignment) code.push_back(0x806b816bu); code.insert(code.end(), { - waterfall ? 0x98eb0d0cu : 0x936bb00cu, 0xf4201a84u, 0xd6000000u | sampler_field, + 0xf4201a84u, 0xd6000000u | sampler_field, 0xf4201ac4u, 0xd6000000u | image_field, WaitAll, 0x8f6a846au, 0x8f6b856bu, 0xf4280600u, 0xd4000000u, 0xf42c0402u, 0xd6000000u, WaitAll, 0xf0800109u, 0x00c40400u, WaitAll, }); @@ -378,21 +463,21 @@ void RuntimeOffsetDescriptors(RecordIndex index) { }; bind_table(0, sampler_table, sizeof(samplers)); bind_table(4, image_table, sizeof(images)); - bind_table(8, ConstantAddress, combined ? 32u : waterfall ? 160u : 96u); + bind_table(8, ConstantAddress, independent_alignment ? 56u : combined ? 32u : waterfall ? 160u : 96u); if (waterfall) user_data[13] = combined ? 3u : 5u; const IR::SrtRuntime runtime {.user_data = user_data, .read_specialization_memory = ReadMemory}; IR::ResourceSpecialization specialization; for (uint32_t record = 0; record < 2u; ++record) { if (combined) { const auto address = ConstantAddress + record * 16u; - Poke(address, 7u); - Poke(address + 4u, overlap ? record : 0u); - Poke(address + 8u, overlap ? 7u : record); + Poke(address, overlap ? record : 0u); + Poke(address + 4u, overlap ? 7u : record); + Poke(address + 8u, 7u); } else { const auto address = ConstantAddress + (waterfall ? 4u + record * 16u : record * 48u); if (waterfall) Poke(address - 4u + sampler_field, 7u); - Poke(address + image_field, 1u - record); - Poke(address + sampler_field, record); + Poke(address + (independent_alignment ? 4u : image_field), 1u - record); + Poke(address + (independent_alignment ? 0u : sampler_field), record); } } IR::ResourceSnapshot snapshot; @@ -455,8 +540,10 @@ int main() { Common::SoftExitScope soft; IR::SetComputeIndirectFloors(256, 8); RuntimeOffsetDescriptors(RecordIndex::UserData); + RuntimeOffsetDescriptors(RecordIndex::IndependentAlignment); RuntimeOffsetDescriptors(RecordIndex::FirstLane); try { + RecordTableAlignedOffsets(); RuntimeOffsetDescriptors(RecordIndex::Waterfall); RuntimeOffsetDescriptors(RecordIndex::CombinedOffsets); RuntimeOffsetDescriptors(RecordIndex::OverlappingOffsets); diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/UniformScalarReplay.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/UniformScalarReplay.cpp index 03cea47abca..66243fcf956 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/UniformScalarReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/UniformScalarReplay.cpp @@ -247,29 +247,46 @@ int main(int argc, char** argv) { std::cerr << test.name << ": " << failure << '\n'; printTail(scalar.log); } - constexpr std::array combined_cases { - OffsetCase{Case{"combined offset in bounds", Input, 8u, 3u}, 1u, 4u}, - OffsetCase{Case{"combined offset outside", Input, 4u, 3u}, 1u, 4u}, - OffsetCase{Case{"combined offset without carry", Input, 8u, 2u}, 1u, 0u}, + constexpr std::array alignment_cases { + OffsetCase{Case{"separate offset in bounds", Input, 8u, 3u}, 1u, 0u}, + OffsetCase{Case{"separate offset at bound", Input, 4u, 3u}, 1u, 0u}, + OffsetCase{Case{"separate offset without carry", Input, 8u, 2u}, 1u, 0u}, }; - for (std::size_t index = 0; index < combined_cases.size(); ++index) { - const auto& offset_case = combined_cases[index]; - auto combined_words = ScalarWords; - combined_words[1] = 0x10000000u | offset_case.immediate; - auto single_words = ScalarWords; - single_words[1] = 0xfa000000u | offset_case.equivalent; - const auto combined = replay(tool, root / ("combined-" + std::to_string(index)), offset_case.test, - combined_words); - const auto single = replay(tool, root / ("single-" + std::to_string(index)), offset_case.test, - single_words); - if (combined.completed && single.completed && combined.frame == single.frame) { + for (std::size_t index = 0; index < alignment_cases.size(); ++index) { + const auto& offset_case = alignment_cases[index]; + auto offset_words = ScalarWords; + offset_words[1] = 0x10000000u | offset_case.immediate; + auto reference_words = ScalarWords; + reference_words[1] = 0xfa000000u | offset_case.equivalent; + const auto offset = replay(tool, root / ("offset-" + std::to_string(index)), offset_case.test, + offset_words); + const auto reference = replay(tool, root / ("reference-" + std::to_string(index)), offset_case.test, + reference_words); + if (offset.completed && reference.completed && offset.frame == reference.frame) { std::cout << offset_case.test.name << ": ok\n"; continue; } ++failures; - std::cerr << offset_case.test.name << ": combining the register and immediate offsets changed the scalar load\n"; - printTail(combined.log); - printTail(single.log); + std::cerr << offset_case.test.name << ": separate register and immediate alignment changed the scalar load\n"; + printTail(offset.log); + printTail(reference.log); + } + const Case raw_case{"separate raw address offsets", Input, 0x100u, 3u}; + auto raw_words = ScalarWords; + raw_words[0] = 0xf4000400u; + raw_words[1] = 0x10000001u; + raw_words[2] = 0xf4000440u; + auto buffer_words = ScalarWords; + buffer_words[1] = 0xfa000000u; + const auto raw = replay(tool, root / "raw-offset", raw_case, raw_words); + const auto buffer = replay(tool, root / "buffer-reference", raw_case, buffer_words); + if (raw.completed && buffer.completed && raw.frame == buffer.frame) { + std::cout << raw_case.name << ": ok\n"; + } else { + ++failures; + std::cerr << raw_case.name << ": separate raw address alignment changed the scalar load\n"; + printTail(raw.log); + printTail(buffer.log); } if (failures != 0) return 1; std::filesystem::remove_all(root); diff --git a/docs/dev/debt/changes/fix-kyty-sbuffer-offset-alignment.md b/docs/dev/debt/changes/fix-kyty-sbuffer-offset-alignment.md index 0fba22f7ca5..d35d24f6383 100644 --- a/docs/dev/debt/changes/fix-kyty-sbuffer-offset-alignment.md +++ b/docs/dev/debt/changes/fix-kyty-sbuffer-offset-alignment.md @@ -2,4 +2,4 @@ ## add Functional -- [Scalar buffer load offsets](../../../core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp) have not been measured on PS5 hardware when the low bits of `SOFFSET` and the instruction immediate carry into the next dword. The implementation combines the byte offsets before alignment as [RDNA2 ISA section 7.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) specifies. Synthetic replay covers a carry, no carry and a crossed bound; the console result remains unverified. Closes when a PS5 hardware oracle measures those cases, including a multi-dword load at the bound. +- [Scalar buffer load offsets](../../../core/kyty/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cpp) have not been measured on PS5 hardware when the low bits of `SOFFSET` and the instruction immediate would carry into the next dword. The implementation masks each operand before addition, matching the [Mesa ACO SMEM rule](https://chromium.googlesource.com/external/gitlab.freedesktop.org/mesa/mesa/+/fff0e3f85c4fbf87bc7cfe5be2544e831c584ca1/src/amd/compiler/aco_optimizer.cpp#1905) and the RDNA2 measurements in [issue #216](https://github.com/simnJS/AnyPS5/issues/216). The RDNA2 ISA's buffered-address pseudocode suggests a final mask instead. Synthetic replay covers carry, no-carry and a crossed bound. Closes when a PS5 hardware oracle measures the cases, including a multi-dword load at the bound. From 8a26fbfd3a0ee653c7d726c43757125e39ef051c Mon Sep 17 00:00:00 2001 From: mjnhbg3 <2287071+mjnhbg3@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:32:47 -0500 Subject: [PATCH 2/2] fix(kyty): classify wave scalar reads from complete offsets --- .../ir/passes/RayQueryTraversal.cpp | 54 ++++++++++++++++--- .../recompiler/ir/passes/RayQueryTraversal.h | 4 ++ .../KytyShim/tests/RtOracle.cpp | 33 ++++++++++++ 3 files changed, 84 insertions(+), 7 deletions(-) diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.cpp b/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.cpp index 9597fac4d3e..064371fc0fa 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.cpp +++ b/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.cpp @@ -73,6 +73,40 @@ std::optional Immediate(Value value) { return value.U32(); } +std::optional LowThreeBits(Value value, uint32_t depth = 0u) { + if (depth >= 16u) return std::nullopt; + if (const auto immediate = Immediate(value)) return *immediate & 7u; + const auto* inst = value.Resolve().TryInstruction(); + if (inst == nullptr) return std::nullopt; + switch (inst->GetOpcode()) { + case ValueOpcode::IAdd32: { + const auto left = LowThreeBits(inst->Arg(0), depth + 1u); + const auto right = LowThreeBits(inst->Arg(1), depth + 1u); + if (left && right) return (*left + *right) & 7u; + return std::nullopt; + } + case ValueOpcode::ShiftLeftLogical32: { + const auto shift = Immediate(inst->Arg(1)); + if (!shift) return std::nullopt; + const auto count = *shift & 31u; + if (count >= 3u) return 0u; + const auto low = LowThreeBits(inst->Arg(0), depth + 1u); + if (low) return (*low << count) & 7u; + return std::nullopt; + } + case ValueOpcode::BitwiseAnd32: { + const auto left = Immediate(inst->Arg(0)); + const auto right = Immediate(inst->Arg(1)); + if ((left && (*left & 7u) == 0u) || (right && (*right & 7u) == 0u)) return 0u; + const auto low_left = LowThreeBits(inst->Arg(0), depth + 1u); + const auto low_right = LowThreeBits(inst->Arg(1), depth + 1u); + if (low_left && low_right) return *low_left & *low_right; + return std::nullopt; + } + default: return std::nullopt; + } +} + std::optional Slot(Value value) { const auto* read = Producer(value, ValueOpcode::ReadConst); return read != nullptr ? Immediate(read->Arg(1)) : std::nullopt; @@ -1456,6 +1490,18 @@ uint32_t TraceTraversalsWithRayQueries(Program& program) { return traced; } +std::optional WaveScalarReadKind(const Program& program, const Inst& read) { + if (read.GetOpcode() != ValueOpcode::ReadConstBuffer || read.NumArgs() < 2u) return std::nullopt; + const auto index = read.Flags().index; + if (index >= program.memory_info.size()) return std::nullopt; + const auto low = LowThreeBits(read.Arg(1)); + if (!low) return std::nullopt; + const auto at = ((*low & ~3u) + (program.memory_info[index].offset & ~3u)) & 7u; + return at == 0u ? std::optional(RayQueryResultKind::Node) + : at == 4u ? std::optional(RayQueryResultKind::Word) + : std::nullopt; +} + namespace { @@ -3993,13 +4039,7 @@ std::optional WaveResultKind(const Program& program, const L (base->GetOpcode() == ValueOpcode::CompositeConstructU64 && resource->Arg(0).Resolve() == base->Arg(0).Resolve())); if (!blas || !InLoop(program, value->Parent(), s.wave_header, s.wave_latch)) return std::nullopt; - auto at = MemoryOf(program, *value).offset & ~3u; - if (const auto* add = Producer(value->Arg(1), ValueOpcode::IAdd32); add != nullptr) - at += Immediate(add->Arg(0)).value_or(Immediate(add->Arg(1)).value_or(0u)) & ~3u; - at &= 7u; - return at == 0u ? std::optional(RayQueryResultKind::Node) - : at == 4u ? std::optional(RayQueryResultKind::Word) - : std::nullopt; + return WaveScalarReadKind(program, *value); } const auto* mul = Producer(Canonical(Value(const_cast(value))), ValueOpcode::FPMul32); for (uint32_t side = 0; mul != nullptr && side < 2; ++side) { diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.h b/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.h index 191e8bb8ab3..1f4de3bfd5b 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.h +++ b/core/kyty/graphics/shader/recompiler/ir/passes/RayQueryTraversal.h @@ -1,8 +1,10 @@ #pragma once +#include "graphics/shader/recompiler/ir/RayQuery.h" #include "graphics/shader/recompiler/ir/ShaderIR.h" #include +#include #include #include @@ -14,6 +16,8 @@ namespace Libs::Graphics::ShaderRecompiler::IR { [[nodiscard]] uint32_t TraceTraversalsWithRayQueries(Program& program); +[[nodiscard]] std::optional WaveScalarReadKind(const Program& program, const Inst& read); + constexpr uint32_t OracleImprovementMask = 1u << 1; struct OracleImprovement { diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/RtOracle.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/RtOracle.cpp index 554bc4d2e8c..6cffe1d2338 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/RtOracle.cpp +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/RtOracle.cpp @@ -2,6 +2,7 @@ #include "graphics/shader/recompiler/ir/Block.h" #include "graphics/shader/recompiler/ir/RayQuery.h" #include "graphics/shader/recompiler/ir/passes/RayQueryOracle.h" +#include "graphics/shader/recompiler/ir/passes/RayQueryTraversal.h" #include #include @@ -148,6 +149,37 @@ void NodeCountFacts() { "the BLAS fact changes bit 31 only"); } +void WaveScalarReadKindFacts() { + IR::Program program; + program.memory_info.push_back({.kind = IR::ResourceKind::ScalarBuffer, .offset = 0u}); + IR::Block block; + const auto read = [&](IR::Value offset) -> IR::Inst& { + return block.AppendNewInst(IR::ValueOpcode::ReadConstBuffer, {IR::Value(0u), offset}); + }; + auto& carried = block.AppendNewInst(IR::ValueOpcode::IAdd32, {IR::Value(3u), IR::Value(1u)}); + Expect(IR::WaveScalarReadKind(program, read(IR::Value(&carried))) == IR::RayQueryResultKind::Word, + "a carry inside the register operand selects the second word"); + auto& dynamic = block.AppendNewInst(IR::ValueOpcode::GetUserData, {IR::Value(static_cast(0u))}); + auto& unknown = block.AppendNewInst(IR::ValueOpcode::IAdd32, {IR::Value(&dynamic), IR::Value(1u)}); + Expect(!IR::WaveScalarReadKind(program, read(IR::Value(&unknown))), + "an unknown register residue cannot identify a wave result word"); + auto& aligned = block.AppendNewInst(IR::ValueOpcode::ShiftLeftLogical32, {IR::Value(&dynamic), IR::Value(3u)}); + auto& first = block.AppendNewInst(IR::ValueOpcode::IAdd32, {IR::Value(&aligned), IR::Value(1u)}); + auto& second = block.AppendNewInst(IR::ValueOpcode::IAdd32, {IR::Value(&aligned), IR::Value(4u)}); + Expect(IR::WaveScalarReadKind(program, read(IR::Value(&first))) == IR::RayQueryResultKind::Node, + "a proven aligned register plus one selects the first word"); + Expect(IR::WaveScalarReadKind(program, read(IR::Value(&second))) == IR::RayQueryResultKind::Word, + "a proven aligned register plus four selects the second word"); + auto& masked = block.AppendNewInst(IR::ValueOpcode::BitwiseAnd32, {IR::Value(&dynamic), IR::Value(~7u)}); + auto& masked_second = block.AppendNewInst(IR::ValueOpcode::IAdd32, {IR::Value(&masked), IR::Value(4u)}); + Expect(IR::WaveScalarReadKind(program, read(IR::Value(&masked_second))) == IR::RayQueryResultKind::Word, + "masking the register low bits proves the second word"); + auto& condition = block.AppendNewInst(IR::ValueOpcode::INotEqual32, {IR::Value(&dynamic), IR::Value(0u)}); + auto& selected = block.AppendNewInst(IR::ValueOpcode::SelectU32, {IR::Value(&condition), IR::Value(&aligned), IR::Value(5u)}); + Expect(!IR::WaveScalarReadKind(program, read(IR::Value(&selected))), + "a selected aligned or unaligned register remains unclassified"); +} + void TriangleIndexSpirv() { namespace Emit = Spirv::Emitter; const IR::Value unused(0u); @@ -194,6 +226,7 @@ int main() { EmptyWalks(); Modes(); NodeCountFacts(); + WaveScalarReadKindFacts(); TriangleIndexSpirv(); if (failures != 0) { std::fprintf(stderr, "%d check(s) failed\n", failures);