Triforce v0.8.0

Evil HD (SMAA Ultra, 16x filtering, full textures, ambient occlusion with bounce light, sunlight shafts, foliage drawn 4x as far, the remastered texture pack's loader and the launcher's download of it), FSR 3.1 frame generation for every GPU, Intel XeSS, FSR 4 model choice, ReShade presets, Auto (this PC), HUD placement, the options menu in 13 languages, a second input for every control, hold to toggle, DualSense speaker and haptics, NFC from the player's own dumps, the above-60 fps game fixes, the Debug tab's flight and Inventory fixes, the launcher's full settings, and over 250 fixes.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-25 10:21:32 -06:00
parent 861702476a
commit 4fa4f9188b
881 changed files with 179428 additions and 15581 deletions

View File

@@ -169,6 +169,13 @@ void Traverse(EmitContext& ctx, IR::Program& program) {
ctx.OpAtomicIAdd(ctx.U32[1], counter, ctx.Const(static_cast<u32>(spv::Scope::Device)), ctx.u32_zero_value,
ctx.Const(1U));
}
if (ctx.wmma16_fused.active) {
if (ctx.wmma16_fused.skip_insts.contains(&inst)) continue;
if (inst.GetOpcode() == IR::Opcode::MatrixMulAddF16) {
EmitMatrixMulAddF16Fused(ctx, &inst);
continue;
}
}
EmitInst(ctx, &inst);
}
break;
@@ -176,6 +183,8 @@ void Traverse(EmitContext& ctx, IR::Program& program) {
case IR::AbstractSyntaxNode::Type::If: {
const Id if_label{node.data.if_node.body->Definition<Id>()};
const Id endif_label{node.data.if_node.merge->Definition<Id>()};
// (Triforce: the shared warp's region, said before the merge instruction, which must stand right before its branch)
WarpOpenRegion(ctx, node.data.if_node.body, ctx.Def(node.data.if_node.cond));
ctx.OpSelectionMerge(endif_label, spv::SelectionControlMask::MaskNone);
ctx.OpBranchConditional(ctx.Def(node.data.if_node.cond), if_label, endif_label);
break;
@@ -196,6 +205,7 @@ void Traverse(EmitContext& ctx, IR::Program& program) {
break;
}
case IR::AbstractSyntaxNode::Type::EndIf:
WarpCloseRegion(ctx);
if (current_block) {
ctx.OpBranch(node.data.end_if.merge->Definition<Id>());
}
@@ -509,9 +519,11 @@ void SetupCapabilities(const Profile& profile, const Info& info, EmitContext& ct
ctx.AddExtension("SPV_KHR_shader_draw_parameters");
ctx.AddCapability(spv::Capability::DrawParameters);
}
// (Triforce: not for a stage on the shared warp, which has no subgroup instruction; its check keeps them)
const bool subgroup_free{ctx.warp_shared && !ctx.warp_shared_check};
if ((info.uses_subgroup_vote || info.uses_subgroup_invocation_id ||
info.uses_subgroup_shuffles || info.uses_subgroup_mask) &&
profile.support_vote && profile.SupportsSubgroupStage(ctx.stage)) {
profile.support_vote && profile.SupportsSubgroupStage(ctx.stage) && !subgroup_free) {
ctx.AddCapability(spv::Capability::GroupNonUniformBallot);
ctx.AddCapability(spv::Capability::GroupNonUniformShuffle);
if (info.uses_subgroup_shuffles && profile.support_shuffle_relative) {
@@ -684,6 +696,12 @@ void PatchMeshInstructions(std::vector<u32>& code, const EmitContext& ctx) {
std::vector<u32> EmitSPIRV(const Profile& profile, const RuntimeInfo& runtime_info, IR::Program& program, Bindings& bindings) {
EmitContext ctx{profile, runtime_info, program, bindings};
if (program.info.uses_cooperative_matrix && mma_software) DefineSoftwareMatrixFunction(ctx);
if (program.info.uses_cooperative_matrix && !mma_software && mma_wmma16) {
if (!DefineWmma16MatrixFunction(ctx, program))
DefineSoftwareMatrixFunction(ctx); // (the tiles do not fit the shared memory)
else if (mma_wmma16_fused)
DefineWmma16PairFunction(ctx, program);
}
Id main{};
if (runtime_info.mesh_fallback_vertex) { // (hookshot: the fallback's generated vertex stage, which reads the records)
const Id void_function{ctx.TypeFunction(ctx.void_id)};

View File

@@ -10,6 +10,7 @@
#include "common/common_types.h"
#include "shader_recompiler/backend/bindings.h"
#include "shader_recompiler/backend/spirv/mma_layout.h"
#include "shader_recompiler/frontend/ir/program.h"
#include "shader_recompiler/profile.h"
#include "shader_recompiler/runtime_info.h"
@@ -68,12 +69,75 @@ constexpr u32 MESH_FALLBACK_ALLOC_WORD = 4; // (records taken, past the en
// a count from the GPU (DrawMeshTasksIndirect, the floor grass) the host knew none, and dispatched no mesh workgroup)
constexpr u32 MESH_FALLBACK_DISPATCH_WORD = 5;
constexpr u32 MESH_FALLBACK_HEADER_WORDS = 8;
constexpr u32 MESH_FALLBACK_RECORD_WORDS = 16u << 20; // (64 MB: ~47k grass primitives of 31 words are 17 MB)
// (128 MB. Every program takes records from it, so a program with longer records fits fewer: MeshFallbackFit. At 16M words
// the floor grass at the Grass distance's 4x lost its blades: their program's records are 22 words and fit 762600,
// its partner's 7 words, and each drew ~1.02M records a frame, so the blades past the fit were left out and drawn white.
// 32M words fit 1.52M of 22 words)
constexpr u32 MESH_FALLBACK_RECORD_WORDS = 32u << 20;
// (emit_spirv_mesh.cpp BufferWordAt makes a word's byte offset in 32 bits)
static_assert((u64{MESH_FALLBACK_HEADER_WORDS} + MESH_FALLBACK_RECORD_WORDS) * 4 < (u64{1} << 32));
// (Triforce, mma_layout.h mesh_fallback_global_attributes) the mesh workgroups' attribute regions out of workgroup memory: a pool
// after the records, in the same buffer. Its header is a ticket counter and a word a slot, the ticket generation that may take
// that slot next (both zeroed before each draw, with the records' header); then the slots, each one workgroup's region
constexpr u64 MESH_FALLBACK_POOL_OFFSET = u64{MESH_FALLBACK_RECORD_WORDS} * 4 + 4096; // (past the header and the records)
constexpr u32 MESH_FALLBACK_POOL_SLOTS = 1024; // (a power of two: a ticket's slot is its low bits)
constexpr u32 MESH_FALLBACK_POOL_SLOT_SHIFT = 10;
constexpr u32 MESH_FALLBACK_POOL_HEADER_BYTES = 8192; // (the counter and a word a slot: 4100 bytes)
constexpr u32 MESH_FALLBACK_POOL_SLOT_BYTES = 32768; // (the largest region a slot holds; a larger one stays in workgroup memory)
constexpr u64 MESH_FALLBACK_POOL_BYTES = MESH_FALLBACK_POOL_HEADER_BYTES + u64{MESH_FALLBACK_POOL_SLOTS} * MESH_FALLBACK_POOL_SLOT_BYTES;
constexpr u32 MESH_FALLBACK_POOL_WAIT = 1u << 20; // (a wait for a slot's last holder gives up after this many reads)
static_assert((MESH_FALLBACK_POOL_SLOTS >> MESH_FALLBACK_POOL_SLOT_SHIFT) == 1 && MESH_FALLBACK_POOL_HEADER_BYTES >= 4 + MESH_FALLBACK_POOL_SLOTS * 4);
static_assert(MESH_FALLBACK_POOL_OFFSET >= (u64{MESH_FALLBACK_HEADER_WORDS} + MESH_FALLBACK_RECORD_WORDS) * 4);
// (Triforce, mma_layout.h mesh_fallback_shared_warp) the shared warp's words in workgroup memory: an if with a warp operation
// inside has the lanes that entered it and those that reached it; a ballot or a vote its lanes and those that arrived; a shuffle
// a value a lane and those that arrived, or one value where the source lane is a constant
constexpr u32 WARP_REGION_WORDS = 2;
constexpr u32 WARP_BALLOT_WORDS = 2;
constexpr u32 WARP_SHUFFLE_WORDS = 33;
constexpr u32 WARP_BROADCAST_WORDS = 2;
constexpr u32 WARP_WAIT = 1u << 16; // (a wait for other lanes gives up after this many reads: a wrong word, not a hung GPU)
// (its counters, four words right past the records buffer's regular end, which vk_draw.cpp fallback_buffers_of adds and
// clears when the shared warp or the attribute pool is on: the waits that gave up, with RX_VK_MESH_SHARED_WARP_CHECK the
// answers compared with the subgroup's and those that differed, and the attribute pool's waits for a slot that gave up
// (mma_layout.h mesh_fallback_global_attributes). They only grow and wrap; fallback_warp_counters logs them)
constexpr u32 WARP_COUNTER_BYTES = 16;
constexpr u32 WARP_COUNTER_WAITS = 0;
constexpr u32 WARP_COUNTER_COMPARED = 4;
constexpr u32 WARP_COUNTER_DIFFERENT = 8;
constexpr u32 WARP_COUNTER_POOL_WAITS = 12;
// (the largest records buffer vk_draw.cpp fallback_buffers_of makes, a recording thread's: past it, every program is left
// without the fallback. The largest layout, the records with the attribute pool and the counters, ~160 MB, fits)
constexpr u64 MESH_FALLBACK_RECORDS_LIMIT = 192ull << 20;
static_assert(MESH_FALLBACK_POOL_OFFSET + MESH_FALLBACK_POOL_BYTES + WARP_COUNTER_BYTES <= MESH_FALLBACK_RECORDS_LIMIT);
/// Whether the records buffer carries those counters past its regular end: the shared warp's and the pool's waits count there
[[nodiscard]] inline bool MeshFallbackCounters() {
return mesh_fallback_shared_warp || mesh_fallback_global_attributes;
}
/// The fallback's records buffer without those counters: the header and the records, and the attribute regions' pool where
/// mma_layout.h mesh_fallback_global_attributes is on
[[nodiscard]] inline u64 MeshFallbackRecordsBytes() {
return mesh_fallback_global_attributes ? MESH_FALLBACK_POOL_OFFSET + MESH_FALLBACK_POOL_BYTES
: (u64{MESH_FALLBACK_HEADER_WORDS} + MESH_FALLBACK_RECORD_WORDS) * 4;
}
// (Triforce) how the records lie in their area (RuntimeInfo::mesh_fallback_layout, RX_VK_MESH_FB_LAYOUT):
// - Aos: record after record, a record's words together (word H + record * W + line). Neighbouring threads write words a
// record apart, so each store of a mesh workgroup touches as many cache lines as it has threads.
// - Soa: line after line, the area cut into W lines of `fit` words (word H + line * fit + record), and the threads take the
// records in turn, so neighbouring threads write neighbouring words. The same records, the same count, the same draw.
enum class MeshFallbackLayout : u32 { Aos = 0, Soa = 1 };
/// A line's words: the records of `record_words` words the area holds
[[nodiscard]] constexpr u32 MeshFallbackFit(u32 record_words) {
return MESH_FALLBACK_RECORD_WORDS / (record_words ? record_words : 1);
}
[[nodiscard]] std::vector<u32> EmitSPIRV(const Profile& profile, const RuntimeInfo& runtime_info, IR::Program& program, Bindings& bindings);
[[nodiscard]] inline std::vector<u32> EmitSPIRV(const Profile& profile, IR::Program& program) {
Bindings binding;
return EmitSPIRV(profile, {}, program, binding);
}
// (Triforce, AMD RDNA 3/4) whether HMMA_nx2 in the program runs on the WMMA 16x16x16 tiles (mma_layout.h mma_wmma16):
// every subgroup full and the tiles fit the shared memory of the device. Otherwise EmitSPIRV gives it the software multiply
[[nodiscard]] bool Wmma16Fits(const Profile& profile, const IR::Program& program);
} // namespace Shader::Backend::SPIRV

View File

@@ -372,8 +372,15 @@ Id EmitStorageAtomicExchange32x2(EmitContext& ctx, const IR::Value& binding,
Id EmitStorageAtomicAddF32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
Id value) {
if (ctx.native_f32_add) { // (hookshot) the GPU's own float add: one atomic, never given up (DefineStorageBuffers)
const Id pointer{StoragePointer(ctx, ctx.storage_types.F32, &StorageDefinitions::F32, binding, offset,
sizeof(f32))};
const auto [scope, semantics]{AtomicArgs(ctx)};
return ctx.OpAtomicFAddEXT(ctx.F32[1], pointer, scope, semantics, value);
}
const Id ssbo{ctx.ssbos[binding.U32()].U32};
const Id base_index{StorageIndex(ctx, offset, sizeof(u32))};
// Reducing operands first can overflow even when adding each to the stored value would not.
return ctx.OpFunctionCall(ctx.F32[1], ctx.f32_add_cas, base_index, value, ssbo);
}

View File

@@ -105,6 +105,11 @@ Id EmitFPMul16(EmitContext& ctx, IR::Inst* inst, Id a, Id b) {
}
Id EmitFPMul32(EmitContext& ctx, IR::Inst* inst, Id a, Id b) {
// ((Triforce) mma_layout.h mesh_fallback_strict_fmul: a * b as fma(a, b, -0.0), the same value to the last bit, which
// AMD's older Windows compiler does not take apart)
if (ctx.mesh_fallback && mesh_fallback_strict_fmul && inst->Flags<IR::FpControl>().no_contraction) {
return Decorate(ctx, inst, ctx.OpFma(ctx.F32[1], a, b, ctx.Const(-0.0f)));
}
return Decorate(ctx, inst, ctx.OpFMul(ctx.F32[1], a, b));
}

View File

@@ -264,7 +264,7 @@ Id TextureImage(EmitContext& ctx, IR::TextureInstInfo info, const IR::Value& ind
const Id idx{index.IsImmediate() ? ctx.Const(index.U32()) : ctx.Def(index)};
const bool non_uniform{
MarkNonUniform(ctx, idx, index, NonUniformKind::UniformTexelBuffer)};
const Id ptr{ctx.OpAccessChain(ctx.image_buffer_type, def.id, idx)};
const Id ptr{ctx.OpAccessChain(def.pointer_type, def.id, idx)};
const Id object{ctx.OpLoad(ctx.image_buffer_type, ptr)};
if (non_uniform) {
DecorateNonUniform(ctx, ptr);

View File

@@ -1,22 +1,52 @@
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <tuple>
#include "shader_recompiler/backend/spirv/emit_spirv_instructions.h"
#include "shader_recompiler/backend/spirv/spirv_emit_context.h"
#include "shader_recompiler/frontend/ir/modifiers.h"
namespace Shader::Backend::SPIRV {
namespace {
Id Image(EmitContext& ctx, IR::TextureInstInfo info) {
if (info.type == TextureType::Buffer) {
const ImageBufferDefinition def{ctx.image_buffers.at(info.descriptor_index)};
return def.id;
} else {
const ImageDefinition def{ctx.images.at(info.descriptor_index)};
return def.id;
void DecorateNonUniform(EmitContext& ctx, Id object) { // (as emit_spirv_image.cpp's)
if (ctx.non_uniform_ids.insert(object.value).second) {
ctx.Decorate(object, spv::Decoration::NonUniform);
}
}
// (Triforce) The image an atomic works on: the image itself, or for an array (count above 1, DefineImages and
// DefineImageBuffers) the element the texture pass's index picks, as Image() in emit_spirv_image.cpp takes it for loads and
// stores; nonuniform (true) where the profile indexes that kind of array so. A single image still takes no index
Id Image(EmitContext& ctx, IR::TextureInstInfo info, const IR::Value& index, bool& non_uniform) {
const bool buffer{info.type == TextureType::Buffer};
const auto [id, pointer_type, count]{[&] {
if (buffer) {
const ImageBufferDefinition& def{ctx.image_buffers.at(info.descriptor_index)};
return std::tuple{def.id, def.pointer_type, def.count};
}
const ImageDefinition& def{ctx.images.at(info.descriptor_index)};
return std::tuple{def.id, def.pointer_type, def.count};
}()};
non_uniform = false;
if (count <= 1) {
if (!index.IsImmediate() || index.U32() != 0) {
throw NotImplementedException("Image indexing");
}
return id;
}
const Id idx{index.IsImmediate() ? ctx.Const(index.U32()) : ctx.Def(index)};
const Id element{ctx.OpAccessChain(pointer_type, id, idx)};
non_uniform = !index.IsImmediate() && (buffer ? ctx.profile.support_storage_texel_buffer_array_nonuniform_indexing
: ctx.profile.support_storage_image_array_nonuniform_indexing);
if (non_uniform) {
DecorateNonUniform(ctx, idx);
DecorateNonUniform(ctx, element);
(buffer ? ctx.uses_nonuniform_storage_texel_buffer : ctx.uses_nonuniform_storage_image) = true;
}
return element;
}
std::pair<Id, Id> AtomicArgs(EmitContext& ctx) {
const Id scope{ctx.Const(static_cast<u32>(spv::Scope::Device))};
const Id semantics{ctx.u32_zero_value};
@@ -25,13 +55,13 @@ std::pair<Id, Id> AtomicArgs(EmitContext& ctx) {
Id ImageAtomicU32(EmitContext& ctx, IR::Inst* inst, const IR::Value& index, Id coords, Id value,
Id (Sirit::Module::*atomic_func)(Id, Id, Id, Id, Id)) {
if (!index.IsImmediate() || index.U32() != 0) {
// TODO: handle layers
throw NotImplementedException("Image indexing");
}
const auto info{inst->Flags<IR::TextureInstInfo>()};
const Id image{Image(ctx, info)};
bool non_uniform{};
const Id image{Image(ctx, info, index, non_uniform)};
const Id pointer{ctx.OpImageTexelPointer(ctx.image_u32, image, coords, ctx.Const(0U))};
if (non_uniform) {
DecorateNonUniform(ctx, pointer);
}
const auto [scope, semantics]{AtomicArgs(ctx)};
return (ctx.*atomic_func)(ctx.U32[1], pointer, scope, semantics, value);
}

View File

@@ -13,8 +13,10 @@
namespace Shader::IR {
enum class Attribute : u64;
enum class Patch : u64;
class Block;
class Inst;
class Value;
struct Program;
} // namespace Shader::IR
namespace Shader::Backend::SPIRV {
@@ -63,6 +65,7 @@ void EmitSetAttributeIndexed(EmitContext& ctx, Id offset, Id value, Id vertex);
Id EmitGetPatch(EmitContext& ctx, IR::Patch patch);
void EmitSetPatch(EmitContext& ctx, IR::Patch patch, Id value);
Id EmitIsbeRead(EmitContext& ctx, Id address);
Id EmitIsbeReadOutput(EmitContext& ctx, Id address);
void EmitIsbeWriteAttribute(EmitContext& ctx, Id address, Id value);
void EmitIsbeWriteMapU8(EmitContext& ctx, Id address, Id value);
void EmitIsbeWriteMapU32(EmitContext& ctx, const IR::Value& address, Id value);
@@ -113,6 +116,7 @@ void EmitWriteGlobalS16(EmitContext& ctx, Id address, Id value);
void EmitWriteGlobal32(EmitContext& ctx, Id address, Id value);
void EmitWriteGlobal64(EmitContext& ctx, Id address, Id value);
void EmitWriteGlobal128(EmitContext& ctx, Id address, Id value);
Id EmitStorageBufferLength(EmitContext& ctx, const IR::Value& binding);
Id EmitLoadStorageU8(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset);
Id EmitLoadStorageS8(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset);
Id EmitLoadStorageU16(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset);
@@ -616,6 +620,11 @@ Id EmitImageAtomicXor32(EmitContext& ctx, IR::Inst* inst, const IR::Value& index
Id value);
Id EmitImageAtomicExchange32(EmitContext& ctx, IR::Inst* inst, const IR::Value& index, Id coords,
Id value);
// (Triforce, mma_layout.h mesh_fallback_shared_warp: emit_spirv_warp.cpp) the shared warp's start in the entry block, and the
// region an if with a warp operation inside opens for its body
void WarpPrologue(EmitContext& ctx);
void WarpOpenRegion(EmitContext& ctx, const IR::Block* body, Id cond);
void WarpCloseRegion(EmitContext& ctx);
Id EmitLaneId(EmitContext& ctx);
Id EmitVoteAll(EmitContext& ctx, Id pred);
Id EmitVoteAny(EmitContext& ctx, Id pred);
@@ -637,6 +646,9 @@ Id EmitShuffleButterfly(EmitContext& ctx, IR::Inst* inst, Id value, Id index, Id
Id EmitQuadBroadcast(EmitContext& ctx, Id value, Id lane);
Id EmitMatrixMulAddF16(EmitContext& ctx, Id a, Id b, Id c);
void DefineSoftwareMatrixFunction(EmitContext& ctx);
bool DefineWmma16MatrixFunction(EmitContext& ctx, const IR::Program& program);
void DefineWmma16PairFunction(EmitContext& ctx, const IR::Program& program);
void EmitMatrixMulAddF16Fused(EmitContext& ctx, IR::Inst* inst);
Id EmitQuadSwap(EmitContext& ctx, Id value, Id direction);
Id EmitFSwizzleAdd(EmitContext& ctx, Id op_a, Id op_b, Id swizzle);
Id EmitDPdxFine(EmitContext& ctx, Id op_a);

View File

@@ -78,6 +78,16 @@ void WriteStorageByCasLoop(EmitContext& ctx, const IR::Value& binding, const IR:
}
} // Anonymous namespace
// ((Triforce) simulated turf, ir_opt/sim_turf_pool_pass.h) The descriptor's range in bytes. The simulated-turf lists take every
// cap from it: the producers' guards and the readers' bounds follow what is bound, a list of the renderer's own of any size or
// the game's own list (whose range is its header and its cap's records: the game's cap, exactly)
Id EmitStorageBufferLength(EmitContext& ctx, const IR::Value& binding) {
if (!binding.IsImmediate()) throw NotImplementedException("Dynamic storage buffer length");
const Id ssbo{ctx.ssbos[binding.U32()].U32};
const Id words{ctx.OpArrayLength(ctx.U32[1], ssbo, 0U)};
return ctx.OpShiftLeftLogical(ctx.U32[1], words, ctx.Const(2u));
}
// (hookshot) 8- and 16-bit loads through a pointer no storage buffer was found for: the aligned 32-bit word by the same
// search as LoadGlobal32, and the byte or half of it the address names (the console's loads are naturally aligned). They
// threw "not implemented": 30 of OoT's mesh programs (LoadGlobalS16) were left untranslated on every card, issue 351

View File

@@ -10,6 +10,7 @@
// epilogue (reached by every invocation, see structured_control_flow.cpp) hands them to Vulkan.
#include <algorithm>
#include <array>
#include <cstdlib>
#include <span>
@@ -20,6 +21,14 @@
namespace Shader::Backend::SPIRV {
namespace {
void Barrier(EmitContext& ctx) {
if (ctx.mesh_attributes_global) { // (Triforce: the attribute region in device memory, its writes seen across the workgroup too)
ctx.OpControlBarrier(ctx.Const(static_cast<u32>(spv::Scope::Workgroup)),
ctx.Const(static_cast<u32>(spv::Scope::Workgroup)),
ctx.Const(static_cast<u32>(spv::MemorySemanticsMask::AcquireRelease |
spv::MemorySemanticsMask::WorkgroupMemory |
spv::MemorySemanticsMask::UniformMemory)));
return;
}
ctx.OpControlBarrier(ctx.Const(static_cast<u32>(spv::Scope::Workgroup)),
ctx.Const(static_cast<u32>(spv::Scope::Workgroup)),
ctx.Const(static_cast<u32>(spv::MemorySemanticsMask::AcquireRelease |
@@ -166,6 +175,30 @@ void StoreWord(EmitContext& ctx, Id pointer, Id value) {
ctx.OpStore(pointer, value, spv::MemoryAccessMask::Aligned, 4U);
}
/// (Triforce, mma_layout.h mesh_fallback_global_attributes) word `index` of the attribute region: in the workgroup's pool slot, or in
/// workgroup memory as before
Id LoadAttribute(EmitContext& ctx, Id index) {
if (ctx.mesh_attributes_global) {
return LoadWord(ctx, BufferWordAt(ctx, ctx.mesh_attribute_base, index));
}
return ctx.OpLoad(ctx.U32[1], SharedWord(ctx, ctx.mesh_attributes, index));
}
void StoreAttribute(EmitContext& ctx, Id index, Id value) {
if (ctx.mesh_attributes_global) {
StoreWord(ctx, BufferWordAt(ctx, ctx.mesh_attribute_base, index), value);
return;
}
ctx.OpStore(SharedWord(ctx, ctx.mesh_attributes, index), value);
}
/// (the same) the pool's word `word`: 0 the ticket counter, 1 + slot the generation that may take that slot next
Id PoolWord(EmitContext& ctx, Id word) {
const Id pool{ctx.OpIAdd(ctx.U64, PushU64(ctx, ctx.mesh_fallback_records_member_index),
ctx.Constant(ctx.U64, u64{MESH_FALLBACK_POOL_OFFSET}))};
return BufferWordAt(ctx, pool, word);
}
Id WorkgroupId(EmitContext& ctx) {
return ctx.OpCompositeExtract(ctx.U32[1], ctx.OpLoad(ctx.U32[3], ctx.workgroup_id), 0U);
}
@@ -186,25 +219,90 @@ void Strided(EmitContext& ctx, u32 count, u32 threads, Id invocation, Func&& bod
}
}
/// The raw stage buffer word of line `line` for element `element` (a vertex or a primitive).
Id LineWord(EmitContext& ctx, Id array, Id element, u32 base, u32 num_lines, u32 line) {
/// The attribute region's index of line `line` (a value) for element `element` (a vertex or a primitive): base + (element / 32)
/// * num_lines * 32 + element % 32 + line * 32.
Id LineIndex(EmitContext& ctx, Id element, u32 base, u32 num_lines, Id line) {
const Id group{ctx.OpShiftRightLogical(ctx.U32[1], element, ctx.Const(5U))};
const Id slot{ctx.OpBitwiseAnd(ctx.U32[1], element, ctx.Const(31U))};
const Id first{ctx.OpIAdd(
ctx.U32[1], ctx.OpIMul(ctx.U32[1], group, ctx.Const(num_lines * 32)),
ctx.OpIAdd(ctx.U32[1], slot, ctx.Const(base)))};
return ctx.OpLoad(
ctx.U32[1],
SharedWord(ctx, array, ctx.OpIAdd(ctx.U32[1], first, ctx.Const(line * 32))));
return ctx.OpIAdd(ctx.U32[1], first, ctx.OpShiftLeftLogical(ctx.U32[1], line, ctx.Const(5U)));
}
/// (Triforce) A loop that is not unrolled: body(index) for index = first, first + step, ... below end. var is a function variable
/// of the entry block (EmitMeshPrologue): one declared at the call, mid-function, is invalid SPIR-V
template <typename Func>
void Loop(EmitContext& ctx, Id var, Id first, Id end, u32 step, Func&& body) {
ctx.OpStore(var, first);
const Id header{ctx.OpLabel()}, block{ctx.OpLabel()}, next{ctx.OpLabel()}, done{ctx.OpLabel()};
ctx.OpBranch(header);
ctx.AddLabel(header);
const Id at{ctx.OpLoad(ctx.U32[1], var)};
const Id more{ctx.OpULessThan(ctx.U1, at, end)}; // (before the merge: it must be the branch's neighbour)
ctx.OpLoopMerge(done, next, spv::LoopControlMask::DontUnroll);
ctx.OpBranchConditional(more, block, done);
ctx.AddLabel(block);
body(at);
ctx.OpBranch(next);
ctx.AddLabel(next);
ctx.OpStore(var, ctx.OpIAdd(ctx.U32[1], at, ctx.Const((std::max)(step, 1U))));
ctx.OpBranch(header);
ctx.AddLabel(done);
}
/// The Soa layout's records (MeshFallbackLayout): record k of the workgroup's, base + k, is corner k % corners of primitive
/// k / corners, its index byte at 4 + k. The threads take the records in turn, and each line's words are neighbours: line l of
/// record r at H + l * fit + r.
/// (Triforce) Two loops, not unrolled: thread t takes records t, t + threads, ... below taken, and writes each one's lines in
/// turn, so at each step the threads write one line's neighbouring words, as the unrolled form did. Unrolled, a thread had a
/// store of its own for every line of every record it could take (348 for 126 primitives of 3 corners and 28 lines), which
/// Mesa's Intel compiler took minutes and gigabytes over, as it did the Aos form's (MeshFallbackEpilogue)
void WriteFallbackLines(EmitContext& ctx, Id base, Id taken) {
const MeshInfo& mesh{ctx.mesh_info};
const u32 corners{mesh.Corners()};
const u32 words{FallbackRecordWords(mesh)};
const u32 fit{MeshFallbackFit(words)};
const u32 vertex_lines{static_cast<u32>(mesh.vertex_lines.size())};
const u32 primitive_lines{static_cast<u32>(mesh.primitive_lines.size())};
const Id records{PushU64(ctx, ctx.mesh_fallback_records_member_index)};
const Id first{ctx.OpIAdd(ctx.U32[1], ctx.Const(MESH_FALLBACK_HEADER_WORDS), base)}; // (line 0 of record base)
Loop(ctx, ctx.mesh_fallback_epilogue_word, LocalInvocation(ctx), taken, ctx.mesh_threads, [&](Id k) {
// (an index byte the program left unwritten is held to the vertex count)
const Id vertex{Clamped(ctx, ctx.OpLoad(ctx.U32[1], SharedWord(ctx, ctx.mesh_map, ctx.OpIAdd(ctx.U32[1], k, ctx.Const(4U)))),
mesh.max_vertices)};
const Id primitive{corners == 1 ? k : ctx.OpUDiv(ctx.U32[1], k, ctx.Const(corners))};
const Id at{ctx.OpIAdd(ctx.U32[1], first, k)};
Loop(ctx, ctx.mesh_fallback_epilogue_line, ctx.u32_zero_value, ctx.Const(words), 1, [&](Id word) {
// (word 0 the validity, 1 .. vertex_lines its vertex's lines, then its primitive's: one load, its index clamped into
// the region, as word 0 and the lines of the other kind ask for one past it)
const Id line{ctx.OpISub(ctx.U32[1], word, ctx.Const(1U))};
const Id of_vertex{ctx.OpULessThan(ctx.U1, line, ctx.Const(vertex_lines))};
const Id vertex_index{LineIndex(ctx, vertex, 0, vertex_lines, line)};
const Id primitive_index{LineIndex(ctx, primitive, ctx.mesh_primitive_base, primitive_lines,
ctx.OpISub(ctx.U32[1], line, ctx.Const(vertex_lines)))};
const Id index{Clamped(ctx, ctx.OpSelect(ctx.U32[1], of_vertex, vertex_index, primitive_index),
ctx.mesh_attribute_words)};
const Id line_value{LoadAttribute(ctx, index)};
const Id value{ctx.OpSelect(ctx.U32[1], ctx.OpIEqual(ctx.U1, word, ctx.u32_zero_value), ctx.Const(1U), line_value)};
StoreWord(ctx, BufferWordAt(ctx, records, ctx.OpIAdd(ctx.U32[1], at, ctx.OpIMul(ctx.U32[1], word, ctx.Const(fit)))),
value);
});
});
}
/// A mesh workgroup takes records for its primitives' corners from the records buffer's allocator and writes them; the vertex
/// stage's indirect draw covers the records taken (MESH_FALLBACK_DRAW_WORD). A task's flag first bounds its count.
/// (Triforce) The records are written by one loop over their words, the workgroup's threads side by side: thread t writes
/// words t, t + threads, ... of the workgroup's records, each word a load from the attribute region and a store. They were
/// written out unrolled, a primitive's corners and every line of each, its own address each: 348 stores a thread for a mesh
/// of 126 primitives and 28 lines, which Mesa's Intel compiler (Iris Xe, 32 lanes) took 207 s and 3.8 GB to build (41 s and
/// 1.5 GB without them). Side by side, the stores of a step are one run of memory, too.
void MeshFallbackEpilogue(EmitContext& ctx) {
const MeshInfo& mesh{ctx.mesh_info};
const u32 corners{mesh.Corners()};
const u32 words{FallbackRecordWords(mesh)};
const u32 fit{MESH_FALLBACK_RECORD_WORDS / words}; // (this program's records the buffer holds)
const u32 fit{MeshFallbackFit(words)}; // (this program's records the buffer holds)
const Id none{ctx.Const(0xFFFFFFFFU)};
Barrier(ctx);
// (with a task program every workgroup dispatched was started by it: the dispatch is the map's, TaskEpilogue)
@@ -237,46 +335,67 @@ void MeshFallbackEpilogue(EmitContext& ctx) {
Barrier(ctx);
const Id base{ctx.OpLoad(ctx.U32[1], ctx.mesh_primitive_count)};
If(ctx, ctx.OpINotEqual(ctx.U1, base, none), [&] {
const Id invocation{LocalInvocation(ctx)};
Strided(ctx, mesh.max_primitives, ctx.mesh_threads, invocation, [&](Id primitive) {
If(ctx, ctx.OpULessThan(ctx.U1, primitive, count), [&] {
for (u32 corner = 0; corner < corners; ++corner) {
const Id byte{ctx.OpIAdd(
ctx.U32[1], ctx.OpIMul(ctx.U32[1], primitive, ctx.Const(corners)),
ctx.Const(4U + corner))};
// (an index byte the program left unwritten is held to the vertex count)
const Id vertex{Clamped(
ctx, ctx.OpLoad(ctx.U32[1], SharedWord(ctx, ctx.mesh_map, byte)),
mesh.max_vertices)};
const Id record{ctx.OpIAdd(
ctx.U32[1], base,
ctx.OpIAdd(ctx.U32[1], ctx.OpIMul(ctx.U32[1], primitive, ctx.Const(corners)),
ctx.Const(corner)))};
const Id word{ctx.OpIAdd(ctx.U32[1], ctx.Const(MESH_FALLBACK_HEADER_WORDS),
ctx.OpIMul(ctx.U32[1], record, ctx.Const(words)))};
StoreWord(ctx, BufferWord(ctx, ctx.mesh_fallback_records_member_index, word),
ctx.Const(1U));
for (u32 line = 0; line < mesh.vertex_lines.size(); ++line) {
const Id value{LineWord(ctx, ctx.mesh_attributes, vertex, 0,
static_cast<u32>(mesh.vertex_lines.size()), line)};
StoreWord(ctx, BufferWord(ctx, ctx.mesh_fallback_records_member_index,
ctx.OpIAdd(ctx.U32[1], word, ctx.Const(1U + line))),
value);
}
for (u32 line = 0; line < mesh.primitive_lines.size(); ++line) {
const Id value{LineWord(ctx, ctx.mesh_attributes, primitive,
ctx.mesh_primitive_base,
static_cast<u32>(mesh.primitive_lines.size()), line)};
StoreWord(ctx, BufferWord(ctx, ctx.mesh_fallback_records_member_index,
ctx.OpIAdd(ctx.U32[1], word,
ctx.Const(static_cast<u32>(1U + mesh.vertex_lines.size()) +
line))),
value);
}
}
});
});
if (ctx.runtime_info.mesh_fallback_layout == static_cast<u32>(MeshFallbackLayout::Soa)) {
WriteFallbackLines(ctx, base, taken);
return;
}
const u32 vertex_lines{static_cast<u32>(mesh.vertex_lines.size())};
const u32 primitive_lines{static_cast<u32>(mesh.primitive_lines.size())};
// (the workgroup's records are words first .. first + taken * words: its first record's, then each record's validity,
// its vertex's lines and its primitive's lines)
const Id records{PushU64(ctx, ctx.mesh_fallback_records_member_index)};
const Id first{ctx.OpIAdd(ctx.U32[1], ctx.Const(MESH_FALLBACK_HEADER_WORDS),
ctx.OpIMul(ctx.U32[1], base, ctx.Const(words)))};
const Id total{ctx.OpIMul(ctx.U32[1], taken, ctx.Const(words))};
const Id at_var{ctx.mesh_fallback_epilogue_word}; // (declared in the entry block: EmitMeshPrologue)
ctx.OpStore(at_var, LocalInvocation(ctx));
const Id header{ctx.OpLabel()}, body{ctx.OpLabel()}, next{ctx.OpLabel()}, done{ctx.OpLabel()};
ctx.OpBranch(header);
ctx.AddLabel(header);
const Id at{ctx.OpLoad(ctx.U32[1], at_var)};
const Id more{ctx.OpULessThan(ctx.U1, at, total)}; // (before the merge: it must be the branch's neighbour)
ctx.OpLoopMerge(done, next, spv::LoopControlMask::DontUnroll);
ctx.OpBranchConditional(more, body, done);
ctx.AddLabel(body);
// (record r is corner r % corners of primitive r / corners: its index byte is the map's byte 4 + r)
const Id record{ctx.OpUDiv(ctx.U32[1], at, ctx.Const(words))};
const Id word{ctx.OpISub(ctx.U32[1], at, ctx.OpIMul(ctx.U32[1], record, ctx.Const(words)))};
const Id primitive{ctx.OpUDiv(ctx.U32[1], record, ctx.Const(corners))};
// (an index byte the program left unwritten is held to the vertex count)
const Id vertex{Clamped(
ctx, ctx.OpLoad(ctx.U32[1], SharedWord(ctx, ctx.mesh_map, ctx.OpIAdd(ctx.U32[1], record, ctx.Const(4U)))),
mesh.max_vertices)};
// (word 0 the validity, 1 .. vertex_lines its vertex's lines, then its primitive's: one load, its index clamped into the
// region, as the word 0 and the lines of the other kind ask for one past it)
const Id line{ctx.OpISub(ctx.U32[1], word, ctx.Const(1U))};
const Id of_vertex{ctx.OpULessThan(ctx.U1, line, ctx.Const(vertex_lines))};
const Id vertex_index{LineIndex(ctx, vertex, 0, vertex_lines, line)};
const Id primitive_index{LineIndex(ctx, primitive, ctx.mesh_primitive_base, primitive_lines,
ctx.OpISub(ctx.U32[1], line, ctx.Const(vertex_lines)))};
const Id index{Clamped(ctx, ctx.OpSelect(ctx.U32[1], of_vertex, vertex_index, primitive_index),
ctx.mesh_attribute_words)};
const Id line_value{LoadAttribute(ctx, index)};
const Id value{ctx.OpSelect(ctx.U32[1], ctx.OpIEqual(ctx.U1, word, ctx.u32_zero_value), ctx.Const(1U), line_value)};
StoreWord(ctx, BufferWordAt(ctx, records, ctx.OpIAdd(ctx.U32[1], first, at)), value);
ctx.OpBranch(next);
ctx.AddLabel(next);
ctx.OpStore(at_var, ctx.OpIAdd(ctx.U32[1], at, ctx.Const((std::max)(ctx.mesh_threads, 1U))));
ctx.OpBranch(header);
ctx.AddLabel(done);
});
if (ctx.mesh_attributes_global) {
// (every thread has read what it copies from the region: thread 0 hands the slot on to the ticket a pool's length later)
Barrier(ctx);
If(ctx, ctx.OpIEqual(ctx.U1, LocalInvocation(ctx), ctx.u32_zero_value), [&] {
const Id ticket{ctx.mesh_attribute_ticket};
const Id slot{ctx.OpBitwiseAnd(ctx.U32[1], ticket, ctx.Const(MESH_FALLBACK_POOL_SLOTS - 1))};
const Id next{ctx.OpIAdd(ctx.U32[1], ctx.OpShiftRightLogical(ctx.U32[1], ticket, ctx.Const(MESH_FALLBACK_POOL_SLOT_SHIFT)),
ctx.Const(1U))};
// (an exchange: Sirit's OpAtomicStore is emitted a word too long, and spirv-val and the driver reject it)
ctx.OpAtomicExchange(ctx.U32[1], PoolWord(ctx, ctx.OpIAdd(ctx.U32[1], slot, ctx.Const(1U))),
ctx.Const(static_cast<u32>(spv::Scope::Device)), ctx.u32_zero_value, next);
});
}
}
void StorePosition(EmitContext& ctx, u32 element, Id value) {
@@ -366,8 +485,15 @@ void MeshEpilogue(EmitContext& ctx) {
return;
}
Barrier(ctx);
const Id count{ctx.OpUMin(ctx.U32[1], ctx.OpLoad(ctx.U32[1], ctx.mesh_primitive_count),
ctx.Const(mesh.max_primitives))};
Id count{ctx.OpUMin(ctx.U32[1], ctx.OpLoad(ctx.U32[1], ctx.mesh_primitive_count),
ctx.Const(mesh.max_primitives))};
if (Sirit::ValidId(ctx.num_workgroups)) {
// (Triforce, , as Lichii ) keep the NumWorkgroups load live through NIR's dead-code elimination into
// ac_nir_lower_ngg_ms so RADV < 26.2.5 reserves the mesh grid-size registers (NumWorkgroups.x > 0 for every
// launched mesh workgroup)
const Id grid_x{ctx.OpCompositeExtract(ctx.U32[1], ctx.OpLoad(ctx.U32[3], ctx.num_workgroups), 0U)};
count = ctx.OpSelect(ctx.U32[1], ctx.OpINotEqual(ctx.U1, grid_x, ctx.u32_zero_value), count, ctx.u32_zero_value);
}
const Id max_vertices{ctx.Const(mesh.max_vertices)};
// Marker for OpSetMeshOutputsEXT max_vertices, count (PatchMeshInstructions).
ctx.OpStore(max_vertices, count);
@@ -474,16 +600,19 @@ void EmitMeshFallbackVertexBody(EmitContext& ctx) {
const u32 primitive_lines{static_cast<u32>(mesh.primitive_lines.size())};
const u32 words{FallbackRecordWords(mesh)};
// (a record a vertex, in the order the mesh workgroups took them (MeshFallbackEpilogue): the indirect draw's count is the
// records taken, so every one it reaches was written)
// records taken, so every one it reaches was written. Its words a record apart (Aos) or a line apart (Soa))
const bool lines{ctx.runtime_info.mesh_fallback_layout == static_cast<u32>(MeshFallbackLayout::Soa)};
const u32 stride{lines ? MeshFallbackFit(words) : 1U};
const Id vertex{ctx.OpLoad(ctx.U32[1], ctx.vertex_index)};
const Id first{ctx.OpIAdd(ctx.U32[1], ctx.Const(MESH_FALLBACK_HEADER_WORDS),
ctx.OpIMul(ctx.U32[1], vertex, ctx.Const(words)))};
const Id first{lines ? ctx.OpIAdd(ctx.U32[1], ctx.Const(MESH_FALLBACK_HEADER_WORDS), vertex)
: ctx.OpIAdd(ctx.U32[1], ctx.Const(MESH_FALLBACK_HEADER_WORDS),
ctx.OpIMul(ctx.U32[1], vertex, ctx.Const(words)))};
const Id valid{LoadWord(ctx, BufferWord(ctx, ctx.mesh_fallback_records_member_index, first))};
const auto read = [&](u32 word) {
return ctx.OpBitcast(
ctx.F32[1],
LoadWord(ctx, BufferWord(ctx, ctx.mesh_fallback_records_member_index,
ctx.OpIAdd(ctx.U32[1], first, ctx.Const(word)))));
ctx.OpIAdd(ctx.U32[1], first, ctx.Const(word * stride)))));
};
std::array<Id, 4> position{};
for (u32 line = 0; line < vertex_lines; ++line) {
@@ -563,14 +692,23 @@ Id EmitIsbeRead(EmitContext& ctx, Id address) {
word);
}
/// (hookshot) ISBERD.O: the word EmitIsbeWriteAttribute writes at that address, read back (a task program reads its
/// payload: one of OoT's task programs stopped at it)
Id EmitIsbeReadOutput(EmitContext& ctx, Id address) {
const Id index{ctx.OpShiftRightLogical(ctx.U32[1], address, ctx.Const(2U))};
if (ctx.stage == Stage::Task) {
return LoadWord(ctx, PayloadWord(ctx, index)); // (as EmitIsbeWriteAttribute's StoreWord wrote it)
}
return LoadAttribute(ctx, Clamped(ctx, index, ctx.mesh_attribute_words));
}
void EmitIsbeWriteAttribute(EmitContext& ctx, Id address, Id value) {
const Id index{ctx.OpShiftRightLogical(ctx.U32[1], address, ctx.Const(2U))};
if (ctx.stage == Stage::Task) {
StoreWord(ctx, PayloadWord(ctx, index), value);
return;
}
ctx.OpStore(SharedWord(ctx, ctx.mesh_attributes, Clamped(ctx, index, ctx.mesh_attribute_words)),
value);
StoreAttribute(ctx, Clamped(ctx, index, ctx.mesh_attribute_words), value);
}
void EmitIsbeWriteMapU8(EmitContext& ctx, Id address, Id value) {
@@ -590,6 +728,16 @@ void EmitIsbeWriteMapU32(EmitContext& ctx, const IR::Value& address, Id value) {
}
void EmitMeshPrologue(EmitContext& ctx) {
if (ctx.stage == Stage::Mesh && ctx.mesh_fallback) {
// (Triforce) the epilogue's loop index (MeshFallbackEpilogue): a function's variables open its first block, and the
// prologue is the first thing in it. Before anything else here
ctx.mesh_fallback_epilogue_word = ctx.AddLocalVariable(
ctx.TypePointer(spv::StorageClass::Function, ctx.U32[1]), spv::StorageClass::Function);
ctx.mesh_fallback_epilogue_line = ctx.AddLocalVariable( // (WriteFallbackLines' inner loop)
ctx.TypePointer(spv::StorageClass::Function, ctx.U32[1]), spv::StorageClass::Function);
}
// (Triforce, mma_layout.h mesh_fallback_shared_warp) the shared warp's lane and its words at zero, before the barriers below
WarpPrologue(ctx);
if (ctx.stage == Stage::Task) {
// (hookshot) the count starts at nothing: task payload memory holds whatever the last task left, and a task that keeps no meshlet
// never writes it. The barrier: every thread has done this before any of them goes on to write the real count
@@ -605,6 +753,20 @@ void EmitMeshPrologue(EmitContext& ctx) {
ctx.mesh_fallback_slot =
LoadWord(ctx, BufferWordAt(ctx, PushU64(ctx, ctx.mesh_fallback_payload_member_index), WorkgroupId(ctx)));
}
if (ctx.mesh_attributes_global) {
// (Triforce, mma_layout.h mesh_fallback_global_attributes) the workgroup's pool slot, before anything writes the region:
// thread 0 takes a ticket (a call: no branch here), every thread reads it after the barrier
ctx.OpFunctionCall(ctx.void_id, ctx.mesh_attribute_claim, std::array{LocalInvocation(ctx)});
Barrier(ctx);
ctx.mesh_attribute_ticket = ctx.OpLoad(ctx.U32[1], ctx.mesh_attribute_ticket_shared);
const Id slot{ctx.OpBitwiseAnd(ctx.U32[1], ctx.mesh_attribute_ticket, ctx.Const(MESH_FALLBACK_POOL_SLOTS - 1))};
const Id offset{ctx.OpIMul(ctx.U32[1], slot, ctx.Const(ctx.mesh_attribute_slot_bytes))};
ctx.mesh_attribute_base =
ctx.OpIAdd(ctx.U64,
ctx.OpIAdd(ctx.U64, PushU64(ctx, ctx.mesh_fallback_records_member_index),
ctx.Constant(ctx.U64, u64{MESH_FALLBACK_POOL_OFFSET} + MESH_FALLBACK_POOL_HEADER_BYTES)),
ctx.OpUConvert(ctx.U64, offset));
}
// (local) The stage buffer's map and attribute regions start at zero, as they come out on NVIDIA: workgroup memory holds
// whatever the last workgroup on that unit left, and a vertex or an index byte the program left unwritten was that. On an
// RX 7700S the foliage drawn into the 2400 x 2400 shadow map around Link came out with hundreds of long thin triangles
@@ -625,6 +787,12 @@ void EmitMeshPrologue(EmitContext& ctx) {
};
zero_all(ctx.mesh_map, ctx.mesh_map_bytes);
zero_all(ctx.mesh_attributes, ctx.mesh_attribute_words);
if (ctx.mesh_attributes_global) { // (Triforce: the region in its pool slot, zeroed the same way)
for (u32 first = 0; first < ctx.mesh_attribute_words; first += ctx.mesh_threads) {
StoreAttribute(ctx, Clamped(ctx, ctx.OpIAdd(ctx.U32[1], invocation, ctx.Const(first)), ctx.mesh_attribute_words),
ctx.u32_zero_value);
}
}
}
if (ctx.mesh_fallback && !ctx.runtime_info.mesh_fallback_task && ctx.mesh_threads) {
// (a mesh program with no task reads its workgroup index from the payload: NVN's hardware puts it at byte 0)

File diff suppressed because it is too large Load Diff

View File

@@ -16,6 +16,28 @@ inline std::array<uint32_t, 8> mma_order_a{0, 1, 2, 3, 4, 5, 6, 7};
inline std::array<uint32_t, 4> mma_order_b{0, 1, 2, 3};
inline std::array<uint32_t, 4> mma_order_c{0, 1, 2, 3};
inline bool mma_software = false; // (HMMA_nx2 in software: emit_spirv_warp.cpp, RX_VK_MMA_SOFTWARE=1)
// (Triforce) and in which form (mma_software.h SoftwareMmaForm: 0 the loop, 1 unrolled, 2 unrolled with the GPU's f16 rounding),
// chosen by vk_coopmat.cpp's self-test; and whether its quad broadcasts may be used (the device has quad operations in every stage)
inline uint32_t mma_software_form = 0;
inline bool mma_software_quad = false;
// (Triforce, AMD RDNA 3/4) HMMA_nx2 on 16x16x16 f16 cooperative matrices: the console's fragments are staged through a
// per-subgroup tile of shared memory at their PTX m16n8k16 positions, so the device's own lane layout does not matter
// (emit_spirv_warp.cpp DefineWmma16MatrixFunction, vk_coopmat.cpp). B and C are padded to 16 columns with zeros.
inline bool mma_wmma16 = false;
// (with mma_wmma16) one 16x16x16 multiply instead of two K=8 halves rounded to f16 between them as HMMA.F16 does
inline bool mma_wmma16_fast = false;
// (with mma_wmma16) fuse N-pairs (two HMMA_nx2 sharing A into one 16x16 [B0|B1] DontInline call)
inline bool mma_wmma16_fused = true;
// shared memory the WMMA16 tiles add per subgroup, in u32 words: A (16x16 row major), B's two K halves (each 16x16 column
// major, the other half's rows zero) and C/D (16x16 row major), 16x16 f16 = 128 words each
inline constexpr uint32_t mma_wmma16_tile_words = 4 * 128;
inline constexpr uint32_t mma_wmma16_tile_bytes = mma_wmma16_tile_words * 4;
// the device's maxComputeSharedMemorySize (vk_coopmat.cpp): a program whose tiles would pass it multiplies in software
inline uint32_t mma_wmma16_shared_limit = 0;
// the device's computeFullSubgroups (vk_coopmat.cpp): with it a workgroup X width that is a multiple of 32 is created with
// REQUIRE_FULL_SUBGROUPS (vk_draw.cpp pin_subgroup), so no subgroup has lanes missing; without it no program uses the tiles
inline bool mma_wmma16_full_subgroups = false;
inline uint32_t mma_wmma16_max_subgroups = 0;
// (amd-fix) float colour outputs carry no NaN or infinity to their target (EmitSetFragColor): one NaN texel spreads
// through bloom/blur/downsample averages into glowing blocks (OoT's flowers on AMD, Hookshot issue 606). On for every
// card but NVIDIA (vk_coopmat.cpp coopmat_init); RX_VK_NO_NAN_GUARD=1 turns it off. Idea from NX2navi patch 0027.
@@ -35,5 +57,63 @@ inline bool fetch_bounds_buffers = false;
// (hookshot) isnan tested on the value's bits (IsNan in emit_spirv_floating_point.cpp), not OpIsNan, for AMD's older Windows
// shader compiler (RX 5000 and RX 6000: gpu/vk/vk_vendor.h); RX_VK_NAN_BITS=0 or 1
inline bool nan_bits = false;
// (Triforce) In compute-fallback mesh stages, NoContraction f32 multiplies as OpFma(a, b, -0.0f) (EmitFPMul32): AMD's older
// Windows shader compiler (RDNA 1 and 2, RX 5000 and RX 6000: gpu/vk/vk_vendor.h amd_older_compiler) ignores NoContraction
// on a multiply, even in a pipeline made without its optimizer, and turns fma(t, v * rsq, add) into fma(rsq * t, v, add) in
// the depth-only mesh fallback programs, where v * rsq has one use, while the colour pass's keeps v * rsq. A fallback stage
// writes its positions to a storage buffer, so gl_Position cannot be decorated Invariant there. The grass blades' tips then
// differ by one unit in the last place between the two passes, fail the colour pass's EQUAL depth test, and single
// triangles flash white for a frame. OpFma(a, b, -0.0f) is a * b exactly (signed zeros, subnormals, infinities and NaNs
// too) and is not taken apart. On for that compiler (vk_coopmat.cpp); RX_VK_MESH_STRICT_FMUL=0 or 1
inline bool mesh_fallback_strict_fmul = false;
// (Triforce) A compute stage's float adds to storage buffers that take the compare-exchange loop (no native add on this GPU:
// gpu/vk/native_fadd.h) are admitted to the loop one at a time a subgroup (spirv_emit_context.cpp SubgroupCasLoop,
// OpGroupNonUniformElect). The sky's light sums (compute 499dbfd0721d2858) add into a few words from every invocation; each
// failed attempt is another adder's success, so the attempts grow with the square of the adders, and on Intel's Arc cards
// the dispatch outlasted the driver's timeout: the device lost after the intro. On for Intel's GPUs (vk_coopmat.cpp), where
// that was seen; elsewhere the plain loop, as it was, until the admission has run on those drivers (a subgroup operation
// inside a loop the invocations leave one by one). RX_VK_FADD_SUBGROUP=0 or 1 on any GPU
inline bool f32_add_subgroup = false;
// (hookshot) a storage buffer table's entries searched in a loop the driver is asked not to unroll (DefineGlobalMemoryFunctions),
// not one test an entry written out sixteen times. Mesa inlines every function, DontInline or not: OoT's foliage culling
// (53caac5f) has 46 global accesses, each with its ~70 table entries written out, over 100k instructions that Intel's
// compiler did not finish in minutes, and every compute pipeline queued behind it on Intel's one build thread waited:
// mesh-drawn rocks and doors white, the forest grey. In a loop: 12 s. On for Intel's Mesa driver (vk_coopmat.cpp); RX_VK_GM_LOOP=0 or 1
inline bool global_table_loop = false;
// (Triforce) The mesh fallback's task and mesh stages read global memory through the guest page table alone, the way the console's
// GPU reads it, not by searching the program's storage buffers (DefineGlobalMemoryFunctions). The search is the cost there: on an
// Iris Xe the fallback's colour mesh stages are held to 32 lanes at the register file's limit, and each of their global loads,
// inlined with its four buffers and three table entries, filled the program with spill code: 739acd67 (Hyrule Castle's) took
// 12.3 ms a frame, 5.7 ms with its loads through the table, its 243 million loads the same words both ways. A storage buffer in a
// virtual pool (from 1 TB) is not in the table and reads 0. (Triforce) Off by default on every GPU: the table must give each bound
// storage buffer the memory its binding reads, which was not checked against Triforce's memory code (vk_coopmat.cpp); RX_VK_MESH_PAGES=1
inline bool mesh_fallback_pages = false;
// (Triforce) Vertex, fragment, compute, task and mesh stages' global loads (native task and mesh stages and the mesh fallback's) through the guest page
// table alone, as mesh_fallback_pages does. The search
// over every bound storage buffer, inlined at each load, made a vertex stage with 61 loads 585 ms of RADV's compile (44 ms through
// the table). 1: the table alone; 2: the search kept, a load where the two disagree recorded in the miss log's buffer
// (vk_draw.cpp gp_table_check_log). (Triforce) Off by default: on where the table holds the pools (vk_coopmat.cpp) with
// RX_VK_GP_TABLE=1 or 2. Every storage buffer bound to such a stage is then looked at in the table (vk_draw.cpp gp_table_cover)
inline int graphics_table_loads = 0;
// (Triforce) The mesh fallback's mesh workgroups keep their attribute region (the stage buffer's vertex and primitive lines, up to
// 32 KB) in a slot of a pool in the records buffer instead of in workgroup memory (emit_spirv.h MESH_FALLBACK_POOL_*). Intel
// gives workgroup memory in powers of two, so Hyrule Castle's colour mesh stages, 9 to 18 KB of it, took 16 or 32 KB each: few
// workgroups fit on a subslice at once, and nothing hid the stages' spill traffic. On an Iris Xe 739acd67 took 5.3-6.9 ms a
// dispatch with its region in workgroup memory, 7.4 ms given 8 KB more of it, and 2.6-2.8 ms with the region in a slot.
// On for Intel's Mesa driver (vk_coopmat.cpp); RX_VK_MESH_GLOBAL_ATTRS=0 or 1
inline bool mesh_fallback_global_attributes = false;
// (Triforce) The mesh fallback's task and mesh stages keep their warp in workgroup memory, not in the host's subgroup: a lane is the
// invocation's place in its 32-thread workgroup, and ballots, votes and shuffles go through words of workgroup memory that every
// lane of the block's region writes and waits for (emit_spirv_warp.cpp, the shared warp). Such a stage has no subgroup
// instruction left, so it gives the same result at any lane count, and the renderer runs it at 8 lanes (vk_draw.cpp): on an
// Iris Xe the colour mesh stages, held to 32 lanes for their subgroup instructions, spent most of their time spilling
// (d8e59341: 843k cycles a workgroup at 32 lanes by Mesa's count, 4 x 70k at 8). Only stages it can be done for: 32-thread
// workgroups, no warp operation in a loop, no read of the stage buffer's outputs (EmitContext::PlanSharedWarp). On for Intel's
// Mesa driver (vk_coopmat.cpp); RX_VK_MESH_SHARED_WARP=0 or 1
inline bool mesh_fallback_shared_warp = false;
// (RX_VK_MESH_SHARED_WARP_CHECK=1, for a developer: each shared ballot, vote and shuffle beside the subgroup's own, those
// compared and those that differ counted past the fallback's records (emit_spirv.h WARP_COUNTER_*) and logged; the stage
// keeps its subgroup instructions, so it stays at 32 lanes)
inline bool mesh_fallback_shared_warp_check = false;
} // namespace Shader::Backend::SPIRV

View File

@@ -0,0 +1,228 @@
// (Triforce) HMMA.16816.F16 in software: D(16x8) = A(16x16) * B(16x8) + C on the subgroup's lanes, for GPUs without
// cooperative matrices (AMD before RDNA 3, the Steam Deck among them; GTX 10 and 16; Intel's integrated GPUs). The 32 lanes'
// fragments (PTX mma.m16n8k16's layout: lane t, g = t/4, i = t%4) are exchanged through subgroup operations; the products are
// accumulated with FMA in f32 and rounded to f16 after every 8 columns of K, as HMMA.F16 does. One function, called for each
// HMMA_nx2 (emit_spirv_warp.cpp EmitMatrixMulAddF16), and built the same way by the device's self-test (vk_coopmat.cpp), which
// is why it takes a plain Sirit module and the types it needs rather than the translator's EmitContext.
//
// Two forms compute the same words:
// - Loop: Lichii's (zortos293/Lichii, emit_spirv_tensor.cpp, GPL-3.0). The 8 steps (4 K-pairs in each half of K) in a loop the
// driver is asked not to unroll; A and B from other lanes through shuffles, the f16 rounding in integer operations.
// - Unrolled: the steps written out (in a loop that runs once: see below). A lane's rows of A are in its own quad (lanes 4g..4g+3), so A comes through quad broadcasts
// (DPP on AMD, not the LDS crossbar a shuffle takes), and A's lane indices are constants (B's are still the lane's
// warp_base + col_base + c). The rounding to f16 is either the same
// integer operations or the GPU's own f32 -> f16 -> f32 conversion (round to nearest even, f16 subnormals kept). A conversion
// applied to an FMA's result may be folded into it by the driver (RADV: v_fma_mixlo_f16), which rounds the exact sum once
// instead of rounding it to f32 first: a tie in f32 then goes the other way (1 word in about 17,000 of random data). The value
// is passed through a shuffle with lane xor 0 (the same lane) before the conversion, which keeps them apart; RADV folds that
// shuffle into the conversion as a DPP identity, so it costs nothing. vk_coopmat.cpp runs both forms on the device and uses the
// unrolled one only where its words are the loop's. The shuffle keeps them apart only while the driver keeps a shuffle by
// xor 0: one that folds it away rounds once again, and the tie inputs then make the self-test keep the loop (slower, said
// only in the log).
//
// On the Steam Deck (RADV), one multiply a lane over a 1280x800 dispatch: 0.469 ms looped, 0.363 ms unrolled with the integer
// rounding, 0.177 ms unrolled with the conversion (a fully fused conversion, not the same words, 0.153 ms). OoT's gameplay network
// at Resolution 100% (9dc98871, Kokiri Forest): 8.61 ms a frame looped, 3.82 ms unrolled with the conversion.
#pragma once
#include <array>
#include <cstdint>
#include <sirit/sirit.h>
namespace Shader::Backend::SPIRV {
enum class SoftwareMmaForm : uint32_t {
Loop = 0, // (Lichii's: the steps in a loop, shuffles, integer rounding)
Unrolled = 1, // (written out, A through quad broadcasts, integer rounding)
UnrolledF16 = 2, // (written out, A through quad broadcasts, the GPU's f16 conversion rounds)
};
struct SoftwareMmaTypes {
Sirit::Id u32, u32x2, u32x4, f32, f32x2, f16, boolean;
};
/// The function (A: 4 words, B: 2, C: 2) -> D: 2 words, as the console's fragments hold them, two f16 a word. lane_variable is the
/// SubgroupLocalInvocationId input; quad: OpGroupNonUniformQuadBroadcast may be used (the caller adds GroupNonUniformQuad), else
/// A's lanes are shuffled to. The caller adds GroupNonUniform and GroupNonUniformShuffle.
inline Sirit::Id DefineSoftwareMma(Sirit::Module& m, const SoftwareMmaTypes& t, Sirit::Id lane_variable, SoftwareMmaForm form,
bool quad) {
using Sirit::Id;
const Id u32ty = t.u32, f32ty = t.f32;
const auto imm = [&](uint32_t v) { return m.Constant(u32ty, v); };
const auto add = [&](Id a, Id b) { return m.OpIAdd(u32ty, a, b); };
const auto and_ = [&](Id a, uint32_t b) { return m.OpBitwiseAnd(u32ty, a, imm(b)); };
const auto unpack = [&](Id v) { return m.OpUnpackHalf2x16(t.f32x2, v); };
const auto round_half = [&](Id value) {
// Do not express the intermediate rounding as unpack(pack(value)): drivers may
// eliminate that round trip. Round normal significands explicitly, ties to even;
// half subnormals lie on the exactly representable 2^-24 grid.
const Id bits = m.OpBitcast(u32ty, value);
const Id magnitude = and_(bits, 0x7fffffffU);
const Id tie = and_(m.OpShiftRightLogical(u32ty, magnitude, imm(13)), 1);
const Id rounded = and_(add(add(magnitude, imm(0xfff)), tie), ~0x1fffU);
const Id normal = m.OpSelect(u32ty, m.OpUGreaterThanEqual(t.boolean, rounded, imm(0x47800000)), imm(0x7f800000), rounded);
const Id scaled = m.OpFMul(f32ty, m.OpBitcast(f32ty, magnitude), m.Constant(f32ty, 16777216.0f));
const Id subnormal = m.OpBitcast(u32ty, m.OpFMul(f32ty, m.OpRoundEven(f32ty, scaled), m.Constant(f32ty, 0x1p-24f)));
const Id finite = m.OpSelect(u32ty, m.OpUGreaterThanEqual(t.boolean, magnitude, imm(0x38800000)), normal, subnormal);
const Id result = m.OpSelect(u32ty, m.OpUGreaterThanEqual(t.boolean, magnitude, imm(0x7f800000)), magnitude, finite);
return m.OpBitcast(f32ty, m.OpBitwiseOr(u32ty, result, and_(bits, 0x80000000)));
};
const auto round_half_f16 = [&](Id value) {
// (through the same lane first: the conversion is then not folded into the FMA that made the value, see above)
const Id same = m.OpBitcast(f32ty, m.OpGroupNonUniformShuffleXor(u32ty, imm(3), m.OpBitcast(u32ty, value), imm(0)));
const Id half = m.OpFConvert(t.f16, same);
m.Decorate(half, spv::Decoration::NoContraction);
const Id back = m.OpFConvert(f32ty, half);
m.Decorate(back, spv::Decoration::NoContraction);
return back;
};
const Id type = m.TypeFunction(t.u32x2, t.u32x4, t.u32x2, t.u32x2);
const Id fn = m.OpFunction(t.u32x2, spv::FunctionControlMask::DontInline, type);
const Id matrix_a = m.OpFunctionParameter(t.u32x4);
const Id matrix_b = m.OpFunctionParameter(t.u32x2);
const Id matrix_c = m.OpFunctionParameter(t.u32x2);
m.AddLabel();
const bool loop = form == SoftwareMmaForm::Loop;
// (a function's variables come first in its first block; the counter first in either form, as in Lichii's)
const Id counter = m.AddLocalVariable(m.TypePointer(spv::StorageClass::Function, u32ty), spv::StorageClass::Function);
Id result{};
std::array<Id, 4> accumulators{};
if (!loop)
result = m.AddLocalVariable(m.TypePointer(spv::StorageClass::Function, t.u32x2), spv::StorageClass::Function);
else
for (auto& acc : accumulators)
acc = m.AddLocalVariable(m.TypePointer(spv::StorageClass::Function, f32ty), spv::StorageClass::Function);
std::array<Id, 8> inputs;
for (uint32_t i = 0; i < 4; ++i) inputs[i] = m.OpCompositeExtract(u32ty, matrix_a, i);
for (uint32_t i = 0; i < 2; ++i) {
inputs[4 + i] = m.OpCompositeExtract(u32ty, matrix_b, i);
inputs[6 + i] = m.OpCompositeExtract(u32ty, matrix_c, i);
}
// (the lane's warp, its quad and its B lanes' base; read where Lichii's function reads them, so that the loop's SPIR-V is
// the same as before word for word)
Id warp_base{}, row_base{}, col_base{};
const auto read_lane = [&] {
const Id lane = m.OpLoad(u32ty, lane_variable);
warp_base = and_(lane, ~31U);
row_base = and_(lane, 28);
col_base = m.OpShiftLeftLogical(u32ty, and_(lane, 3), imm(3));
};
const auto subgroup = [&] { return imm(3); }; // (spv::Scope::Subgroup)
// acc[row * 2 + col] += A[row's register].half * B[col's lane].half, each half of the pair in turn (NoContraction: each FMA
// rounds to f32 as the CPU's would)
const auto multiply_add = [&](Id value, Id as, Id bs) {
for (uint32_t half = 0; half < 2; ++half) {
value = m.OpFma(f32ty, m.OpCompositeExtract(f32ty, as, half), m.OpCompositeExtract(f32ty, bs, half), value);
m.Decorate(value, spv::Decoration::NoContraction);
}
return value;
};
if (!loop) {
read_lane();
std::array<Id, 4> acc;
for (uint32_t row = 0; row < 2; ++row) {
const Id c = unpack(inputs[6 + row]);
for (uint32_t col = 0; col < 2; ++col) acc[row * 2 + col] = m.OpCompositeExtract(f32ty, c, col);
}
// (the body in a loop that runs once, which the driver is asked not to unroll. Mesa inlines every call, and with the bodies
// side by side its CSE shares the shuffles of an operand that several multiplies take: fewer of them, but each held until
// its last use. OoT's gameplay network then took 256 VGPRs (4 waves a SIMD on the Steam Deck, not 8) and the 3/4 one spilled
// 181 to scratch; in a loop of their own they keep the loop form's 128. On the Deck, at 1280x800: 3.82 ms a frame in a loop,
// 4.60 ms without)
m.OpStore(counter, imm(0));
const Id header = m.OpLabel(), body = m.OpLabel(), next = m.OpLabel(), end = m.OpLabel();
m.OpBranch(header);
m.AddLabel(header);
const Id trip = m.OpLoad(u32ty, counter);
const Id more = m.OpULessThan(t.boolean, trip, imm(1));
m.OpLoopMerge(end, next, spv::LoopControlMask::DontUnroll);
m.OpBranchConditional(more, body, end);
m.AddLabel(body);
for (uint32_t upper = 0; upper < 2; ++upper) { // (K 0-7, then 8-15: B's word and A's two of that half)
for (uint32_t component = 0; component < 4; ++component) { // (the K pair 2 * component of that half)
std::array<Id, 2> bs; // (B's column 2i + col, from lane 8i + component + 4 col)
for (uint32_t col = 0; col < 2; ++col)
bs[col] = unpack(m.OpGroupNonUniformShuffle(u32ty, subgroup(), inputs[4 + upper],
add(warp_base, add(col_base, imm(component + col * 4)))));
for (uint32_t row = 0; row < 2; ++row) { // (A's row g + 8 row, from lane 4g + component: this lane's quad)
const Id a = inputs[upper * 2 + row];
const Id as = unpack(quad ? m.OpGroupNonUniformQuadBroadcast(u32ty, subgroup(), a, imm(component))
: m.OpGroupNonUniformShuffle(u32ty, subgroup(), a, add(warp_base, add(row_base, imm(component)))));
for (uint32_t col = 0; col < 2; ++col) acc[row * 2 + col] = multiply_add(acc[row * 2 + col], as, bs[col]);
}
}
// HMMA.F16 rounds after each K=8 group, including the midpoint of K=16.
for (auto& v : acc) v = form == SoftwareMmaForm::UnrolledF16 ? round_half_f16(v) : round_half(v);
}
std::array<Id, 2> packed;
for (uint32_t row = 0; row < 2; ++row)
packed[row] = m.OpPackHalf2x16(u32ty, m.OpCompositeConstruct(t.f32x2, acc[row * 2], acc[row * 2 + 1]));
m.OpStore(result, m.OpCompositeConstruct(t.u32x2, packed[0], packed[1]));
m.OpBranch(next);
m.AddLabel(next);
m.OpStore(counter, add(trip, imm(1)));
m.OpBranch(header);
m.AddLabel(end);
m.OpReturnValue(m.OpLoad(t.u32x2, result));
m.OpFunctionEnd();
return fn;
}
for (uint32_t row = 0; row < 2; ++row) {
const Id c = unpack(inputs[6 + row]);
for (uint32_t col = 0; col < 2; ++col) m.OpStore(accumulators[row * 2 + col], m.OpCompositeExtract(f32ty, c, col));
}
m.OpStore(counter, imm(0));
read_lane();
const Id header = m.OpLabel(), body = m.OpLabel(), next = m.OpLabel(), end = m.OpLabel();
m.OpBranch(header);
m.AddLabel(header);
const Id pair = m.OpLoad(u32ty, counter);
const Id more = m.OpULessThan(t.boolean, pair, imm(8));
m.OpLoopMerge(end, next, spv::LoopControlMask::DontUnroll);
m.OpBranchConditional(more, body, end);
m.AddLabel(body);
const Id upper = m.OpUGreaterThanEqual(t.boolean, pair, imm(4));
const Id component = and_(pair, 3);
const Id a_lane = add(warp_base, add(row_base, component));
const Id b_lane = add(warp_base, add(col_base, component));
const Id b = m.OpSelect(u32ty, upper, inputs[5], inputs[4]);
std::array<Id, 2> bs;
for (uint32_t col = 0; col < 2; ++col)
bs[col] = unpack(m.OpGroupNonUniformShuffle(u32ty, subgroup(), b, add(b_lane, imm(col * 4))));
const Id round_now = m.OpIEqual(t.boolean, component, imm(3));
for (uint32_t row = 0; row < 2; ++row) {
const Id a = m.OpSelect(u32ty, upper, inputs[row + 2], inputs[row]);
const Id as = unpack(m.OpGroupNonUniformShuffle(u32ty, subgroup(), a, a_lane));
for (uint32_t col = 0; col < 2; ++col)
m.OpStore(accumulators[row * 2 + col], multiply_add(m.OpLoad(f32ty, accumulators[row * 2 + col]), as, bs[col]));
}
// HMMA.F16 rounds after each K=8 group, including the midpoint of K=16.
// OpSelect evaluates both operands: keep the expensive half conversion in
// a branch so the other three pairs do no rounding work. The counter is
// identical in every participating lane and all shuffles precede this branch.
const Id round_block = m.OpLabel(), round_merge = m.OpLabel();
m.OpSelectionMerge(round_merge, spv::SelectionControlMask::DontFlatten);
m.OpBranchConditional(round_now, round_block, round_merge);
m.AddLabel(round_block);
for (const Id accumulator : accumulators) m.OpStore(accumulator, round_half(m.OpLoad(f32ty, accumulator)));
m.OpBranch(round_merge);
m.AddLabel(round_merge);
m.OpBranch(next);
m.AddLabel(next);
m.OpStore(counter, add(pair, imm(1)));
m.OpBranch(header);
m.AddLabel(end);
std::array<Id, 2> packed;
for (uint32_t row = 0; row < 2; ++row)
packed[row] = m.OpPackHalf2x16(u32ty, m.OpCompositeConstruct(t.f32x2, m.OpLoad(f32ty, accumulators[row * 2]),
m.OpLoad(f32ty, accumulators[row * 2 + 1])));
m.OpReturnValue(m.OpCompositeConstruct(t.u32x2, packed[0], packed[1]));
m.OpFunctionEnd();
return fn;
}
} // namespace Shader::Backend::SPIRV

View File

@@ -6,6 +6,8 @@
#include <algorithm>
#include <map>
#include <utility>
#include <unordered_set>
#include <array>
#include <bit>
#include <climits>
@@ -476,6 +478,45 @@ Id CasLoop(EmitContext& ctx, Operation operation, Id array_pointer, Id element_p
return func;
}
// Admit one active invocation per subgroup to the CAS loop at a time. Each invocation
// still adds its own value and receives its own old value, including on overflow.
Id SubgroupCasLoop(EmitContext& ctx, Id cas_func, Id array_pointer) {
const Id subgroup{ctx.Const(static_cast<u32>(spv::Scope::Subgroup))};
const Id func_type{ctx.TypeFunction(ctx.F32[1], ctx.U32[1], ctx.F32[1], array_pointer)};
const Id func{ctx.OpFunction(ctx.F32[1], spv::FunctionControlMask::MaskNone, func_type)};
const Id index{ctx.OpFunctionParameter(ctx.U32[1])};
const Id value{ctx.OpFunctionParameter(ctx.F32[1])};
const Id base{ctx.OpFunctionParameter(array_pointer)};
ctx.AddLabel();
const Id result{ctx.AddLocalVariable(ctx.TypePointer(spv::StorageClass::Function, ctx.F32[1]),
spv::StorageClass::Function)};
const Id header{ctx.OpLabel()};
const Id selected{ctx.OpLabel()};
const Id selection_end{ctx.OpLabel()};
const Id next{ctx.OpLabel()};
const Id merge{ctx.OpLabel()};
ctx.OpBranch(header);
ctx.AddLabel(header);
ctx.OpLoopMerge(merge, next, spv::LoopControlMask::MaskNone);
const Id elect_block{ctx.OpLabel()};
ctx.OpBranch(elect_block);
ctx.AddLabel(elect_block);
const Id elected{ctx.OpGroupNonUniformElect(ctx.U1, subgroup)};
ctx.OpSelectionMerge(selection_end, spv::SelectionControlMask::MaskNone);
ctx.OpBranchConditional(elected, selected, selection_end);
ctx.AddLabel(selected);
ctx.OpStore(result, ctx.OpFunctionCall(ctx.F32[1], cas_func, index, value, base));
ctx.OpBranch(selection_end);
ctx.AddLabel(selection_end);
ctx.OpBranch(next);
ctx.AddLabel(next);
ctx.OpBranchConditional(elected, merge, header);
ctx.AddLabel(merge);
ctx.OpReturnValue(ctx.OpLoad(ctx.F32[1], result));
ctx.OpFunctionEnd();
return func;
}
template <typename Desc>
std::string NameOf(Stage stage, const Desc& desc, std::string_view prefix) {
if (desc.count > 1) {
@@ -487,6 +528,10 @@ std::string NameOf(Stage stage, const Desc& desc, std::string_view prefix) {
}
}
// (Triforce) Textures, texture buffers, image buffers and images alike: a descriptor of count above 1 is an array of count,
// the descriptors the renderer writes to its binding (vk_draw.cpp, ensure_layout), indexed with an OpAccessChain to an element
// (pointer_type). Texture buffers were refused ("Array of texture buffers") and image buffers and images declared one image,
// which that OpAccessChain cannot index (invalid SPIR-V). With a count of 1 the declaration is what it was.
Id DescType(EmitContext& ctx, Id sampled_type, Id pointer_type, u32 count) {
if (count > 1) {
const Id array_type{ctx.TypeArray(sampled_type, ctx.Const(count))};
@@ -532,7 +577,16 @@ EmitContext::EmitContext(const Profile& profile_, const RuntimeInfo& runtime_inf
}
DefineCommonTypes(program.info);
DefineCommonConstants();
PlanSharedWarp(program); // (Triforce: before the inputs, which a stage on the shared warp declares none of the subgroup's)
DefineInterfaces(program);
// (Triforce, mma_layout.h graphics_table_loads) a native task or mesh stage's global loads read the guest page table, as the
// other stages' do (DefineGlobalMemoryFunctions table_stage): its push block holds the table's address, so the member is
// wanted before any block is made (RX_VK_MESH_FIRST's below makes one)
if ((stage == Stage::Task || stage == Stage::Mesh) && !runtime_info.mesh_fallback && graphics_table_loads != 0 &&
program.info.uses_global_memory && profile.support_int64 && profile.unified_descriptor_binding &&
profile.supported_spirv >= 0x00010400) {
wants_guest_pages = true;
}
// (RX_VK_MESH_FIRST=1, with RX_VK_MESH_ARGS=1: off, one task program with it hung or ended the game at its first draw)
if (stage == Stage::Task && !runtime_info.mesh_fallback && getenv("RX_VK_MESH_FIRST") &&
profile.unified_descriptor_binding && profile.support_int64) {
@@ -1093,9 +1147,14 @@ void EmitContext::DefineWriteStorageCasLoopFunction(const Info& info) {
constexpr unsigned long long kGuestPagesBase = 0x1000000000ull;
constexpr unsigned long long kGuestPagesBytes = 8ull << 30;
// (a second window, its entries after the first's: the pools the game's GPU allocator puts at 0x7fxxxxxxxx, where its storage
// buffers are. Pointers there read 0 with the first alone)
// buffers are. Pointers there read 0 with the first alone. (Triforce) Kept at 4 GB from 508 GB: a wider one changes what every
// GPU's compute stages read through it; the pool census (page_table_census.h) logs the pools outside it)
constexpr unsigned long long kGuestPagesBase2 = 0x7f00000000ull;
constexpr unsigned long long kGuestPagesBytes2 = 4ull << 30;
// (and a third, after the second's: NVN's virtual pools from 1 TB (nvn_native.c VBASE), their entries the memory behind each
// virtual page, written where a storage buffer there is bound (vk_memory.cpp memory_table_cover))
constexpr unsigned long long kGuestPagesBase3 = 0x10000000000ull;
constexpr unsigned long long kGuestPagesBytes3 = 4ull << 30;
void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
if (!info.uses_global_memory || !profile.support_int64) {
@@ -1118,8 +1177,12 @@ void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
const bool graphics_stage{stage == Stage::VertexB || stage == Stage::Fragment};
const bool follow_pointers{(stage == Stage::Compute || (!no_mesh && (stage == Stage::Task || stage == Stage::Mesh)) ||
(graphics && graphics_stage && !info.uses_render_area)) && !no_follow};
// (Triforce) a native task or mesh stage with the page table's member wanted (the constructor): addresses, and the push block
// that holds the table's, for its loads through the table (table_stage below). Its searches are left as they were: no
// follow_pointers fallback for its stores
const bool native_mesh_table{(stage == Stage::Task || stage == Stage::Mesh) && !mesh_fallback && wants_guest_pages};
Id ptr_u64{};
if (follow_pointers) {
if (follow_pointers || native_mesh_table) {
wants_guest_pages = true;
if (profile.unified_descriptor_binding && rescaling_push_constants.value == 0) DefineRescalingInputPushConstant(); // (the table's address is in it)
AddCapability(spv::Capability::PhysicalStorageBufferAddresses);
@@ -1157,23 +1220,44 @@ void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
// and must end that block (a return). Falls through after it)
// (RX_VK_FOLLOW_STORES=1: writes and atomics through the table too; off by default, see the storage buffer pass)
static const bool follow_stores{getenv("RX_VK_FOLLOW_STORES") != nullptr};
// (hookshot) size: the access's bytes. An access that runs past its 4 KB page is left to the miss path: the table maps pages one
// (Triforce, mma_layout.h graphics_table_loads) a vertex, fragment or compute stage that has the table, the task and mesh
// stages, native and the mesh fallback's: its loads through it alone (1), or the search kept and checked against it (2, not
// the fallback's task and mesh stages: the miss log's buffer is not theirs). Not where the render area's push block leaves
// no table (follow_pointers). A native task or mesh stage inlines its load helpers (, define_load): with the search,
// every bound storage buffer's range tested at every load
const bool table_stage{graphics_stage || stage == Stage::Compute || stage == Stage::Task || stage == Stage::Mesh};
const bool graphics_table{graphics_table_loads != 0 && table_stage && wants_guest_pages &&
rescaling_push_constants.value != 0 && profile.supported_spirv >= 0x00010400};
const bool table_alone{graphics_table && graphics_table_loads == 1};
const bool table_check{graphics_table && graphics_table_loads == 2 &&
!(mesh_fallback && (stage == Stage::Task || stage == Stage::Mesh))};
// (Triforce) size: the access's bytes. An access that runs past its 4 KB page is left to the miss path: the table maps pages one
// by one, the next page may be another allocation's or none, and a 16-byte read at a page's end faulted the device (the culling
// passes 53caac5f, b6122162 at a save's load)
// (Triforce) where an address's entry is in the table: inside one of its windows (page_table_census.h kPageWindows), its page
// numbered after the windows before it
const auto table_window = [&](Id addr) {
const Id offset_a{OpISub(U64, addr, Constant(U64, u64{kGuestPagesBase}))};
const Id offset_b{OpISub(U64, addr, Constant(U64, u64{kGuestPagesBase2}))};
const Id offset_c{OpISub(U64, addr, Constant(U64, u64{kGuestPagesBase3}))};
const Id in_a{OpULessThan(U1, offset_a, Constant(U64, u64{kGuestPagesBytes}))};
const Id in_b{OpULessThan(U1, offset_b, Constant(U64, u64{kGuestPagesBytes2}))};
const Id in_c{OpULessThan(U1, offset_c, Constant(U64, u64{kGuestPagesBytes3}))};
const Id page_c{OpIAdd(U64, OpShiftRightLogical(U64, offset_c, Const(12U)),
Constant(U64, u64{(kGuestPagesBytes + kGuestPagesBytes2) >> 12}))};
const Id page_b{OpIAdd(U64, OpShiftRightLogical(U64, offset_b, Const(12U)), Constant(U64, u64{kGuestPagesBytes >> 12}))};
const Id page_index{OpSelect(U64, in_a, OpShiftRightLogical(U64, offset_a, Const(12U)), OpSelect(U64, in_b, page_b, page_c))};
return std::pair{OpLogicalOr(U1, in_a, OpLogicalOr(U1, in_b, in_c)), page_index};
};
const auto guest_lookup = [&](Id addr, u32 size, auto&& hit) {
if (!follow_pointers || gp_level < 2) return;
const Id table{wants_guest_pages && rescaling_push_constants.value != 0
? OpLoad(U64, OpAccessChain(TypePointer(spv::StorageClass::PushConstant, U64), rescaling_push_constants,
Const(guest_pages_member_index)))
: Constant(U64, u64{0})}; // (pushed: the table's device address, 0 for none)
const Id offset_a{OpISub(U64, addr, Constant(U64, u64{kGuestPagesBase}))};
const Id offset_b{OpISub(U64, addr, Constant(U64, u64{kGuestPagesBase2}))};
const Id in_a{OpULessThan(U1, offset_a, Constant(U64, u64{kGuestPagesBytes}))};
const Id in_b{OpULessThan(U1, offset_b, Constant(U64, u64{kGuestPagesBytes2}))};
const Id page_index{OpSelect(U64, in_a, OpShiftRightLogical(U64, offset_a, Const(12U)),
OpIAdd(U64, OpShiftRightLogical(U64, offset_b, Const(12U)), Constant(U64, u64{kGuestPagesBytes >> 12})))};
const auto [in_window, page_index] = table_window(addr);
const Id fits{OpULessThanEqual(U1, OpBitwiseAnd(U64, addr, Constant(U64, u64{0xfff})), Constant(U64, u64{0x1000 - size}))};
const Id inside{OpLogicalAnd(U1, OpLogicalAnd(U1, OpLogicalOr(U1, in_a, in_b), OpINotEqual(U1, table, Constant(U64, u64{0}))), fits)};
const Id inside{OpLogicalAnd(U1, OpLogicalAnd(U1, in_window, OpINotEqual(U1, table, Constant(U64, u64{0}))), fits)};
const Id then_label{OpLabel()};
const Id else_label{OpLabel()};
OpSelectionMerge(else_label, spv::SelectionControlMask::MaskNone);
@@ -1197,6 +1281,7 @@ void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
// (EvilOOT) the structure pointer type of a storage buffer of that member's elements, for OpArrayLength
const auto struct_pointer_of{[&](DefPtr m) -> Id {
if (m == &StorageDefinitions::U32) return storage_types.U32.array;
if (m == &StorageDefinitions::F32) return storage_types.F32.array; // (hookshot: the native float add's, as U32's)
if (m == &StorageDefinitions::U32x2) return storage_types.U32x2.array;
if (m == &StorageDefinitions::U32x4) return storage_types.U32x4.array;
return Id{};
@@ -1239,6 +1324,12 @@ void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
const auto define_body{[&](DefPtr ssbo_member, Id addr, Id element_pointer, u32 shift,
auto&& callback, bool add_label = true) {
if (add_label) AddLabel();
// (hookshot, global_table_loop: the tables' entries in a loop, its counter here, where the function's variables must be.
// The CAS loops' callers open the block themselves: theirs stay written out)
const Id table_counter{global_table_loop && add_label && !ssbo_tables.empty()
? AddLocalVariable(TypePointer(spv::StorageClass::Function, U32[1]), spv::StorageClass::Function)
: Id{}};
if (Sirit::ValidId(table_counter)) AddCapability(spv::Capability::StorageBufferArrayDynamicIndexing); // (the tables by k)
const size_t num_buffers{info.storage_buffers_descriptors.size()};
// (from Fritchii) Info::native_global_bounds: the candidate pointers the storage buffer pass bound for accesses it
// left global (any single descriptor not in the driver bank) carry no NVN size word: the address goes to the
@@ -1293,7 +1384,9 @@ void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
// nvn_buffer_used[index], took a descriptor's place in the list for an NVN slot number: with the tracked
// buffers first, the slots' own descriptors past them were skipped and their reads gave 0. A match is exact,
// so searching a buffer the access never falls in costs a comparison and nothing else.
if (info.storage_buffers_descriptors[index].count > 1) {
// ((Triforce) nor a simulated-turf list's own descriptor (ir_opt/sim_turf_pool_pass.h): its offset is no constant bank
// word, and the accesses that go to it name it)
if (info.storage_buffers_descriptors[index].count > 1 || IsSimTurfStorage(info.storage_buffers_descriptors[index])) {
continue;
}
const auto& ssbo{info.storage_buffers_descriptors[index]};
@@ -1336,6 +1429,58 @@ void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
if (!Sirit::ValidId(table_id) || !Sirit::ValidId(cbufs[table.cbuf_index].U32x2)) {
continue;
}
if (Sirit::ValidId(table_counter)) {
// (mma_layout.h global_table_loop) the same test as the written-out one below, entry k of the loop's counter, the
// driver asked not to unroll it. k is the same in every invocation that runs it: dynamic indexing, not non-uniform.
// The written-out form below is left as it was: other GPUs' SPIR-V, and their drivers' caches of it, do not change
const Id header{OpLabel()};
const Id check{OpLabel()};
const Id body{OpLabel()};
const Id next{OpLabel()};
const Id done{OpLabel()};
OpStore(table_counter, zero);
OpBranch(header);
AddLabel(header);
OpLoopMerge(done, next, spv::LoopControlMask::DontUnroll);
OpBranch(check);
AddLabel(check);
const Id k{OpLoad(U32[1], table_counter)};
OpBranchConditional(OpULessThan(U1, k, Const(table.count)), body, done);
AddLabel(body);
// (entry k at cbuf_offset + 16k: its address in the U32x2 word cbuf_offset / 8 + 2k, its size in the next)
const Id word{OpIAdd(U32[1], Const(table.cbuf_offset / 8), OpShiftLeftLogical(U32[1], k, Const(1U)))};
const Id entry_pointer{OpAccessChain(uniform_types.U32x2, cbufs[table.cbuf_index].U32x2, zero, word)};
const Id size_pointer{OpAccessChain(uniform_types.U32x2, cbufs[table.cbuf_index].U32x2, zero,
OpIAdd(U32[1], word, Const(1U)))};
const u64 ssbo_align_mask{~(profile.min_ssbo_alignment - 1U)};
const Id unaligned_addr{OpBitcast(U64, OpLoad(U32[2], entry_pointer))};
const Id ssbo_addr{OpBitwiseAnd(U64, unaligned_addr, Constant(U64, ssbo_align_mask))};
const Id size_word{OpCompositeExtract(U32[1], OpLoad(U32[2], size_pointer), 0U)};
Id ssbo_end{OpIAdd(U64, unaligned_addr, OpUConvert(U64, size_word))};
if (const Id struct_pointer{struct_pointer_of(ssbo_member)}; Sirit::ValidId(struct_pointer)) {
const Id elements{OpArrayLength(U32[1], OpAccessChain(struct_pointer, table_id, k), 0U)};
const Id bound_end{
OpIAdd(U64, ssbo_addr, OpUConvert(U64, OpShiftLeftLogical(U32[1], elements, Const(shift))))};
const Id capped{OpSelect(U64, OpULessThan(U1, bound_end, ssbo_end), bound_end, ssbo_end)};
ssbo_end = OpSelect(U64, OpIEqual(U1, size_word, zero), bound_end, capped);
}
const Id cond{OpLogicalAnd(U1, OpUGreaterThanEqual(U1, addr, ssbo_addr), OpULessThan(U1, addr, ssbo_end))};
const Id then_label{OpLabel()};
const Id else_label{OpLabel()};
OpSelectionMerge(else_label, spv::SelectionControlMask::MaskNone);
OpBranchConditional(cond, then_label, else_label);
AddLabel(then_label);
const Id ssbo_offset{OpUConvert(U32[1], OpISub(U64, addr, ssbo_addr))};
const Id ssbo_index{OpShiftRightLogical(U32[1], ssbo_offset, Const(shift))};
callback(OpAccessChain(element_pointer, table_id, k, zero, ssbo_index)); // (ends in a return)
AddLabel(else_label);
OpBranch(next);
AddLabel(next);
OpStore(table_counter, OpIAdd(U32[1], k, Const(1U)));
OpBranch(header);
AddLabel(done);
continue;
}
for (u32 k = 0; k < table.count; ++k) {
const u32 at{table.cbuf_offset + k * 16};
const Id entry_pointer{OpAccessChain(uniform_types.U32x2, cbufs[table.cbuf_index].U32x2, zero,
@@ -1370,9 +1515,34 @@ void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
AddLabel(else_label);
}
}
record_miss(addr); // (EvilOOT, RX_VK_MISS_LOG: here no buffer held the address)
if (!table_check) record_miss(addr); // (EvilOOT, RX_VK_MISS_LOG: here no buffer held the address. Checking, the buffer
// records the loads the table answers otherwise instead)
}};
// (hookshot) the helpers below are DontInline: inlined at each of a culling program's hundreds of global accesses, with EvilOOT's
// (Triforce, mma_layout.h mesh_fallback_pages) the mesh fallback's task and mesh stages: a load is the guest page table's word,
// 0 where it maps nothing, as the console's GPU reads memory. No branch and no search: a storage buffer bound below 1 TB is in a
// pool the table maps (vk_memory.cpp guest_pages_set), so the search found the same words (739acd67's 243 million loads,
// compared), and where it found none it answered 0 though the console reads the memory. A virtual pool's (from 1 TB,
// nvn_native.c VBASE) is not in the table: a load from one reads 0 here (none at Hyrule Castle). The stage is held to 32 lanes and at the register
// file's limit: what a load keeps alive is spilled, and a branch around it cost as much again (Iris Xe, Mesa 26.2). No test
// that the access stays in its page: the guest's loads are aligned to their size (16 bytes at most), so none crosses one.
// Stores and atomics keep the search
const bool fallback_pages{mesh_fallback_pages && mesh_fallback && (stage == Stage::Task || stage == Stage::Mesh) &&
wants_guest_pages && rescaling_push_constants.value != 0 &&
profile.supported_spirv >= 0x00010400}; // (a vector's OpSelect on one condition: SPIR-V 1.4)
const auto page_load = [&](Id type, Id addr) {
const Id table{OpLoad(U64, OpAccessChain(TypePointer(spv::StorageClass::PushConstant, U64), rescaling_push_constants,
Const(guest_pages_member_index)))};
const Id u64_zero{Constant(U64, u64{0})};
const auto [in_window, page_index] = table_window(addr);
const Id inside{OpLogicalAnd(U1, in_window, OpINotEqual(U1, table, u64_zero))};
// (outside the table's windows the table's own first word is read, and the answer is 0 all the same)
const Id slot{OpSelect(U64, inside, OpIAdd(U64, table, OpShiftLeftLogical(U64, page_index, Const(3U))), table)};
const Id page{psb_load(U64, slot, 8U)};
const Id mapped{OpLogicalAnd(U1, inside, OpINotEqual(U1, page, u64_zero))};
const Id target{OpSelect(U64, mapped, OpIAdd(U64, page, OpBitwiseAnd(U64, addr, Constant(U64, u64{0xfff}))), table)};
return OpSelect(type, mapped, psb_load(type, target, 4U), ConstantNull(type));
};
// (Triforce) the helpers below are DontInline: inlined at each of a culling program's hundreds of global accesses, with EvilOOT's
// fuller buffer search, NVIDIA's compiler took 41 s on 53caac5f and the driver reset. Lichii PR 408 found the same (161 s for 68 programs)
const auto define_load{[&](DefPtr ssbo_member, Id element_pointer, Id type, u32 shift) {
const Id function_type{TypeFunction(type, U64)};
@@ -1390,8 +1560,37 @@ void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
const Id func_id{OpFunction(type, inline_here ? spv::FunctionControlMask::Inline : spv::FunctionControlMask::DontInline,
function_type)};
const Id addr{OpFunctionParameter(U64)};
define_body(ssbo_member, addr, element_pointer, shift,
[&](Id ssbo_pointer) { OpReturnValue(OpLoad(type, ssbo_pointer)); });
if (fallback_pages || table_alone) {
AddLabel();
OpReturnValue(page_load(type, addr));
OpFunctionEnd();
return func_id;
}
define_body(ssbo_member, addr, element_pointer, shift, [&](Id ssbo_pointer) {
const Id value{OpLoad(type, ssbo_pointer)};
if (table_check) { // (the bound buffer's words against the table's, every component)
const Id from_table{page_load(type, addr)};
Id differ{};
const u32 components{shift == 2 ? 1U : shift == 3 ? 2U : 4U};
for (u32 i = 0; i < components; ++i) {
const Id a{components == 1 ? value : OpCompositeExtract(U32[1], value, i)};
const Id b{components == 1 ? from_table : OpCompositeExtract(U32[1], from_table, i)};
const Id x{OpBitwiseXor(U32[1], a, b)};
differ = i == 0 ? x : OpBitwiseOr(U32[1], differ, x);
}
// (the condition before the merge: OpSelectionMerge must come right before its branch, or RADV crashes)
const Id differs{OpINotEqual(U1, differ, zero)};
const Id then_label{OpLabel()};
const Id end_label{OpLabel()};
OpSelectionMerge(end_label, spv::SelectionControlMask::MaskNone);
OpBranchConditional(differs, then_label, end_label);
AddLabel(then_label);
record_miss(addr);
OpBranch(end_label);
AddLabel(end_label);
}
OpReturnValue(value);
});
guest_lookup(addr, 1U << shift, [&](Id target) {
if (gp_level >= 3) OpReturnValue(psb_load(type, target, 4U));
else OpReturnValue(ConstantNull(type));
@@ -1532,17 +1731,18 @@ void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
write_global_cas_loop_func = func;
}
// (hookshot) RED/ATOM.E.ADD.F32 at an address no buffer was tracked to: the 32-bit atomics' fallback, with the float
// sum made in a compare-exchange loop as the storage buffers' f32_add_cas does
// sum made in a compare-exchange loop as the storage buffers' f32_add_cas does, or the GPU's own float add where
// the storage buffers' adds are (native_f32_add: the f32 views, searched as the u32 ones)
if (info.stores_global_memory) {
const Id func_type{TypeFunction(F32[1], U64, F32[1])};
const Id func{OpFunction(F32[1], spv::FunctionControlMask::DontInline, func_type)};
const Id addr{OpFunctionParameter(U64)};
const Id value{OpFunctionParameter(F32[1])};
AddLabel();
const Id expected_var{AddLocalVariable(TypePointer(spv::StorageClass::Function, U32[1]),
spv::StorageClass::Function)};
const Id tries_var{AddLocalVariable(TypePointer(spv::StorageClass::Function, U32[1]),
spv::StorageClass::Function)};
const Id expected_var{native_f32_add ? Id{} : AddLocalVariable(TypePointer(spv::StorageClass::Function, U32[1]),
spv::StorageClass::Function)};
const Id tries_var{native_f32_add ? Id{} : AddLocalVariable(TypePointer(spv::StorageClass::Function, U32[1]),
spv::StorageClass::Function)};
const auto cas_loop{[&](Id pointer) {
OpStore(expected_var, OpLoad(U32[1], pointer, spv::MemoryAccessMask::Aligned, 4U));
OpStore(tries_var, u32_zero_value); // (a ceiling of attempts, as every compare-exchange loop has: #548)
@@ -1569,11 +1769,19 @@ void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
AddLabel(continue_label);
OpBranch(begin_label);
}};
define_body(&StorageDefinitions::U32, addr, storage_types.U32.element, 2,
[&](Id ssbo_pointer) { cas_loop(ssbo_pointer); }, false);
const auto native_add{[&](Id pointer) {
OpReturnValue(OpAtomicFAddEXT(F32[1], pointer, Const(static_cast<u32>(spv::Scope::Device)), u32_zero_value, value));
}};
if (native_f32_add) {
define_body(&StorageDefinitions::F32, addr, storage_types.F32.element, 2, native_add, false);
} else {
define_body(&StorageDefinitions::U32, addr, storage_types.U32.element, 2,
[&](Id ssbo_pointer) { cas_loop(ssbo_pointer); }, false);
}
if (follow_stores) guest_lookup(addr, 4U, [&](Id target) {
if (gp_level >= 3) cas_loop(psb_member(U32[1], target));
else OpReturnValue(ConstantNull(F32[1]));
if (gp_level < 3) OpReturnValue(ConstantNull(F32[1]));
else if (native_f32_add) native_add(psb_member(F32[1], target));
else cas_loop(psb_member(U32[1], target));
});
OpReturnValue(ConstantNull(F32[1]));
OpFunctionEnd();
@@ -1858,6 +2066,14 @@ void EmitContext::DefineConstantBufferIndirectFunctions(const Info& info) {
}
void EmitContext::DefineStorageBuffers(const Info& info, u32& binding) {
// (hookshot) RED/ATOM.ADD.F32 as the GPU's own float add where it has one, on an f32 view of the buffer: the
// compare-exchange loop gives up after CAS_LOOP_MAX_TRIES attempts, and an add that gives up is lost. Decided before
// the early return: DefineGlobalMemoryFunctions' fallback reads it too
native_f32_add = profile.support_float32_atomic_add && profile.support_descriptor_aliasing && info.uses_atomic_f32_add;
if (native_f32_add) {
AddExtension("SPV_EXT_shader_atomic_float_add");
AddCapability(spv::Capability::AtomicFloat32AddEXT);
}
if (info.storage_buffers_descriptors.empty()) {
return;
}
@@ -1866,6 +2082,9 @@ void EmitContext::DefineStorageBuffers(const Info& info, u32& binding) {
IR::Type used_types{profile.support_descriptor_aliasing ? info.used_storage_buffer_types
: IR::Type::U32};
used_types |= IR::Type::U32;
if (native_f32_add) {
used_types |= IR::Type::F32;
}
if (profile.support_int8 && profile.support_storage_buffer_8bit &&
True(used_types & IR::Type::U8)) {
DefineSsbos(*this, storage_types.U8, &StorageDefinitions::U8, info, binding, U8,
@@ -1918,9 +2137,14 @@ void EmitContext::DefineStorageBuffers(const Info& info, u32& binding) {
decrement_cas_ssbo = CasLoop(*this, Operation::Decrement, storage_types.U32.array,
storage_types.U32.element, U32[1], spv::Scope::Device);
}
if (info.uses_atomic_f32_add) {
if (info.uses_atomic_f32_add && !native_f32_add) {
f32_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
storage_types.U32.element, F32[1], spv::Scope::Device);
if (f32_add_subgroup && stage == Stage::Compute && !mesh_fallback && profile.supported_spirv >= 0x00010300 &&
profile.SupportsSubgroupStage(stage)) {
AddCapability(spv::Capability::GroupNonUniform);
f32_add_cas = SubgroupCasLoop(*this, f32_add_cas, storage_types.U32.array);
}
}
if (info.uses_atomic_f16x2_add) {
f16x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
@@ -1958,15 +2182,14 @@ void EmitContext::DefineTextureBuffers(const Info& info, u32& binding) {
const Id type{TypePointer(spv::StorageClass::UniformConstant, image_buffer_type)};
texture_buffers.reserve(info.texture_buffer_descriptors.size());
for (const TextureBufferDescriptor& desc : info.texture_buffer_descriptors) {
if (desc.count != 1) {
throw NotImplementedException("Array of texture buffers");
}
const Id id{AddGlobalVariable(type, spv::StorageClass::UniformConstant)};
const Id desc_type{DescType(*this, image_buffer_type, type, desc.count)};
const Id id{AddGlobalVariable(desc_type, spv::StorageClass::UniformConstant)};
Decorate(id, spv::Decoration::Binding, binding);
Decorate(id, spv::Decoration::DescriptorSet, 0U);
Name(id, NameOf(stage, desc, "texbuf"));
texture_buffers.push_back({
.id = id,
.pointer_type = type,
.count = desc.count,
});
if (profile.supported_spirv >= 0x00010400) {
@@ -1984,7 +2207,8 @@ void EmitContext::DefineImageBuffers(const Info& info, u32& binding) {
const Id image_type{
TypeImage(sampled_type, spv::Dim::Buffer, false, false, false, 2, format)};
const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
const Id desc_type{DescType(*this, image_type, pointer_type, desc.count)};
const Id id{AddGlobalVariable(desc_type, spv::StorageClass::UniformConstant)};
Decorate(id, spv::Decoration::Binding, binding);
Decorate(id, spv::Decoration::DescriptorSet, 0U);
Name(id, NameOf(stage, desc, "imgbuf"));
@@ -2039,7 +2263,8 @@ void EmitContext::DefineImages(const Info& info, u32& binding, u32& scaling_inde
const Id sampled_type{desc.is_integer ? U32[1] : F32[1]};
const Id image_type{ImageType(*this, desc, sampled_type)};
const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
const Id desc_type{DescType(*this, image_type, pointer_type, desc.count)};
const Id id{AddGlobalVariable(desc_type, spv::StorageClass::UniformConstant)};
Decorate(id, spv::Decoration::Binding, binding);
Decorate(id, spv::Decoration::DescriptorSet, 0U);
Name(id, NameOf(stage, desc, "img"));
@@ -2071,6 +2296,12 @@ void EmitContext::DefineInputs(const IR::Program& program) {
if (info.uses_workgroup_id) {
workgroup_id = DefineInput(*this, U32[3], false, spv::BuiltIn::WorkgroupId);
}
if (stage == Stage::Mesh && !runtime_info.mesh_fallback && profile.need_mesh_num_workgroups) {
// (Triforce, , as Lichii ) RADV before Mesa 26.2.5 (!45092) miscounted the mesh grid-size registers and
// emitted an invalid SET_SH_REG packet (reg_count == 0, RING_GFP_TIMEOUT on RDNA 3/4) when a native mesh shader
// did not read gl_NumWorkGroups
num_workgroups = DefineInput(*this, U32[3], false, spv::BuiltIn::NumWorkgroups);
}
if (info.uses_local_invocation_id) {
local_invocation_id = DefineInput(*this, U32[3], false, spv::BuiltIn::LocalInvocationId);
}
@@ -2090,7 +2321,9 @@ void EmitContext::DefineInputs(const IR::Program& program) {
if (info.uses_is_helper_invocation) {
is_helper_invocation = DefineInput(*this, U1, false, spv::BuiltIn::HelperInvocation);
}
if (info.uses_subgroup_mask && profile.SupportsSubgroupStage(stage)) {
// (Triforce: a stage on the shared warp reads none of the subgroup's inputs, and declares none; its check keeps them)
const bool subgroup_free{warp_shared && !warp_shared_check};
if (info.uses_subgroup_mask && profile.SupportsSubgroupStage(stage) && !subgroup_free) {
subgroup_mask_eq = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupEqMaskKHR);
subgroup_mask_lt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLtMaskKHR);
subgroup_mask_le = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLeMaskKHR);
@@ -2107,7 +2340,7 @@ void EmitContext::DefineInputs(const IR::Program& program) {
if ((info.uses_fswzadd || info.uses_subgroup_invocation_id || info.uses_subgroup_shuffles ||
(profile.warp_size_potentially_larger_than_guest &&
(info.uses_subgroup_vote || info.uses_subgroup_mask))) &&
profile.SupportsSubgroupStage(stage)) {
profile.SupportsSubgroupStage(stage) && !subgroup_free) {
AddCapability(spv::Capability::GroupNonUniform);
subgroup_local_invocation_id =
DefineInput(*this, U32[1], false, spv::BuiltIn::SubgroupLocalInvocationId);
@@ -2269,6 +2502,166 @@ void EmitContext::DefineInputs(const IR::Program& program) {
}
}
/// (Triforce, mma_layout.h mesh_fallback_shared_warp) Whether this fallback stage's warp can live in workgroup memory, and if so
/// how many words it takes. It can when the workgroup is one warp (32 threads), no ballot, vote or shuffle is in a loop (a
/// site's words serve one pass), nothing leaves the program inside an if (a lane that entered a region reaches its sites), and
/// nothing depends on the lanes running in one thread in program order: no quad or matrix operation, no subgroup barrier, no
/// read of the stage buffer's outputs. The ifs with a site inside become regions (emit_spirv_warp.cpp). Nothing is emitted
/// here: it runs before the stage's inputs are declared (DefineInputs), which depend on the answer.
void EmitContext::PlanSharedWarp(const IR::Program& program) {
// (one warp a workgroup: the lane is the invocation's x, so a workgroup of more than one row would be two warps on one set of words)
if (!runtime_info.mesh_fallback || (stage != Stage::Task && stage != Stage::Mesh) || !mesh_fallback_shared_warp ||
program.workgroup_size[0] != 32 || program.workgroup_size[1] != 1 || program.workgroup_size[2] != 1) {
return;
}
std::vector<const IR::Block*> open;
std::unordered_set<const IR::Block*> regions;
u32 loops{};
u32 words{};
for (const IR::AbstractSyntaxNode& node : program.syntax_list) {
switch (node.type) {
case IR::AbstractSyntaxNode::Type::Block:
for (const IR::Inst& inst : std::as_const(*node.data.block).Instructions()) {
u32 site{};
switch (inst.GetOpcode()) {
case IR::Opcode::SubgroupBallot:
case IR::Opcode::VoteAll:
case IR::Opcode::VoteAny:
case IR::Opcode::VoteEqual:
site = WARP_BALLOT_WORDS;
break;
case IR::Opcode::ShuffleIndex: {
const IR::Value lane{inst.Arg(1).Resolve()};
const IR::Value segment{inst.Arg(3).Resolve()};
site = lane.IsImmediate() && segment.IsImmediate() && segment.U32() == 0 ? WARP_BROADCAST_WORDS
: WARP_SHUFFLE_WORDS;
break;
}
case IR::Opcode::ShuffleUp:
case IR::Opcode::ShuffleDown:
case IR::Opcode::ShuffleButterfly:
site = WARP_SHUFFLE_WORDS;
break;
case IR::Opcode::QuadBroadcast:
case IR::Opcode::QuadSwap:
case IR::Opcode::FSwizzleAdd:
case IR::Opcode::MatrixMulAddF16:
case IR::Opcode::SubgroupBarrier:
case IR::Opcode::IsbeReadOutput:
return;
default:
break;
}
if (!site) {
continue;
}
if (loops) {
return;
}
words += site;
regions.insert(open.begin(), open.end());
}
break;
case IR::AbstractSyntaxNode::Type::If:
open.push_back(node.data.if_node.body);
break;
case IR::AbstractSyntaxNode::Type::EndIf:
if (open.empty()) {
return;
}
open.pop_back();
break;
case IR::AbstractSyntaxNode::Type::Loop:
++loops;
break;
case IR::AbstractSyntaxNode::Type::Repeat:
if (!loops) {
return;
}
--loops;
break;
case IR::AbstractSyntaxNode::Type::Break:
break;
case IR::AbstractSyntaxNode::Type::Return:
case IR::AbstractSyntaxNode::Type::Unreachable:
if (!open.empty() || loops) {
return;
}
break;
}
}
if (!open.empty() || loops) {
return;
}
warp_shared = true;
warp_shared_check = mesh_fallback_shared_warp_check;
warp_region_ifs = std::move(regions);
warp_word_count = (std::max)(words + WARP_REGION_WORDS * static_cast<u32>(warp_region_ifs.size()), 1U);
}
/// (Triforce, mma_layout.h mesh_fallback_shared_warp) The shared warp's words and the function that waits on them, for a stage
/// PlanSharedWarp took
void EmitContext::DefineSharedWarp() {
if (!warp_shared) {
return;
}
warp_word_pointer = TypePointer(spv::StorageClass::Workgroup, U32[1]);
// (its length a signed constant: Sirit gives back the type already made for the same words, and u32 arrays of that
// length made for a block (ResolutionInfo's u32[4]) carry an ArrayStride, which a Workgroup variable must not have)
warp_words = DefineVariable(*this, TypeArray(U32[1], SConst(static_cast<s32>(warp_word_count))), std::nullopt,
spv::StorageClass::Workgroup);
Name(warp_words, "warp_words");
// (the wait: until every one of `lanes` has its bit in the word. The lanes waited for are the region's, which reach the
// site as this one did; bounded all the same, as the pool's wait is, and a wait that gives up is counted past the records
// (emit_spirv.h WARP_COUNTER_WAITS: the host logs it, vk_draw.cpp fallback_warp_counters), since the ballot or shuffle
// after it may be wrong. A function: a block that calls it keeps its label, which later blocks' phis name)
const Id function_type{TypeFunction(void_id, U32[1], U32[1])};
warp_wait = OpFunction(void_id, spv::FunctionControlMask::MaskNone, function_type);
Name(warp_wait, "warp_wait");
const Id word{OpFunctionParameter(U32[1])};
const Id lanes{OpFunctionParameter(U32[1])};
AddLabel();
const Id waited{AddLocalVariable(TypePointer(spv::StorageClass::Function, U32[1]), spv::StorageClass::Function)};
const Id pointer{OpAccessChain(warp_word_pointer, warp_words, word)};
OpStore(waited, u32_zero_value);
const Id header{OpLabel()};
const Id body{OpLabel()};
const Id next{OpLabel()};
const Id done{OpLabel()};
OpBranch(header);
AddLabel(header);
OpLoopMerge(done, next, spv::LoopControlMask::DontUnroll);
OpBranch(body);
AddLabel(body);
const Id seen{OpAtomicLoad(U32[1], pointer, Const(static_cast<u32>(spv::Scope::Workgroup)), u32_zero_value)};
const Id count{OpLoad(U32[1], waited)};
const Id go{OpLogicalOr(U1, OpIEqual(U1, OpBitwiseAnd(U32[1], seen, lanes), lanes),
OpUGreaterThanEqual(U1, count, Const(WARP_WAIT)))};
OpBranchConditional(go, done, next);
AddLabel(next);
OpStore(waited, OpIAdd(U32[1], count, Const(1U)));
OpBranch(header);
AddLabel(done);
const Id gave_up{OpUGreaterThanEqual(U1, OpLoad(U32[1], waited), Const(WARP_WAIT))};
const Id counted{OpLabel()};
const Id end{OpLabel()};
OpSelectionMerge(end, spv::SelectionControlMask::MaskNone);
OpBranchConditional(gave_up, counted, end);
AddLabel(counted);
OpAtomicIAdd(U32[1], MeshFallbackWarpCounter(WARP_COUNTER_WAITS), Const(static_cast<u32>(spv::Scope::Device)), u32_zero_value,
Const(1U));
OpBranch(end);
AddLabel(end);
OpReturn();
OpFunctionEnd();
}
Id EmitContext::MeshFallbackWarpCounter(u32 counter) {
const Id records{OpLoad(U64, OpAccessChain(TypePointer(spv::StorageClass::PushConstant, U64), rescaling_push_constants,
Const(mesh_fallback_records_member_index)))};
return MeshFallbackWord(OpIAdd(U64, records, Constant(U64, MeshFallbackRecordsBytes() + counter)));
}
void EmitContext::DefineMesh(const IR::Program& program) {
if (stage != Stage::Task && stage != Stage::Mesh) {
return;
@@ -2280,6 +2673,7 @@ void EmitContext::DefineMesh(const IR::Program& program) {
}
mesh_info = program.mesh;
mesh_threads = program.workgroup_size[0];
DefineSharedWarp();
// The task's output region, which its mesh workgroups read as their input region.
const Id payload_type{TypeArray(U32[1], Const(mesh_info.payload_words))};
if (mesh_fallback) {
@@ -2318,9 +2712,15 @@ void EmitContext::DefineMesh(const IR::Program& program) {
// triangles over Kokiri's foliage and ground (as nxnative found: "primitive index bytes for every primitive block")
mesh_map_bytes = 4 + mesh_info.Corners() * Common::DivCeil(mesh_info.max_primitives, 32U) * 32;
mesh_shared_u32 = TypePointer(spv::StorageClass::Workgroup, U32[1]);
mesh_attributes = DefineVariable(*this, TypeArray(U32[1], Const(mesh_attribute_words)),
std::nullopt, spv::StorageClass::Workgroup);
Name(mesh_attributes, "isbe_attributes");
// (Triforce, mma_layout.h mesh_fallback_global_attributes) the region in a slot of the records buffer's pool, where it fits one
const u32 slot_bytes{(mesh_attribute_words * 4 + 255) & ~255U};
mesh_attributes_global = mesh_fallback && stage == Stage::Mesh && mesh_fallback_global_attributes &&
slot_bytes <= MESH_FALLBACK_POOL_SLOT_BYTES;
if (!mesh_attributes_global) {
mesh_attributes = DefineVariable(*this, TypeArray(U32[1], Const(mesh_attribute_words)),
std::nullopt, spv::StorageClass::Workgroup);
Name(mesh_attributes, "isbe_attributes");
}
mesh_map = DefineVariable(*this, TypeArray(U32[1], Const(mesh_map_bytes)), std::nullopt,
spv::StorageClass::Workgroup);
Name(mesh_map, "isbe_map");
@@ -2328,6 +2728,73 @@ void EmitContext::DefineMesh(const IR::Program& program) {
DefineVariable(*this, U32[1], std::nullopt, spv::StorageClass::Workgroup);
Name(mesh_primitive_count, "isbe_primitive_count");
if (mesh_attributes_global) {
mesh_attribute_slot_bytes = slot_bytes;
mesh_attribute_ticket_shared = DefineVariable(*this, U32[1], std::nullopt, spv::StorageClass::Workgroup);
Name(mesh_attribute_ticket_shared, "isbe_attribute_ticket");
// (thread 0 takes the next ticket, waits until the slot's holder a pool's length of tickets before has handed it on, and
// leaves the ticket in the workgroup word. In a function of its own: the prologue must not branch, its block is a phi
// predecessor of later ones. The holder started before, so it runs and hands the slot on; the wait is bounded all the
// same, as a hung GPU is worse than a wrong region: MESH_FALLBACK_POOL_WAIT reads. A wait that gives up shares the
// slot with its last holder, so it is counted past the records (emit_spirv.h WARP_COUNTER_POOL_WAITS: the host logs
// it, vk_draw.cpp fallback_warp_counters))
const Id function_type{TypeFunction(void_id, U32[1])};
mesh_attribute_claim = OpFunction(void_id, spv::FunctionControlMask::MaskNone, function_type);
Name(mesh_attribute_claim, "isbe_attribute_claim");
const Id local{OpFunctionParameter(U32[1])};
AddLabel();
const Id waited{AddLocalVariable(TypePointer(spv::StorageClass::Function, U32[1]), spv::StorageClass::Function)};
const Id records{OpLoad(U64, OpAccessChain(TypePointer(spv::StorageClass::PushConstant, U64), rescaling_push_constants,
Const(mesh_fallback_records_member_index)))};
const Id pool{OpIAdd(U64, records, Constant(U64, u64{MESH_FALLBACK_POOL_OFFSET}))};
const auto pool_word = [&](Id word) {
return MeshFallbackWord(OpIAdd(U64, pool, OpUConvert(U64, OpShiftLeftLogical(U32[1], word, Const(2U)))));
};
const Id device{Const(static_cast<u32>(spv::Scope::Device))};
const Id first_label{OpLabel()};
const Id end_label{OpLabel()};
const Id is_first{OpIEqual(U1, local, u32_zero_value)}; // (before the merge: it must stand right before its branch)
OpSelectionMerge(end_label, spv::SelectionControlMask::MaskNone);
OpBranchConditional(is_first, first_label, end_label);
AddLabel(first_label);
const Id ticket{OpAtomicIAdd(U32[1], pool_word(u32_zero_value), device, u32_zero_value, Const(1U))};
const Id slot{OpBitwiseAnd(U32[1], ticket, Const(MESH_FALLBACK_POOL_SLOTS - 1))};
const Id generation{OpShiftRightLogical(U32[1], ticket, Const(MESH_FALLBACK_POOL_SLOT_SHIFT))};
const Id slot_word{pool_word(OpIAdd(U32[1], slot, Const(1U)))};
OpStore(waited, u32_zero_value);
const Id header{OpLabel()};
const Id body{OpLabel()};
const Id next{OpLabel()};
const Id done{OpLabel()};
OpBranch(header);
AddLabel(header);
OpLoopMerge(done, next, spv::LoopControlMask::DontUnroll);
OpBranch(body);
AddLabel(body);
const Id seen{OpAtomicLoad(U32[1], slot_word, device, u32_zero_value)};
const Id count{OpLoad(U32[1], waited)};
const Id go{OpLogicalOr(U1, OpIEqual(U1, seen, generation), OpUGreaterThanEqual(U1, count, Const(MESH_FALLBACK_POOL_WAIT)))};
OpBranchConditional(go, done, next);
AddLabel(next);
OpStore(waited, OpIAdd(U32[1], count, Const(1U)));
OpBranch(header);
AddLabel(done);
const Id gave_up{OpUGreaterThanEqual(U1, OpLoad(U32[1], waited), Const(MESH_FALLBACK_POOL_WAIT))};
const Id counted{OpLabel()};
const Id told{OpLabel()};
OpSelectionMerge(told, spv::SelectionControlMask::MaskNone);
OpBranchConditional(gave_up, counted, told);
AddLabel(counted);
OpAtomicIAdd(U32[1], MeshFallbackWarpCounter(WARP_COUNTER_POOL_WAITS), device, u32_zero_value, Const(1U));
OpBranch(told);
AddLabel(told);
OpStore(mesh_attribute_ticket_shared, ticket);
OpBranch(end_label);
AddLabel(end_label);
OpReturn();
OpFunctionEnd();
}
if (mesh_fallback) {
return; // (no mesh outputs here: the epilogue writes records)
}

View File

@@ -6,6 +6,8 @@
#pragma once
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <sirit/sirit.h>
@@ -45,6 +47,7 @@ struct TextureDefinition {
struct TextureBufferDefinition {
Id id;
Id pointer_type;
u32 count;
};
@@ -261,13 +264,15 @@ public:
std::vector<ImageDefinition> images;
Id workgroup_id{};
Id num_workgroups{};
Id local_invocation_id{};
Id invocation_id{};
Id patch_vertices_in{};
Id sample_id{};
Id is_helper_invocation{};
Id subgroup_local_invocation_id{};
Id software_matrix_function{}; // (hookshot: emit_spirv_warp.cpp)
Id software_matrix_function{}; // (Triforce: emit_spirv_warp.cpp)
Id wmma16_function{}; // (Triforce: emit_spirv_warp.cpp DefineWmma16MatrixFunction)
Id subgroup_mask_eq{};
Id subgroup_mask_lt{};
Id subgroup_mask_le{};
@@ -334,6 +339,7 @@ public:
Id decrement_cas_shared{};
Id decrement_cas_ssbo{};
Id f32_add_cas{};
bool native_f32_add{}; // (hookshot) the float adds are OpAtomicFAddEXT, not f32_add_cas (DefineStorageBuffers)
Id f16x2_add_cas{};
Id f16x2_min_cas{};
Id f16x2_max_cas{};
@@ -402,7 +408,35 @@ public:
/// (hookshot) a fallback mesh workgroup's slot (task workgroup * threads + its index), read from the task's map in the
/// entry block (EmitMeshPrologue); invalid without a task program, where the slot is the workgroup id
Id mesh_fallback_slot{};
Id mesh_fallback_epilogue_word{}; ///< (Triforce) the fallback epilogue's loop index, a function variable of the entry block
Id mesh_fallback_epilogue_line{}; ///< (Triforce) the Soa records' line, WriteFallbackLines' inner loop index, as above
/// (Triforce, mma_layout.h mesh_fallback_global_attributes) the attribute region in a pool slot, not in workgroup memory: the
/// slot's bytes, the function that takes a ticket for it (thread 0, into the workgroup word), and in the entry block the
/// ticket and the region's device address (EmitMeshPrologue)
bool mesh_attributes_global{};
u32 mesh_attribute_slot_bytes{};
Id mesh_attribute_ticket_shared{};
Id mesh_attribute_claim{};
Id mesh_attribute_ticket{};
Id mesh_attribute_base{};
Id mesh_shared_u32{}; ///< pointer type to one workgroup word
/// (Triforce, mma_layout.h mesh_fallback_shared_warp) the warp in workgroup memory: the words (a region's entered and
/// reached lanes, a ballot's lanes and arrivals, a shuffle's values and arrivals), the function that waits for lanes'
/// bits in a word, this invocation's lane and bit (entry block), the lanes that run the block being emitted and those of
/// the ifs around it, and the ifs (by their body) with a ballot, vote or shuffle inside (PlanSharedWarp)
bool warp_shared{};
bool warp_shared_check{};
Id warp_words{};
Id warp_word_pointer{};
Id warp_wait{};
Id warp_lane{};
Id warp_bit{};
Id warp_region{};
std::vector<Id> warp_regions;
std::vector<bool> warp_region_opened; ///< each open if: whether it opened a region
u32 warp_word_count{};
u32 warp_word_next{};
std::unordered_set<const IR::Block*> warp_region_ifs;
Id mesh_primitive_indices{};
MeshInfo mesh_info{};
u32 mesh_threads{};
@@ -438,6 +472,8 @@ public:
Id capture_pointer{};
/// A pointer to the u32 at a PhysicalStorageBuffer device address
Id MeshFallbackWord(Id address);
/// (Triforce, mma_layout.h mesh_fallback_shared_warp) a pointer to one of the shared warp's counters past the records
Id MeshFallbackWarpCounter(u32 counter);
Id load_const_func_u8{};
Id load_const_func_u16{};
@@ -454,6 +490,28 @@ public:
bool uses_nonuniform_uniform_texel_buffer{};
bool uses_nonuniform_storage_texel_buffer{};
// (Triforce, AMD RDNA 3/3.5/4) Fused WMMA 16x16x16 N-pair, zero-C, quad-A, and K-chain state.
struct Wmma16Step {
enum class Kind : u8 { Skip, Single, Pair, PairZeroC, QuadZeroC, PairK2ZeroC };
Kind kind{Kind::Single};
IR::Inst* m0{};
IR::Inst* m1{};
IR::Inst* m2{};
IR::Inst* m3{};
std::vector<IR::Inst*> deferred_extracts;
};
struct Wmma16FusedState {
bool active{};
Id pair_fn{};
Id pair_zero_c_fn{};
Id quad_zero_c_fn{};
Id quad_ret_type{};
Id pair_k2_zero_c_fn{};
std::unordered_map<const IR::Inst*, Wmma16Step> steps;
std::unordered_set<const IR::Inst*> skip_insts;
};
Wmma16FusedState wmma16_fused{};
private:
void DefineCommonTypes(const Info& info);
void DefineCommonConstants();
@@ -479,6 +537,8 @@ private:
void DefineInputs(const IR::Program& program);
void DefineOutputs(const IR::Program& program);
void DefineMesh(const IR::Program& program);
void PlanSharedWarp(const IR::Program& program);
void DefineSharedWarp();
};
} // namespace Shader::Backend::SPIRV

View File

@@ -15,6 +15,7 @@
#include <vector>
#include "common/common_types.h"
#include "shader_recompiler/frontend/ampere/geometry_exit.h"
#include "shader_recompiler/frontend/ampere/program_address_map.h"
#include "shader_recompiler/frontend/ampere/register_pressure.h"
namespace Shader::Ampere {
@@ -104,13 +105,23 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
const u32 target = relocation.output_target != ~0U ? relocation.output_target :
result.source_instruction_offsets[static_cast<size_t>(relocation.target)];
const s64 relative = s64{address_of(target)} - address_of(relocation.output_index) - 8;
if (relative < -0x800000 || relative > 0x7fffff) return fail(index, "lowered branch distance");
result.instructions[relocation.output_index] |= (static_cast<u64>(relative) & 0xffffff) << 20;
u64& word = result.instructions[relocation.output_index];
if (relative < -0x800000 || relative > 0x7fffff) {
// ((Triforce) past the reach of BRA and CAL (a 24-bit offset, 8 MiB either way: about 786,000 lowered
// instructions): their absolute forms, JMP and JCAL, which hold the target's address in 32 bits (20-51;
// the frontend reads them so, IsAbsoluteJump). The predicate and the flow test stay as they are
const u64 op = word >> 52;
if (op != 0xe24 && op != 0xe26) return fail(index, "lowered branch distance");
word = (word & ~(u64{0xfff} << 52)) | (u64{op == 0xe24 ? 0xe21U : 0xe22U} << 52) |
(u64{address_of(target)} << 20);
continue;
}
word |= (static_cast<u64>(relative) & 0xffffff) << 20;
}
result.source_size = (index + 1) * sizeof(Instruction);
return result;
};
if (code.empty() || code.size() > 65536) return fail(0, "invalid native program size");
if (code.empty() || code.size() > MaximumNativeInstructions) return fail(0, "invalid native program size");
std::optional<GeometryExitEnvelope> geometry_exit;
if (code.front().Bits(0, 12) == 0x34e) {
if (!geometry_stage) return fail(0, "native program counter load outside geometry stage");
@@ -3823,11 +3834,14 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
const s64 relative = static_cast<s64>(raw << 14) >> 14;
if (s64{index} * 16 + 16 + relative != 0)
return fail(index, "native computed branch relative base");
const s64 offset = -s64{address_of(static_cast<u32>(result.instructions.size()))} - 8;
if (offset < -0x800000) return fail(index, "native computed branch range");
// ((Triforce) BRX goes to the table's value plus its own address plus its offset, which reaches back only 8 MiB
// (24 bits). Past that, JMX: the value plus the offset alone, -8 (the frontend's AnalyzeBRX adds the 8 back)
const s64 back = -s64{address_of(static_cast<u32>(result.instructions.size()))} - 8;
const bool absolute = back < -0x800000;
const s64 offset = absolute ? -8 : back;
const u32 source = opcode == 0x958 ? uniform_register(insn.Bits(24, 8)) : insn.Bits(24, 8);
if (source == ~0U) return fail(index, "native uniform computed branch source");
emit(0xe25000000000000fULL | predicate | (u64{source} << 8) |
emit((absolute ? 0xe20000000000000fULL : 0xe25000000000000fULL) | predicate | (u64{source} << 8) |
((static_cast<u64>(offset) & 0xffffff) << 20));
computed_branch = true;
break;
@@ -3928,7 +3942,17 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
if (target < 0 || target % 16) return fail(index, "native branch destination alignment");
relocations.push_back({static_cast<u32>(result.instructions.size()), target / 16});
emit(0xe24000000000000fULL | branch_predicate);
if (computed_branch && target == s64{index} * 16 && branch_predicate == (u64{7} << 16))
// ((Triforce) a loop that leaves only by predicated EXITs: the program ends at the closing self-branch after the
// loop's unconditional jump back, which nothing falls into (one of OoT's compute programs, its EXITs all @P0)
const auto unconditional_jump = [&](const Instruction& before) {
const u32 op = before.Bits(0, 12);
return before.Bits(12, 4) == 7 && ((op == 0x947 && before.Bits(87, 4) == 7) || op == 0x94d);
};
// (and only when no branch so far goes past it: code a branch reaches behind it is the program's still)
const bool after_jump = index > 0 && call_targets.empty() && unconditional_jump(code[index - 1]) &&
std::none_of(relocations.begin(), relocations.end(),
[&](const auto& r) { return r.target > s64{index}; });
if ((computed_branch || after_jump) && target == s64{index} * 16 && branch_predicate == (u64{7} << 16))
return finish(index); // the closing self-branch
break;
}
@@ -3963,7 +3987,9 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
const bool write = opcode == 0x927;
const u32 region = insn.Bits(76, 2);
const bool output = insn.Bits(79, 1) != 0;
if ((insn.words[2] & ~0xf800U) != 0 || (region != 0 && region != 3) || write != output ||
// ((Triforce) a read may be of the output region (.O): the program reading back what it wrote (one of OoT's
// task programs reads its payload so); a write is always to it
if ((insn.words[2] & ~0xf800U) != 0 || (region != 0 && region != 3) || (write && !output) ||
(!write && region != 3) || (!write && dest == 255))
return fail(index, "native stage buffer access mode");
emit(0xefc0000000000000ULL | predicate | (write ? u64{insn.Bits(32, 8)} : dest) |

View File

@@ -16,6 +16,7 @@
#include <string_view>
#include <vector>
#include "common/common_types.h"
#include "shader_recompiler/frontend/ampere/program_address_map.h" // ((Triforce) Shader::Ampere::MaximumNativeInstructions)
namespace Shader::AmpereRegmap {
@@ -166,13 +167,26 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
if (relocation.target > index) return fail(index, "native branch or call leaves captured program");
const u32 target = result.source_instruction_offsets[static_cast<size_t>(relocation.target)];
const s64 relative = s64{address_of(target)} - address_of(relocation.output_index) - 8;
if (relative < -0x800000 || relative > 0x7fffff) return fail(index, "lowered branch distance");
result.instructions[relocation.output_index] |= (static_cast<u64>(relative) & 0xffffff) << 20;
u64& word = result.instructions[relocation.output_index];
if (relative < -0x800000 || relative > 0x7fffff) {
// ((Triforce) past the reach of BRA and CAL (a 24-bit offset, 8 MiB either way: about 786,000 lowered
// instructions): their absolute forms, JMP and JCAL, which hold the target's address in 32 bits (20-51;
// the frontend reads them so, IsAbsoluteJump). The predicate and the flow test stay as they are
const u64 op = word >> 52;
if (op != 0xe24 && op != 0xe26) return fail(index, "lowered branch distance");
word = (word & ~(u64{0xfff} << 52)) | (u64{op == 0xe24 ? 0xe21U : 0xe22U} << 52) |
(u64{address_of(target)} << 20);
continue;
}
word |= (static_cast<u64>(relative) & 0xffffff) << 20;
}
result.source_size = (index + 1) * sizeof(Instruction);
return result;
};
if (code.empty() || code.size() > 65536) return fail(0, "invalid native program size");
if (code.empty() || code.size() > Shader::Ampere::MaximumNativeInstructions) return fail(0, "invalid native program size");
// ((Triforce) A shared memory store (STS) not yet followed by a barrier: an LDS after it may read what another lane of
// the warp stored (see LDS below)
bool shared_store_pending = false;
for (u32 index = 0; index < code.size(); ++index) {
auto insn = code[index];
result.source_instruction_offsets.push_back(static_cast<u32>(result.instructions.size()));
@@ -230,7 +244,11 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
opcode == 0x927 || opcode == 0xb9b || opcode == 0x59f || opcode == 0x983 ||
opcode == 0x98e || opcode == 0xb6c || opcode == 0x9a8 || (renameable & (1U << f));
if (reg >= 255 || reg + 3 < reserved_base) continue; // (a quad below may reach up)
if (register_field && reg >= reserved_base) any_high = true;
// A vector load can write reserved registers even when its first destination is below them.
const bool load_dest = f == 0 && (opcode == 0x381 || opcode == 0x981);
const u32 load_size = insn.Bits(73, 3);
const u32 width = load_dest && load_size == 6 ? 4U : load_dest && load_size == 5 ? 2U : 1U;
if (register_field && reg + width > reserved_base) any_high = true;
}
for (u32 f = 0; f < 4 && any_high; ++f) {
const u32 bit = bits[f], reg = insn.Bits(bit, 8);
@@ -1589,6 +1607,7 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
case 0xb1d: // BAR.SYNC 0 (bit 80: .DEFER_BLOCKING), full workgroup.
if (insn.words[1] || (insn.words[2] & ~0x10000U) || native_predicate != 7)
return fail(index, "native workgroup barrier mode");
shared_store_pending = false;
emit(0xf0a8000000000000ULL | predicate | (u64{1} << 43) |
(u64{1} << 44) | (u64{1} << 39) | (u64{7} << 39));
break;
@@ -1611,6 +1630,22 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
address = 250;
}
const u32 data = opcode == 0x388 ? insn.Bits(32, 8) : static_cast<u32>(dest);
// ((Triforce) A warp stores to shared memory (STS) and reads it back (LDS) with no barrier between: the Switch runs
// a warp's shared memory accesses in order, Vulkan orders another lane's store and this lane's load only through a
// barrier, and the driver's compiler may move them past each other (OoT's 4/3 gameplay network on NVIDIA's
// cooperative matrix path: 16x2 bright bars). As for LDSM, and as lower_to_maxwell.h has it: a subgroup barrier
// before the first LDS after an STS, only where the LDS is not predicated (every lane of the warp reaches it).
// RX_VK_SHARED_NO_LDS_BARRIER=1: none, as before
static const bool lds_barrier = [] {
const char* const e = std::getenv("RX_VK_SHARED_NO_LDS_BARRIER");
return !(e && *e && *e != '0');
}();
if (opcode == 0x388) {
shared_store_pending = true;
} else if (shared_store_pending && lds_barrier && native_predicate == 7) {
emit(0xef98000000000000ULL | predicate | (u64{1} << 20)); // (MEMBAR, bit 20: barrier_operations.cpp)
shared_store_pending = false;
}
emit((opcode == 0x388 ? 0xef58000000000000ULL : 0xef48000000000000ULL) |
predicate | data | (u64{address} << 8) | (u64{insn.Bits(40, 24)} << 20) |
(u64{width} << 48));
@@ -1723,9 +1758,12 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
return fail(index, "native matrix load mode");
u32 address = insn.Bits(24, 8);
const u64 offset = insn.Bits(40, 24);
// ((Triforce) An address the results overwrite is copied first, to R254: the paths below use R246-R253, and R253
// (the copy's old place) is where each matrix's row address is shuffled to, so matrices 1-3 of an .x2/.x4 shuffled
// matrix 0's address and read the wrong rows (as lower_to_maxwell.h has it: gpu/vk/tests/ldsm_address_test.cpp)
if (address != 255 && address >= dest && address < dest + count) {
emit(0x5c10000000000000ULL | predicate | 253 | (u64{address} << 8) | (u64{255} << 20));
address = 253;
emit(0x5c10000000000000ULL | predicate | 254 | (u64{address} << 8) | (u64{255} << 20));
address = 254;
}
// (hookshot) A warp stores its tiles (STS) and reads them back with LDSM, often with no BAR between: the Switch runs a
// warp's shared memory accesses in order, Vulkan orders another lane's store and this lane's load only through a
@@ -3275,11 +3313,14 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
const s64 relative = static_cast<s64>(raw << 14) >> 14;
if (s64{index} * 16 + 16 + relative != 0)
return fail(index, "native computed branch relative base");
const s64 offset = -s64{address_of(static_cast<u32>(result.instructions.size()))} - 8;
if (offset < -0x800000) return fail(index, "native computed branch range");
// ((Triforce) BRX goes to the table's value plus its own address plus its offset, which reaches back only 8 MiB
// (24 bits). Past that, JMX: the value plus the offset alone, -8 (the frontend's AnalyzeBRX adds the 8 back)
const s64 back = -s64{address_of(static_cast<u32>(result.instructions.size()))} - 8;
const bool absolute = back < -0x800000;
const s64 offset = absolute ? -8 : back;
const u32 source = opcode == 0x958 ? uniform_register(insn.Bits(24, 8)) : insn.Bits(24, 8);
if (source == ~0U) return fail(index, "native uniform computed branch source");
emit(0xe25000000000000fULL | predicate | (u64{source} << 8) |
emit((absolute ? 0xe20000000000000fULL : 0xe25000000000000fULL) | predicate | (u64{source} << 8) |
((static_cast<u64>(offset) & 0xffffff) << 20));
computed_branch = true;
break;
@@ -3406,7 +3447,17 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
if (target < 0 || target % 16) return fail(index, "native branch destination alignment");
relocations.push_back({static_cast<u32>(result.instructions.size()), target / 16});
emit(0xe24000000000000fULL | branch_predicate);
if (computed_branch && target == s64{index} * 16 && branch_predicate == (u64{7} << 16))
// ((Triforce) a loop that leaves only by predicated EXITs: the program ends at the closing self-branch after the
// loop's unconditional jump back, which nothing falls into (one of OoT's compute programs, its EXITs all @P0)
const auto unconditional_jump = [&](const Instruction& before) {
const u32 op = before.Bits(0, 12);
return before.Bits(12, 4) == 7 && ((op == 0x947 && before.Bits(87, 4) == 7) || op == 0x94d);
};
// (and only when no branch so far goes past it: code a branch reaches behind it is the program's still)
const bool after_jump = index > 0 && call_targets.empty() && unconditional_jump(code[index - 1]) &&
std::none_of(relocations.begin(), relocations.end(),
[&](const auto& r) { return r.target > s64{index}; });
if ((computed_branch || after_jump) && target == s64{index} * 16 && branch_predicate == (u64{7} << 16))
return finish(index); // the closing self-branch
break;
}
@@ -3419,7 +3470,9 @@ inline LoweredProgram LowerToMaxwellWith(std::span<const Instruction> code, u32
const bool write = opcode == 0x927;
const u32 region = insn.Bits(76, 2);
const bool output = insn.Bits(79, 1) != 0;
if ((insn.words[2] & ~0xf800U) != 0 || (region != 0 && region != 3) || write != output ||
// ((Triforce) a read may be of the output region (.O): the program reading back what it wrote (one of OoT's
// task programs reads its payload so); a write is always to it
if ((insn.words[2] & ~0xf800U) != 0 || (region != 0 && region != 3) || (write && !output) ||
(!write && region != 3) || (!write && dest == 255))
return fail(index, "native stage buffer access mode");
emit(0xefc0000000000000ULL | predicate | (write ? u64{insn.Bits(32, 8)} : dest) |

View File

@@ -8,6 +8,12 @@
namespace Shader::Ampere {
constexpr u64 NativeAddressMapMagic = 0x50414d4e4544454eULL;
// (Triforce) The most native instructions a program may have, for the capture, the lowering and this map: as many as fit
// in the largest code area the renderer reads (a control section whose area ends past 16 MiB is refused: stage_head,
// gpu/vk/vk_shader.cpp), 16 bytes each. The GPU has no instruction count of its own: Maxwell and Ampere address a program
// by a 32-bit offset in its program region, and an Ampere BRA's offset has 50 bits. (65,536, 1 MiB, refused compute
// program 79116b290d46542f, 0x104680 bytes of code, on every platform)
constexpr u32 MaximumNativeInstructions = (16u << 20) / 16;
inline bool HasNativeAddressMap(std::span<const u64> code) {
return code.size() >= 2 && code.back() == NativeAddressMapMagic;
}
@@ -20,7 +26,7 @@ inline void AppendNativeAddressMap(std::vector<u64>& code, std::span<const u32>
inline std::optional<u32> NativeProgramAddress(std::span<const u64> code, u32 address) {
if (!HasNativeAddressMap(code) || address % 16) return {};
const u64 count = code[code.size() - 2];
if (!count || count > 65536 || count + 2 > code.size() || address / 16 >= count) return {};
if (!count || count > MaximumNativeInstructions || count + 2 > code.size() || address / 16 >= count) return {};
const size_t start = code.size() - static_cast<size_t>(count) - 2;
const u64 target = code[start + address / 16];
if (target < 0x50 || target >= start * 8 || target % 8 || target % 32 == 0) return {};

View File

@@ -3,12 +3,14 @@
#pragma once
#include "shader_recompiler/frontend/ampere/lower_to_maxwell.h"
#include "shader_recompiler/frontend/ampere/program_address_map.h"
namespace Shader::Ampere {
class ProgramCaptureState {
public:
enum class Result { Continue, Complete, InvalidTarget };
static constexpr u32 MaximumInstructions = 65536;
// ((Triforce) a target past the largest program, program_address_map.h; it was 65,536 instructions, 1 MiB)
static constexpr u32 MaximumInstructions = MaximumNativeInstructions;
Result Observe(const Instruction& instruction, u32 index) {
const u32 opcode = instruction.Bits(0, 12);

View File

@@ -337,6 +337,10 @@ U32 IREmitter::IsbeRead(const U32& address) {
return Inst<U32>(Opcode::IsbeRead, address);
}
U32 IREmitter::IsbeReadOutput(const U32& address) {
return Inst<U32>(Opcode::IsbeReadOutput, address);
}
void IREmitter::IsbeWriteAttribute(const U32& address, const U32& value) {
Inst(Opcode::IsbeWriteAttribute, address, value);
}

View File

@@ -89,6 +89,7 @@ public:
void SetPatch(Patch patch, const F32& value);
[[nodiscard]] U32 IsbeRead(const U32& address);
[[nodiscard]] U32 IsbeReadOutput(const U32& address); // (hookshot) the output region read back
void IsbeWriteAttribute(const U32& address, const U32& value);
void IsbeWriteMapU8(const U32& address, const U32& value);
void IsbeWriteMapU32(const U32& address, const U32& value);

View File

@@ -10,7 +10,7 @@ namespace Shader::IR {
namespace Detail {
OpcodeMeta META_TABLE[542] = {
OpcodeMeta META_TABLE[NUM_OPCODES] = {
#define OPCODE(name_token, type_token, ...) \
{ \
.name{#name_token}, \
@@ -21,7 +21,7 @@ OpcodeMeta META_TABLE[542] = {
#undef OPCODE
};
u8 NUM_ARGS[542] = {
u8 NUM_ARGS[NUM_OPCODES] = {
#define OPCODE(name_token, type_token, ...) u8(CalculateNumArgsOf(Opcode::name_token)),
#include "opcodes.inc"
#undef OPCODE

View File

@@ -20,6 +20,7 @@ enum class Opcode {
#define OPCODE(name, ...) name,
#include "opcodes.inc"
#undef OPCODE
Count,
};
namespace Detail {
@@ -57,12 +58,13 @@ static constexpr Type F64x2{Type::F64x2};
static constexpr Type F64x3{Type::F64x3};
static constexpr Type F64x4{Type::F64x4};
extern OpcodeMeta META_TABLE[542];
inline constexpr size_t NUM_OPCODES = static_cast<size_t>(Opcode::Count);
extern OpcodeMeta META_TABLE[NUM_OPCODES];
constexpr size_t CalculateNumArgsOf(Opcode op) noexcept {
const auto& arg_types = META_TABLE[size_t(op)].arg_types;
return size_t(std::distance(arg_types.begin(), std::ranges::find(arg_types, Type::Void)));
}
extern u8 NUM_ARGS[542];
extern u8 NUM_ARGS[NUM_OPCODES];
} // namespace Detail
/// Get return type of an opcode

View File

@@ -50,6 +50,7 @@ OPCODE(SetAttributeIndexed, Void, U32,
OPCODE(GetPatch, F32, Patch, )
OPCODE(SetPatch, Void, Patch, F32, )
OPCODE(IsbeRead, U32, U32, )
OPCODE(IsbeReadOutput, U32, U32, )
OPCODE(IsbeWriteAttribute, Void, U32, U32, )
OPCODE(IsbeWriteMapU8, Void, U32, U32, )
OPCODE(IsbeWriteMapU32, Void, U32, U32, )
@@ -100,6 +101,7 @@ OPCODE(WriteGlobal64, Void, Opaq
OPCODE(WriteGlobal128, Void, Opaque, U32x4, )
// Storage buffer operations
OPCODE(StorageBufferLength, U32, U32, )
OPCODE(LoadStorageU8, U32, U32, U32, )
OPCODE(LoadStorageS8, U32, U32, U32, )
OPCODE(LoadStorageU16, U32, U32, U32, )

View File

@@ -127,7 +127,7 @@ void TranslatorVisitor::ISBERD(u64 insn) {
// nx2 pseudo instruction for the ISBERD/ISBEWR of Switch 2 task and mesh programs (see
// frontend/ampere/lower_to_maxwell.h). Addresses are linear bytes in the stage buffer: reads come
// from the input attribute region, writes go to the output attribute or map region.
// from the input attribute region (or with .O the output one, read back), writes go to the output attribute or map region.
void TranslatorVisitor::ISBE_nx2(u64 insn) {
union {
u64 raw;
@@ -136,6 +136,7 @@ void TranslatorVisitor::ISBE_nx2(u64 insn) {
BitField<20, 24, u64> offset;
BitField<44, 1, u64> is_32;
BitField<45, 1, u64> attribute;
BitField<47, 1, u64> output;
BitField<48, 1, u64> write;
} const isbe{insn};
@@ -145,7 +146,8 @@ void TranslatorVisitor::ISBE_nx2(u64 insn) {
}
const IR::U32 address{ir.IAdd(X(isbe.address_reg), ir.Imm32(static_cast<u32>(isbe.offset)))};
if (isbe.write == 0) {
X(isbe.reg, ir.IsbeRead(address));
// (hookshot) .O: the program reads back its own output region (a task's payload, a mesh's attributes)
X(isbe.reg, isbe.output != 0 ? ir.IsbeReadOutput(address) : ir.IsbeRead(address));
return;
}
const IR::U32 value{X(isbe.reg)};

View File

@@ -4,6 +4,7 @@
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <atomic>
#include <algorithm>
#include <array>
#include <bitset>
@@ -29,6 +30,7 @@ extern thread_local u32 g_nvn2_compute_ssbo_base;
extern thread_local u32 g_nvn2_compute_ssbo_count;
extern thread_local u32 g_nvn2_compute_layout_end;
extern thread_local bool g_nvn2_miss_log_this;
extern std::atomic<u32> g_table_check_unchecked;
}
namespace Shader::Maxwell {
@@ -196,8 +198,17 @@ void AddNVNStorageBuffers(IR::Program& program) {
static const bool miss_log{std::getenv("RX_VK_MISS_LOG") != nullptr && std::atoi(std::getenv("RX_VK_MISS_LOG")) != 0};
// (compute only: the driver crashed compiling a mesh program with it; and only the program vk_shader.cpp names when
// RX_VK_MISS_LOG_PROG is set: Optimization::g_nvn2_miss_log_this)
if (miss_log && (program.stage == Stage::Compute || program.stage == Stage::Mesh || program.stage == Stage::Task) &&
Optimization::g_nvn2_miss_log_this && descs.size() < Info::MAX_SSBOS) {
// (Triforce, RX_VK_GP_TABLE=2: the vertex, fragment, compute, task and mesh stages' loads checked against the page table record
// there too. The mesh fallback's task and mesh stages get the buffer as with the miss log, and leave it unused)
static const bool table_check{std::getenv("RX_VK_GP_TABLE") != nullptr && std::atoi(std::getenv("RX_VK_GP_TABLE")) == 2};
const bool graphics{program.stage == Stage::VertexB || program.stage == Stage::Fragment || program.stage == Stage::Compute ||
program.stage == Stage::Task || program.stage == Stage::Mesh};
if (table_check && graphics && program.info.uses_global_memory && descs.size() >= Info::MAX_SSBOS)
Optimization::g_table_check_unchecked.fetch_add(1, std::memory_order_relaxed); // (no room for the check's buffer)
if (((miss_log && (program.stage == Stage::Compute || program.stage == Stage::Mesh || program.stage == Stage::Task) &&
Optimization::g_nvn2_miss_log_this) ||
(table_check && graphics && program.info.uses_global_memory)) &&
descs.size() < Info::MAX_SSBOS) {
descs.push_back({
.cbuf_index = driver_cbuf,
.cbuf_offset = 0xff0U,

View File

@@ -4,6 +4,7 @@
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <atomic>
#include "common/alignment.h"
#include "shader_recompiler/environment.h"
#include "shader_recompiler/frontend/ir/modifiers.h"
@@ -984,6 +985,9 @@ thread_local u32 g_nvn2_compute_ssbo_count{16};
thread_local u32 g_nvn2_compute_layout_end{0};
/// (RX_VK_MISS_LOG: whether the program being translated gets the miss log; vk_shader.cpp sets it per program)
thread_local bool g_nvn2_miss_log_this{true};
/// (Triforce, RX_VK_GP_TABLE=2: vertex, fragment, compute, task and mesh programs with global loads whose storage buffers left no room for the
/// check's buffer: their loads are not checked, and vk_draw.cpp's check line counts them)
std::atomic<u32> g_table_check_unchecked{0};
/// (RX_VK_ALL_GLOBAL_PROGS=<key prefix>[,...], a test: the program's memory accesses all left global, none bound)
thread_local bool g_all_global_this{false};
thread_local bool g_gm_port_this{false}; // (hookshot: EDEN_NX2_GM_PORT_PROGS names the program being translated)

View File

@@ -0,0 +1,500 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// ((Triforce) simulated turf, 11-24) The large-scale simulated turf's lists moved into buffers of the renderer's own, so that
// area settings that ask for more turf (the Graphics tab's Simulated turf page, vk_menu.cpp; sim_turf_settings.h) do not
// overflow the game's fixed record storage. The Grass distance row (grass_distance.h) only changes the reach and fade of the
// separate short decorative blades and never binds these lists; flowers, shrubs and other foliage use other paths again.
//
// The game builds Hyrule Field's simulated turf on the GPU each frame: a compute program (d5a9475f2790532e) lists the blades in reach,
// 143360 at most, 8 bytes each; a second one (3de6d86ec7e6720e) sorts them into two pools of 138240 records of 48 bytes, which
// mesh programs draw. Past 2x, more blades are in reach than the lists hold: which ones make it in changes from frame to frame
// (the atomic counter's order), and whole turf patches come and go, even standing still. The lists are the game's own
// buffers, sized for its caps: raising a cap writes past them, over whatever comes next.
//
// So the records go to adaptive buffers of their own on the GPU. Each list's 64-byte header (its counters, the indirect
// arguments) stays where the game has it: the game resets it and the draws read their counts from it. Only the records move:
// - the producers' record writes go through a new storage descriptor, a "private" one: the back end binds a buffer of its own
// for it, found by the guest address the original descriptor names (vk_draw.cpp sim_turf_private_binding);
// - the readers' record loads go through another, which the back end binds to that buffer when there is one, and to the
// game's own otherwise;
// - every cap comes from the descriptor's runtime length, so allocation failure and live resize stay memory-safe.
// After a producer dispatch, the back end copies the stock-sized compatible window into the game's record storage. A reader
// variant this pass cannot patch therefore still sees a valid bounded list instead of records written only to the private one.
// The producers are found by key; the mesh readers by what they do (their keys mix in the draw's state: vk_shader.cpp mesh_key),
// including both cached phase-0 keys and all four observed phase-1 keys.
// Every edit is checked first; a program that does not look exactly as expected is left as it is.
#pragma once
#include <algorithm>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include "shader_recompiler/frontend/ir/basic_block.h"
#include "shader_recompiler/frontend/ir/program.h"
#include "shader_recompiler/frontend/ir/value.h"
#include "shader_recompiler/shader_info.h"
namespace Shader::Optimization {
inline constexpr u64 kSimTurfBladeKey = 0xd5a9475f2790532eULL; // the blade list's producer
inline constexpr u64 kSimTurfPoolKey = 0x3de6d86ec7e6720eULL; // the pools' producer, the blade list's reader
inline constexpr u64 kSimTurfBladeKeys[] = {kSimTurfBladeKey, 0xbdcc9ddf7ca7cabdULL};
inline constexpr u64 kSimTurfPoolKeys[] = {kSimTurfPoolKey, 0x64978274654e224cULL, 0x9a6fe9d7a7ce2007ULL,
0xb0cc49ac253104ccULL};
inline constexpr u32 kSimTurfBladeCap = 143360; // records of 8 bytes
inline constexpr u32 kSimTurfPoolCap = 138240; // records of 48 bytes
inline constexpr u32 kSimTurfListHeader = 64; // bytes before a list's records
namespace sim_turf_detail {
/// The constant-bank word an address's low half comes from: c0+offset, through GetCbufU32 or GetCbufU32x2's first half
inline std::optional<u32> CbufLo(IR::Value v) {
v = v.Resolve();
if (v.IsImmediate()) return std::nullopt;
const IR::Inst* inst = v.InstRecursive();
const auto c0_imm = [](const IR::Inst* g) -> std::optional<u32> {
const IR::Value bank = g->Arg(0).Resolve(), off = g->Arg(1).Resolve();
if (!bank.IsImmediate() || bank.U32() != 0 || !off.IsImmediate()) return std::nullopt;
return off.U32();
};
if (inst->GetOpcode() == IR::Opcode::GetCbufU32) return c0_imm(inst);
if (inst->GetOpcode() == IR::Opcode::CompositeExtractU32x2) {
const IR::Value idx = inst->Arg(1).Resolve();
const IR::Value g = inst->Arg(0).Resolve();
if (!idx.IsImmediate() || idx.U32() != 0 || g.IsImmediate()) return std::nullopt;
if (g.InstRecursive()->GetOpcode() == IR::Opcode::GetCbufU32x2) return c0_imm(g.InstRecursive());
}
return std::nullopt;
}
/// A storage access's offset, as the storage buffer pass writes it: ISub32(address low half, BitwiseAnd32(c0 word, mask)).
/// A header access's address is the c0 word plus constants; a record's anything else
struct Offset {
bool ok = false;
u32 orig = 0; // the descriptor's c0 offset the base comes from
u32 mask = 0;
bool header = false;
u32 header_at = 0;
};
inline Offset ClassifyOffset(IR::Value v) {
Offset o;
v = v.Resolve();
if (v.IsImmediate()) return o;
const IR::Inst* sub = v.InstRecursive();
if (sub->GetOpcode() != IR::Opcode::ISub32) return o;
const IR::Value m = sub->Arg(1).Resolve();
if (m.IsImmediate() || m.InstRecursive()->GetOpcode() != IR::Opcode::BitwiseAnd32) return o;
const IR::Inst* and_inst = m.InstRecursive();
const IR::Value mask = and_inst->Arg(1).Resolve();
const std::optional<u32> orig = CbufLo(and_inst->Arg(0));
if (!mask.IsImmediate() || !orig) return o;
IR::Value x = sub->Arg(0).Resolve();
u32 acc = 0;
while (!x.IsImmediate() && x.InstRecursive()->GetOpcode() == IR::Opcode::IAdd32 &&
x.InstRecursive()->Arg(1).Resolve().IsImmediate()) {
acc += x.InstRecursive()->Arg(1).Resolve().U32();
x = x.InstRecursive()->Arg(0).Resolve();
}
const std::optional<u32> lo = CbufLo(x);
o.ok = true, o.orig = *orig, o.mask = mask.U32();
o.header = lo && *lo == *orig;
o.header_at = o.header ? acc : 0;
return o;
}
enum class Kind { Load, Write, Atomic, Other };
inline Kind StorageKind(IR::Opcode op) {
switch (op) {
case IR::Opcode::LoadStorageU8: case IR::Opcode::LoadStorageS8: case IR::Opcode::LoadStorageU16:
case IR::Opcode::LoadStorageS16: case IR::Opcode::LoadStorage32: case IR::Opcode::LoadStorage64:
case IR::Opcode::LoadStorage128:
return Kind::Load;
case IR::Opcode::WriteStorageU8: case IR::Opcode::WriteStorageS8: case IR::Opcode::WriteStorageU16:
case IR::Opcode::WriteStorageS16: case IR::Opcode::WriteStorage32: case IR::Opcode::WriteStorage64:
case IR::Opcode::WriteStorage128:
return Kind::Write;
default:
break;
}
const std::string_view name{IR::NameOf(op)};
if (name.starts_with("StorageAtomic")) return Kind::Atomic;
return Kind::Other;
}
inline IR::Type StorageType(IR::Opcode op) {
switch (op) {
case IR::Opcode::LoadStorage64: case IR::Opcode::WriteStorage64: return IR::Type::U32x2;
case IR::Opcode::LoadStorage128: case IR::Opcode::WriteStorage128: return IR::Type::U32x4;
default: return IR::Type::U32;
}
}
/// What a program does through one storage binding
struct Binding {
std::vector<IR::Inst*> record_loads, record_writes;
std::vector<IR::Inst*> header_loads, header_atomics;
int header12_loads = 0;
bool odd = false; // an access of another form, or a record atomic, or another base
IR::Inst* umax = nullptr; // the header's group count (StorageAtomicUMax32 at +0)
};
inline std::vector<Binding> Bindings(IR::Program& program, const Info& info) {
std::vector<Binding> b(info.storage_buffers_descriptors.size());
for (IR::Block* block : program.blocks)
for (IR::Inst& inst : block->Instructions()) {
const Kind kind = StorageKind(inst.GetOpcode());
if (kind == Kind::Other) continue;
const IR::Value bv = inst.Arg(0).Resolve();
if (!bv.IsImmediate() || bv.U32() >= b.size()) {
for (Binding& x : b) x.odd = true; // (a binding not known here: touch nothing)
continue;
}
Binding& x = b[bv.U32()];
const Offset o = ClassifyOffset(inst.Arg(1));
if (!o.ok || o.orig != info.storage_buffers_descriptors[bv.U32()].cbuf_offset) {
x.odd = true;
continue;
}
if (o.header) {
if (kind == Kind::Load) {
x.header_loads.push_back(&inst);
if (o.header_at == 12 && inst.GetOpcode() == IR::Opcode::LoadStorage32) x.header12_loads++;
} else if (kind == Kind::Atomic) {
x.header_atomics.push_back(&inst);
if (inst.GetOpcode() == IR::Opcode::StorageAtomicUMax32 && o.header_at == 0) x.umax = &inst;
} else {
x.odd = true; // (a header write: not seen in these programs)
}
} else if (kind == Kind::Load) {
x.record_loads.push_back(&inst);
} else if (kind == Kind::Write) {
x.record_writes.push_back(&inst);
} else {
x.odd = true;
}
}
return b;
}
/// The instructions `Identity #imm` and `UMin32 x, #imm`, in program order
inline std::vector<IR::Inst*> Identities(IR::Program& program, u32 imm) {
std::vector<IR::Inst*> r;
for (IR::Block* block : program.blocks)
for (IR::Inst& inst : block->Instructions())
if (inst.GetOpcode() == IR::Opcode::Identity && inst.Arg(0).IsImmediate() && inst.Arg(0).U32() == imm)
r.push_back(&inst);
return r;
}
inline std::vector<IR::Inst*> UMins(IR::Program& program, u32 imm) {
std::vector<IR::Inst*> r;
for (IR::Block* block : program.blocks)
for (IR::Inst& inst : block->Instructions())
if (inst.GetOpcode() == IR::Opcode::UMin32 && inst.Arg(1).IsImmediate() && inst.Arg(1).U32() == imm) r.push_back(&inst);
return r;
}
/// Whether `from`'s value is computed from `target` (through at most `depth` instructions, not through a phi)
inline bool ComesFrom(IR::Value from, const IR::Inst* target, int depth, std::vector<const IR::Inst*>& seen) {
from = from.Resolve();
if (from.IsImmediate()) return false;
const IR::Inst* inst = from.InstRecursive();
if (inst == target) return true;
if (depth == 0 || inst->GetOpcode() == IR::Opcode::Phi) return false;
if (std::find(seen.begin(), seen.end(), inst) != seen.end()) return false;
seen.push_back(inst);
for (size_t i = 0; i < inst->NumArgs(); i++)
if (ComesFrom(inst->Arg(i), target, depth - 1, seen)) return true;
return false;
}
inline bool ComesFrom(IR::Value from, const IR::Inst* target, int depth) {
std::vector<const IR::Inst*> seen;
return ComesFrom(from, target, depth, seen);
}
/// Index of each instruction in program order
inline size_t OrderOf(IR::Program& program, const IR::Inst* target) {
size_t n = 0;
for (IR::Block* block : program.blocks)
for (IR::Inst& inst : block->Instructions()) {
if (&inst == target) return n;
n++;
}
return SIZE_MAX;
}
/// A new private descriptor (shader_info.h IsSimTurfStorage), before the tables (count > 1): the SPIR-V back end numbers its
/// single buffers by their place among the single ones (spirv_emit_context.cpp DefineSsbos), the IR by their place in the list,
/// which agree while the tables come last. Its index, or nullopt when the list is full or a binding past it is in use
inline std::optional<u32> AddPrivate(Info& info, u32 orig, bool pool, bool creator, u32 used_bindings) {
auto& descs = info.storage_buffers_descriptors;
if (descs.size() >= Info::MAX_SSBOS) return std::nullopt;
// ((Triforce) nor in a program with handle programs: those name storage buffers by their place in the list, which a
// descriptor put before the tables would move)
if (!info.handle_programs.empty()) return std::nullopt;
size_t at = 0;
while (at < descs.size() && descs[at].count <= 1) at++;
if (used_bindings > at) return std::nullopt;
descs.insert(descs.begin() + static_cast<std::ptrdiff_t>(at),
StorageBufferDescriptor{
.cbuf_index = 0,
.cbuf_offset = SimTurfStorageOffset(orig, pool, creator),
.count = 1,
.is_written = creator,
});
return static_cast<u32>(at);
}
inline u32 UsedBindings(IR::Program& program) {
u32 n = 0;
for (IR::Block* block : program.blocks)
for (IR::Inst& inst : block->Instructions())
if (StorageKind(inst.GetOpcode()) != Kind::Other && inst.Arg(0).IsImmediate()) n = std::max(n, inst.Arg(0).U32() + 1);
return n;
}
inline void Redirect(Info& info, const std::vector<IR::Inst*>& insts, u32 binding) {
for (IR::Inst* inst : insts) {
inst->SetArg(0, IR::Value{binding});
info.used_storage_buffer_types |= StorageType(inst->GetOpcode());
}
}
/// The number of complete records in a bound private descriptor. Its range includes the guest address's offset from the
/// storage-aligned base and the 64-byte header before the records; subtract both at run time. A fallback descriptor for the
/// game's own buffer therefore restores its real cap, while a renderer-owned descriptor reports exactly what was allocated.
inline IR::Value RuntimeCapacity(IR::Program& program, IR::Inst* before, u32 binding, u32 orig, u32 mask, u32 stride,
bool minus_one = false) {
IR::Block* owner = nullptr;
for (IR::Block* block : program.blocks)
for (IR::Inst& inst : block->Instructions())
if (&inst == before) owner = block;
if (!owner) return IR::Value{0u};
const IR::Block::iterator at = owner->Instructions().iterator_to(*before);
const auto add = [&](IR::Opcode op, std::initializer_list<IR::Value> args) -> IR::Value {
return IR::Value{&*owner->PrependNewInst(at, op, args)};
};
const IR::Value length = add(IR::Opcode::StorageBufferLength, {IR::Value{binding}});
const IR::Value low = add(IR::Opcode::GetCbufU32, {IR::Value{0u}, IR::Value{orig}});
const IR::Value unaligned = add(IR::Opcode::BitwiseAnd32, {low, IR::Value{~mask}});
const IR::Value prefix = add(IR::Opcode::IAdd32, {unaligned, IR::Value{kSimTurfListHeader}});
const IR::Value at_least_prefix = add(IR::Opcode::UMax32, {length, prefix});
const IR::Value bytes = add(IR::Opcode::ISub32, {at_least_prefix, prefix});
IR::Value cap = add(IR::Opcode::UDiv32, {bytes, IR::Value{stride}});
if (minus_one) {
cap = add(IR::Opcode::UMax32, {cap, IR::Value{1u}});
cap = add(IR::Opcode::ISub32, {cap, IR::Value{1u}});
}
program.info.used_storage_buffer_types |= IR::Type::U32;
return cap;
}
/// Phase 0: its two record writes go to a private list whose descriptor length supplies the cap.
inline std::string PatchBladeProducer(IR::Program& program) {
Info& info = program.info;
std::vector<Binding> b = Bindings(program, info);
int list = -1;
for (size_t i = 0; i < b.size(); i++)
if (!b[i].record_writes.empty()) {
if (list != -1) return "two bindings written";
list = static_cast<int>(i);
}
if (list < 0) return "no records written";
const Binding& x = b[list];
if (x.odd || x.record_writes.size() != 2 || !x.record_loads.empty() || !x.umax) return "the list's accesses are not as expected";
const std::vector<IR::Inst*> umin = UMins(program, kSimTurfBladeCap);
const std::vector<IR::Inst*> guards = Identities(program, kSimTurfBladeCap - 1);
if (umin.size() != 1 || guards.size() != 2) return "caps not as expected";
if (!ComesFrom(x.umax->Arg(2), umin[0], 16)) return "the group count does not come from the cap";
const Offset records = ClassifyOffset(x.record_writes[0]->Arg(1));
if (!records.ok) return "the list's record offset is not as expected";
const auto at = AddPrivate(info, info.storage_buffers_descriptors[list].cbuf_offset, false, true, UsedBindings(program));
if (!at) return "no room for a descriptor";
Redirect(info, x.record_writes, *at);
umin[0]->SetArg(1, RuntimeCapacity(program, umin[0], *at, records.orig, records.mask, 8));
for (IR::Inst* g : guards)
g->SetArg(0, RuntimeCapacity(program, g, *at, records.orig, records.mask, 8, true));
return {};
}
/// Phase 1 reads the blade list and writes two independent record pools (ten WriteGlobal operations through c0+0x60 and
/// c0+0x70). Both get private descriptors; their runtime lengths become independent caps, so only a saturated pool grows.
inline std::string PatchPoolProducer(IR::Program& program) {
Info& info = program.info;
const auto original_descs = info.storage_buffers_descriptors;
std::vector<Binding> b = Bindings(program, info);
int input = -1;
for (size_t i = 0; i < b.size(); i++)
if (!b[i].record_loads.empty()) {
if (input != -1) return "two bindings read";
input = static_cast<int>(i);
}
if (input < 0) return "no records read";
if (b[input].odd || !b[input].record_writes.empty() || !b[input].header_atomics.empty() || b[input].header12_loads != 1)
return "the blade list's accesses are not as expected";
// the pools: the bindings with header atomics, at c0+0x60 (pool 2) and c0+0x70 (pool 1)
int pool2 = -1, pool1 = -1;
for (size_t i = 0; i < b.size(); i++) {
const u32 off = info.storage_buffers_descriptors[i].cbuf_offset;
if (info.storage_buffers_descriptors[i].cbuf_index != 0 || info.storage_buffers_descriptors[i].count != 1) continue;
if (off == 0x60) pool2 = static_cast<int>(i);
if (off == 0x70) pool1 = static_cast<int>(i);
}
if (pool2 < 0 || pool1 < 0) return "pools not found";
const Binding& p2 = b[pool2];
const Binding& p1 = b[pool1];
if (p2.odd || !p2.record_loads.empty() || !p2.record_writes.empty() || !p2.umax) return "pool 2's header not as expected";
if (p1.odd || !p1.record_loads.empty() || !p1.record_writes.empty() || !p1.umax) return "pool 1's header not as expected";
// the mask the storage buffer pass took for pool 2's base
u32 mask = 0;
for (IR::Inst* a : p2.header_atomics) mask = ClassifyOffset(a->Arg(1)).mask;
if (!mask) return "no mask";
// pool 2's record writes: WriteGlobal through PackUint2x32(CompositeConstructU32x2(lo, hi)), lo = IAdd32(c0+0x60's low, x),
// two of the ten through IAdd64(that): `extra` is that constant
struct GlobalWrite {
IR::Block* block;
IR::Inst* inst;
IR::Value lo;
u32 extra;
};
std::vector<GlobalWrite> writes2, writes1;
int other_writes = 0;
for (IR::Block* block : program.blocks)
for (IR::Inst& inst : block->Instructions()) {
const IR::Opcode op = inst.GetOpcode();
if (op != IR::Opcode::WriteGlobal32 && op != IR::Opcode::WriteGlobal64) continue;
IR::Value a = inst.Arg(0).Resolve();
u32 extra = 0;
if (!a.IsImmediate() && a.InstRecursive()->GetOpcode() == IR::Opcode::IAdd64) {
const IR::Value k = a.InstRecursive()->Arg(1).Resolve();
if (k.IsImmediate() && k.Type() == IR::Type::U64 && k.U64() < 48) { // (inside one 48-byte record)
extra = static_cast<u32>(k.U64());
a = a.InstRecursive()->Arg(0).Resolve();
} else {
other_writes++;
continue;
}
}
std::optional<u32> base;
IR::Value lo;
if (!a.IsImmediate() && a.InstRecursive()->GetOpcode() == IR::Opcode::PackUint2x32) {
const IR::Value c = a.InstRecursive()->Arg(0).Resolve();
if (!c.IsImmediate() && c.InstRecursive()->GetOpcode() == IR::Opcode::CompositeConstructU32x2) {
lo = c.InstRecursive()->Arg(0).Resolve();
if (!lo.IsImmediate() && lo.InstRecursive()->GetOpcode() == IR::Opcode::IAdd32) {
base = CbufLo(lo.InstRecursive()->Arg(0));
if (!base) base = CbufLo(lo.InstRecursive()->Arg(1));
}
}
}
if (base && *base == 0x60) writes2.push_back({block, &inst, lo, extra});
else if (base && *base == 0x70) writes1.push_back({block, &inst, lo, extra});
else other_writes++;
}
if (writes2.size() != 10 || writes1.size() != 10 || other_writes != 0) return "pool writes not as expected";
// the caps: pool 2's UMin is the one its group count comes from; its guard the first of the two, before its writes
const std::vector<IR::Inst*> umin = UMins(program, kSimTurfPoolCap);
const std::vector<IR::Inst*> guards = Identities(program, kSimTurfPoolCap);
const std::vector<IR::Inst*> in_guards = Identities(program, kSimTurfBladeCap - 1);
if (umin.size() != 2 || guards.size() != 2 || in_guards.size() != 1) return "caps not as expected";
IR::Inst *umin2 = nullptr, *umin1 = nullptr;
int umin2_found = 0, umin1_found = 0;
for (IR::Inst* u : umin)
if (ComesFrom(p2.umax->Arg(2), u, 16)) umin2 = u, umin2_found++;
else if (ComesFrom(p1.umax->Arg(2), u, 16)) umin1 = u, umin1_found++;
if (umin2_found != 1 || umin1_found != 1 || umin1 == umin2) return "the pools' caps were not found independently";
size_t first2 = SIZE_MAX, last2 = 0, first1 = SIZE_MAX, last1 = 0;
for (const GlobalWrite& w : writes2) {
const size_t o = OrderOf(program, w.inst);
first2 = std::min(first2, o), last2 = std::max(last2, o);
}
for (const GlobalWrite& w : writes1) {
const size_t o = OrderOf(program, w.inst);
first1 = std::min(first1, o), last1 = std::max(last1, o);
}
const size_t g0 = OrderOf(program, guards[0]), g1 = OrderOf(program, guards[1]);
if (!(g0 < first2 && last2 < g1 && g1 < first1 && first1 <= last1)) return "the pools' guards are not where expected";
const u32 used = UsedBindings(program);
const Offset input_records = ClassifyOffset(b[input].record_loads[0]->Arg(1));
if (!input_records.ok) return "the blade list's record offset is not as expected";
const auto in_at = AddPrivate(info, info.storage_buffers_descriptors[input].cbuf_offset, false, false, used);
if (!in_at) return "no room for a descriptor";
const auto out2_at = AddPrivate(info, 0x60, true, true, used);
const auto out1_at = out2_at ? AddPrivate(info, 0x70, true, true, used) : std::nullopt;
if (!out2_at || !out1_at) return info.storage_buffers_descriptors = original_descs, "no room for descriptors";
Redirect(info, b[input].record_loads, *in_at);
const auto redirect_globals = [&](const std::vector<GlobalWrite>& writes, u32 orig, u32 binding) {
for (const GlobalWrite& w : writes) {
IR::Block* const block = w.block;
IR::Inst* const inst = w.inst;
const IR::Block::iterator it = block->Instructions().iterator_to(*inst);
const IR::Value lo = w.extra ? IR::Value{&*block->PrependNewInst(it, IR::Opcode::IAdd32, {w.lo, IR::Value{w.extra}})} : w.lo;
const auto word = block->PrependNewInst(it, IR::Opcode::GetCbufU32, {IR::Value{0u}, IR::Value{orig}});
const auto base = block->PrependNewInst(it, IR::Opcode::BitwiseAnd32, {IR::Value{&*word}, IR::Value{mask}});
const auto off = block->PrependNewInst(it, IR::Opcode::ISub32, {lo, IR::Value{&*base}});
const bool wide = inst->GetOpcode() == IR::Opcode::WriteGlobal64;
block->PrependNewInst(it, wide ? IR::Opcode::WriteStorage64 : IR::Opcode::WriteStorage32,
{IR::Value{binding}, IR::Value{&*off}, inst->Arg(1)});
info.used_storage_buffer_types |= wide ? IR::Type::U32x2 : IR::Type::U32;
inst->Invalidate();
}
};
redirect_globals(writes2, 0x60, *out2_at);
redirect_globals(writes1, 0x70, *out1_at);
umin2->SetArg(1, RuntimeCapacity(program, umin2, *out2_at, 0x60, mask, 48));
umin1->SetArg(1, RuntimeCapacity(program, umin1, *out1_at, 0x70, mask, 48));
guards[0]->SetArg(0, RuntimeCapacity(program, guards[0], *out2_at, 0x60, mask, 48));
guards[1]->SetArg(0, RuntimeCapacity(program, guards[1], *out1_at, 0x70, mask, 48));
in_guards[0]->SetArg(0, RuntimeCapacity(program, in_guards[0], *in_at, input_records.orig,
input_records.mask, 8, true));
return {};
}
/// A mesh program that draws a pool: its one guard `Identity #138240`, and one c0 binding read for a count (header +12) and
/// for records, nothing else. Its record loads from the private pool when there is one for the address
inline std::string PatchPoolReader(IR::Program& program) {
Info& info = program.info;
const std::vector<IR::Inst*> guards = Identities(program, kSimTurfPoolCap);
if (guards.size() != 1) return "no";
std::vector<Binding> b = Bindings(program, info);
int pool = -1;
for (size_t i = 0; i < b.size(); i++) {
const auto& d = info.storage_buffers_descriptors[i];
const Binding& x = b[i];
if (d.count != 1 || d.cbuf_index != 0 || IsSimTurfStorage(d) || x.odd) continue;
if (x.header12_loads != 1 || x.record_loads.empty() || !x.record_writes.empty() || !x.header_atomics.empty()) continue;
if (pool != -1) return "two pools read";
pool = static_cast<int>(i);
}
if (pool < 0) return "no";
const Offset records = ClassifyOffset(b[pool].record_loads[0]->Arg(1));
if (!records.ok) return "pool record offset not as expected";
const auto at = AddPrivate(info, info.storage_buffers_descriptors[pool].cbuf_offset, true, false, UsedBindings(program));
if (!at) return "no room for a descriptor";
Redirect(info, b[pool].record_loads, *at);
guards[0]->SetArg(0, RuntimeCapacity(program, guards[0], *at, records.orig, records.mask, 48));
return {};
}
} // namespace sim_turf_detail
/// The pass: for d5a9 and 3de6 by key (compute), for the mesh programs by what they do. "" when nothing was for this program,
/// else a line for the log: "made larger" or why it was left as it is
inline std::string SimTurfPools(IR::Program& program, u64 key) {
if (program.stage == Stage::Compute) {
if (std::find(std::begin(kSimTurfBladeKeys), std::end(kSimTurfBladeKeys), key) != std::end(kSimTurfBladeKeys)) {
const std::string why = sim_turf_detail::PatchBladeProducer(program);
return why.empty() ? "blade list made larger" : "blade list left as it is: " + why;
}
if (std::find(std::begin(kSimTurfPoolKeys), std::end(kSimTurfPoolKeys), key) != std::end(kSimTurfPoolKeys)) {
const std::string why = sim_turf_detail::PatchPoolProducer(program);
return why.empty() ? "both pools made larger" : "pools left as they are: " + why;
}
return {};
}
if (program.stage == Stage::Mesh) {
const std::string why = sim_turf_detail::PatchPoolReader(program);
if (why == "no") return {};
return why.empty() ? "pool reader made larger" : "pool reader left as it is: " + why;
}
return {};
}
} // namespace Shader::Optimization

View File

@@ -47,6 +47,9 @@ struct Profile {
bool support_typeless_image_loads{};
bool support_demote_to_helper_invocation{};
bool support_int64_atomics{};
/// (hookshot) float adds to storage buffers as one OpAtomicFAddEXT (VK_EXT_shader_atomic_float's
/// shaderBufferFloat32AtomicAdd), not a compare-exchange loop; with support_descriptor_aliasing only (an f32 view)
bool support_float32_atomic_add{};
bool support_shared_int64_atomics{};
bool support_derivative_control{};
bool support_geometry_shader_passthrough{};
@@ -105,6 +108,7 @@ struct Profile {
bool has_broken_spirv_subgroup_mask_vector_extract_dynamic{};
bool has_broken_spirv_subgroup_shuffle{};
bool has_broken_spirv_fragment_shuffle{}; // (Lichii #273: AMD's proprietary driver, fragment stages only)
bool need_mesh_num_workgroups{}; // (RADV before Mesa 26.2.5: reserve mesh grid-size registers)
u32 max_subgroup_size{};
u32 gl_max_compute_smem_size{};

View File

@@ -117,6 +117,9 @@ struct RuntimeInfo {
u32 mesh_fallback_task_threads{};
/// (hookshot) the fallback's record slots: mesh workgroups past this one write nothing
u32 mesh_fallback_capacity{};
/// (Triforce) how the fallback's mesh stage lays out its records and its vertex stage reads them
/// (Backend::SPIRV::MeshFallbackLayout, RX_VK_MESH_FB_LAYOUT); 0: record after record
u32 mesh_fallback_layout{};
/// (hookshot) a vertex stage that also stores its final position (clip space, after convert_depth_mode) at a pushed
/// device address, one vec4 a vertex: the temporal upscaler's motion of what the game moves in its shaders
/// (vk_temporal.cpp). A zero address stores nothing (Info::captures_position says it was emitted)

View File

@@ -179,6 +179,22 @@ struct StorageBufferDescriptor {
auto operator<=>(const StorageBufferDescriptor&) const = default;
};
/// ((Triforce) simulated turf, ir_opt/sim_turf_pool_pass.h) A storage descriptor the pass adds: the back end binds the turf list
/// at the guest address c0+(cbuf_offset & 0xffff) names, a buffer of the renderer's own (vk_draw.cpp sim_turf_private_binding)
/// or the game's own list. Bit 31 marks one (c0 holds 64 KiB: no real offset has it); bit 30: a pool of 48-byte records (else
/// the blade list of 8-byte ones); bit 29: the program that writes the records (else one that reads them)
inline constexpr u32 kSimTurfStorageBit = 0x80000000u, kSimTurfStoragePool = 0x40000000u, kSimTurfStorageCreator = 0x20000000u;
[[nodiscard]] constexpr u32 SimTurfStorageOffset(u32 orig, bool pool, bool creator) noexcept {
return kSimTurfStorageBit | (pool ? kSimTurfStoragePool : 0u) | (creator ? kSimTurfStorageCreator : 0u) | (orig & 0xffffu);
}
[[nodiscard]] constexpr bool IsSimTurfStorage(const StorageBufferDescriptor& d) noexcept {
return d.cbuf_index == 0 && d.count == 1 && (d.cbuf_offset & kSimTurfStorageBit) != 0;
}
/// The constant bank offset of the address (and size) words a storage descriptor's binding is read from
[[nodiscard]] constexpr u32 SimTurfStorageOrig(const StorageBufferDescriptor& d) noexcept {
return IsSimTurfStorage(d) ? d.cbuf_offset & 0xffffu : d.cbuf_offset;
}
struct TextureBufferDescriptor {
bool has_secondary;
u32 cbuf_index;